Springcloud簡單入門

Springcloud簡介

簡介

Spring Cloud是一系列框架的有序集合。它利用Spring Boot的開發便利性巧妙地簡化了分佈式系統基礎設施的開發,如服務發現註冊、配置中心、消息總線、負載均衡、斷路器、數據監控等,都可以用Spring Boot的開發風格做到一鍵啓動和部署。Spring Cloud並沒有重複製造輪子,它只是將目前各家公司開發的比較成熟、經得起實際考驗的服務框架組合起來,通過Spring Boot風格進行再封裝屏蔽掉了複雜的配置和實現原理,最終給開發者留出了一套簡單易懂、易部署和易維護的分佈式系統開發工具包。
詳細介紹: https://baike.so.com/doc/25751000-26884657.html
配套參考資料:
https://projects.spring.io/spring-cloud/ springcloud項目官方主頁

https://springcloud.cc/ springcloud中文網 有很詳細的翻譯文檔

http://springcloud.cn/ springcloud中文論壇

Springcloud版本pom文件生成可藉助網站:
https://start.spring.io/

原有的單體項目最終會被演化成下面

在這裏插入圖片描述
這樣的架構解決了單體項目幾點問題

  1. zuul網關解決了服務調用安全性的問題
  2. 服務註冊與發現(註冊中心)eureka解決了各層服務耦合問題,它是微服務架構的核心,有它才能將單體項目拆解成微服務架構
  3. Eureka集羣解決了微服務中,註冊中心宕機產生的問題
  4. Ribbon負載均衡及Feign消費者調用服務,減小了各微服務服務器的訪問壓力,默認採用了經典的輪詢機制
  5. 熔斷器Hystrix解決了,微服務架構中服務器雪崩現象
  6. 服務監控(單機Dashboard與集羣turbine),方便運維人員查看微服務架構項目運行時,各個服務器的運行狀態
  7. 服務配置中心(springcloud config),用來通過github統一管理各個微服務的配置文件(yml文件)

入門案例

最簡單的微服務架構會有四個工程
父工程:microservice
通用模塊(M):microservice-common
服務提供者(C):microservice-student-provider-1001
服務消費者(C):microservice-student-consumer-80

微服務架構注意點:
1、springboot、springcloud版本在父工程定義;
2、由於通用模塊無需操作數據庫,springboot啓動默認會讀取數據庫,所以得添加以下註解 @SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class});
3、分佈式jpa需要在啓動類上添加@EntityScan(“com.javaxl..”);
4、消費者需要添加配置類獲取org.springframework.web.client.RestTemplate,springcloud底層是通過RestTemplate來調用提供者的服務的。

創建父工程

父工程是一個maven項目,一般創建方式即可,父工程的主要用途是鎖定pom依賴包版本。由於springcloud2X停止更新,這裏我們採用穩定的低版本,配套的springboot版本爲1x版本。
Pom.xml配置如下

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.zh</groupId>
  <artifactId>springcloud</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>springcloud</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <druid.version>1.1.10</druid.version>
  </properties>


  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Edgware.SR4</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>1.5.13.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <!--  連接池  -->
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>${druid.version}</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

</project>

創建通用模塊microservice-common

通用模塊主要存放實體類、工具包等被整個微服務框架所使用的代碼。創建一個簡單的springboot模塊即可
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.zh</groupId>
        <artifactId>springcloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>microservice-common</artifactId>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

MicroserviceCommonApplication

package com.zh.microservicecommon;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MicroserviceCommonApplication {

    public static void main(String[] args) {
        SpringApplication.run(MicroserviceCommonApplication.class, args);
    }

}

Student

package com.zh.microservicecommon.entity;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name="t_springcloud_student")
public class Student implements Serializable {
 
    private static final long serialVersionUID = 1L;
 
    @Id
    @GeneratedValue
    private Integer id;
     
    @Column(length=50)
    private String name;
     
    @Column(length=50)
    private String grade;
     
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
}

創建服務提供者microservice-student-provider-1001

創建一個簡單的springboot模塊,這裏服務提供者需要操作數據庫並且被瀏覽器所訪問,固需要添加相關配置如下

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.zh</groupId>
        <artifactId>springcloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>microservice-student-provider-1001</artifactId>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.zh</groupId>
            <artifactId>microservice-common</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

server:
  port: 1001
  context-path: /
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

MicroserviceStudentProvider1001Application

package com.zh.microservicestudentprovider1001;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;

@EntityScan("com.zh.*.*")
@SpringBootApplication
public class MicroserviceStudentProvider1001Application {

    public static void main(String[] args) {
        SpringApplication.run(MicroserviceStudentProvider1001Application.class, args);
    }

}

StudentRepository

package com.zh.microservicestudentprovider1001.repository;

import com.zh.microservicecommon.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends JpaRepository<Student, Integer>, JpaSpecificationExecutor<Student> {

}

StudentService

package com.zh.microservicestudentprovider1001.service;

import com.zh.microservicecommon.entity.Student;

import java.util.List;

public interface StudentService {
 
    public void save(Student student);
     
    public Student findById(Integer id);
     
    public List<Student> list();
     
    public void delete(Integer id);
     
     
}

StudentServiceImpl

package com.zh.microservicestudentprovider1001.service.impl;

import com.zh.microservicecommon.entity.Student;
import com.zh.microservicestudentprovider1001.repository.StudentRepository;
import com.zh.microservicestudentprovider1001.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public void save(Student student) {
        studentRepository.save(student);
    }

    @Override
    public Student findById(Integer id) {
        return studentRepository.findOne(id);
    }

    @Override
    public List<Student> list() {
        return studentRepository.findAll();
    }

    @Override
    public void delete(Integer id) {
        studentRepository.delete(id);
    }

}

StudentProviderController

package com.zh.microservicestudentprovider1001.controller;

import com.zh.microservicecommon.entity.Student;
import com.zh.microservicestudentprovider1001.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentProviderController {
 
    @Autowired
    private StudentService studentService;
     
    @PostMapping(value="/save")
    public boolean save(Student student){
        try{
            studentService.save(student);  
            return true;
        }catch(Exception e){
            return false;
        }
    }
     
    @GetMapping(value="/list")
    public List<Student> list(){
        return studentService.list();
    }
     
    @GetMapping(value="/get/{id}")
    public Student get(@PathVariable("id") Integer id){
        return studentService.findById(id);
    }
     
    @GetMapping(value="/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id){
        try{
            studentService.delete(id);
            return true;
        }catch(Exception e){
            return false;
        }
    }
}

創建服務消費者microservice-student-consumer-80

服務消費者主要是通過restful api來調用提供者的接口,固不需要不需要操作數據庫,相關配置如下
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.zh</groupId>
        <artifactId>springcloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>microservice-student-consumer-80</artifactId>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.zh</groupId>
            <artifactId>microservice-common</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <!--  修改後立即生效,熱部署  -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

server:
  port: 80
  context-path: /

MicroserviceStudentConsumer80Application

package com.zh.microservicestudentconsumer80;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MicroserviceStudentConsumer80Application {

    public static void main(String[] args) {
        SpringApplication.run(MicroserviceStudentConsumer80Application.class, args);
    }

}

SpringCloudConfig

package com.zh.microservicestudentconsumer80.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class SpringCloudConfig {
 
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

StudentConsumerController

package com.zh.microservicestudentconsumer80.controller;

import com.zh.microservicecommon.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentConsumerController {

    private final static String SERVER_IP_PORT = "http://localhost:1001";
 
     @Autowired
     private RestTemplate restTemplate;
      
     @PostMapping(value="/save")
     private boolean save(Student student){
         return restTemplate.postForObject(SERVER_IP_PORT+"/student/save", student, Boolean.class);
     }
      
    @GetMapping(value="/list")
    public List<Student> list(){
        return restTemplate.getForObject(SERVER_IP_PORT+"/student/list", List.class);
    }
     
    @GetMapping(value="/get/{id}")
    public Student get(@PathVariable("id") Integer id){
        return restTemplate.getForObject(SERVER_IP_PORT+"/student/get/"+id, Student.class);
    }
     
    @GetMapping(value="/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id){
        try{
            restTemplate.getForObject(SERVER_IP_PORT+"/student/delete/"+id, Boolean.class);
            return true;
        }catch(Exception e){
            return false;
        }
    }
}

運行1001(服務者訪問):
在這裏插入圖片描述
在這裏插入圖片描述
運行80(消費者訪問):
在這裏插入圖片描述

初識eureka

Eureka簡介:

Eureka是Netflix開發的服務發現框架,本身是一個基於REST的服務,主要用於定位運行在AWS域中的中間層服務,以達到負載均衡和中間層服務故障轉移的目的。SpringCloud將它集成在其子項目spring-cloud-netflix中,以實現SpringCloud的服務發現功能。
Eureka包含兩個組件:Eureka Server和Eureka Client。

  1. Eureka Server提供服務註冊服務,各個節點啓動後,會在Eureka Server中進行註冊,這樣EurekaServer中的服務註冊表中將會存儲所有可用服務節點的信息,服務節點的信息可以在界面中直觀的看到。
  2. Eureka Client是一個java客戶端,用於簡化與Eureka Server的交互,客戶端同時也就別一個內置的、使用輪詢(round-robin)負載算法的負載均衡器。
  3. 在應用啓動後,將會向Eureka Server發送心跳,默認週期爲30秒,如果Eureka Server在多個心跳週期內沒有接收到某個節點的心跳,Eureka Server將會從服務註冊表中把這個服務節點移除(默認90秒)。
  4. Eureka Server之間通過複製的方式完成數據的同步,Eureka還提供了客戶端緩存機制,即使所有的Eureka Server都掛掉,客戶端依然可以利用緩存中的信息消費其他服務的API。

綜上,Eureka通過心跳檢查、客戶端緩存等機制,確保了系統的高可用性、靈活性和可伸縮性。

類似zookeeper,Eureka也是一個服務註冊和發現組件,是SpringCloud的一個優秀子項目,不過,Eureka2版本已經停止更新了。但是Eureka1版本還是很穩定,功能足夠用。

這裏有幾個常用的服務註冊與發現組件比對:
在這裏插入圖片描述
Eureka基本架構:
在這裏插入圖片描述

Eureka的使用

前面說過eureka是c/s模式的 server服務端就是服務註冊中心,其他的都是client客戶端,服務端用來管理所有服務,客戶端通過註冊中心,來調用具體的服務;
我們先來搭建下服務端,也就是服務註冊中心;
新建 module microservice-eureka-server-2001;
在pom文件中加入eureka-server依賴;

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.zh</groupId>
        <artifactId>springcloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>microservice-eureka-server-2001</artifactId>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--  修改後立即生效,熱部署  -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

在yml文件中添加Eureka服務端相關信息;

server:
  port: 2001
  context-path: /
eureka:
  instance:
    hostname: localhost #eureka註冊中心實例名稱
  client:
    register-with-eureka: false     #false 由於該應用爲註冊中心,所以設置爲false,代表不向註冊中心註冊自己。
    fetch-registry: false     #false 由於註冊中心的職責就是維護服務實例,它並不需要去檢索服務,所以也設置爲false
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/       #設置與Eureka註冊中心交互的地址,查詢服務和註冊服務用到

在啓動類中添加@EnableEurekaServer註解;

package com.zh.microserviceeurekaserver2001;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class MicroserviceEurekaServer2001Application {

    public static void main(String[] args) {
        SpringApplication.run(MicroserviceEurekaServer2001Application.class, args);
    }

}

啓動2001:
在這裏插入圖片描述
搭建成功

向Eureka中註冊服務提供者
這裏我們在原來的服務提供者項目 microservice-student-provider-1001 上面直接修改:
首先pom.xml修改,加上eureka客戶端依賴:

<!--添加註冊中心Eureka相關配置-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

然後application.yml上加上配置:

eureka:
  instance:
    hostname: localhost  #eureka客戶端主機實例名稱
    appname: microservice-student  #客戶端服務名
    instance-id: microservice-student:1001 #客戶端實例名稱
    prefer-ip-address: true #顯示IP
  client:
    service-url:
      defaultZone: http://localhost:2001/eureka   #把服務註冊到eureka註冊中心

最後 啓動類加上一個註解 @EnableEurekaClient;
在這裏插入圖片描述
然後我們測試下,先啓動服務註冊中心,再啓動這個服務提供者;
然後運行:http://localhost:2001/
服務提供者成功註冊截圖如下

在這裏插入圖片描述
點擊實例狀態結果如下:
在這裏插入圖片描述
解決方案如下
1、首先在服務提供者項目pom.xml里加入actuator監控依賴:

<!-- actuator監控引入 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2、最後服務提供者項目application.yml加上info配置:

info:
  groupId: com.javaxl.testSpringcloud
  artifactId: microservice-student-provider-1001
  version: 1.0-SNAPSHOT
  userName: http://javaxl.com
  phone: 123456

結果圖如下:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章