pring Cloud是一系列框架的有序集合。它利用Spring Boot的開發便利性巧妙地簡化了分佈式系統基礎設施的開發,如服務發現註冊、配置中心、消息總線、負載均衡、斷路器、數據監控等,均可以用Spring Boot的開發風格作到一鍵啓動和部署。Spring Cloud並無重複製造輪子,它只是將目前各家公司開發的比較成熟、經得起實際考驗的服務框架組合起來,經過Spring Boot風格進行再封裝屏蔽掉了複雜的配置和實現原理,最終給開發者留出了一套簡單易懂、易部署和易維護的分佈式系統開發工具包。html
詳細介紹: https://baike.so.com/doc/25751000-26884657.htmljava
配套參考資料:mysql
https://projects.spring.io/spring-cloud/ springcloud項目官方主頁git
https://springcloud.cc/ springcloud中文網 有很詳細的翻譯文檔 github
http://springcloud.cn/ springcloud中文論壇 web
Springcloud版本pom文件生成可藉助網站:算法
https://start.spring.io/spring
原有的單體項目最終會被演化成下面sql
這樣的架構解決了單體項目幾點問題:數據庫
一、zuul網關解決了服務調用安全性的問題
二、服務註冊與發現(註冊中心)eureka解決了各層服務耦合問題,它是微服務架構的核心,有它才能將單體項目拆解成微服務架構
三、Eureka集羣解決了微服務中,註冊中心宕機產生的問題
四、Ribbon負載均衡及Feign消費者調用服務,減少了各微服務服務器的訪問壓力,默認採用了經典的輪詢機制
五、熔斷器Hystrix解決了,微服務架構中服務器雪崩現象
六、服務監控(單機Dashboard與集羣turbine),方便運維人員查看微服務架構項目運行時,各個服務器的運行狀態
七、服務配置中心(springcloud config),用來經過github統一管理各個微服務的配置文件(yml文件)
最簡單的微服務架構會有四個工程
父工程:microservice
通用模塊(M):microservice-common
服務提供者(C):microservice-student-provider-1001
服務消費者(C):microservice-student-consumer-80
微服務架構注意點:
一、springboot、springcloud版本在父工程定義;
二、因爲通用模塊無需操做數據庫,springboot啓動默認會讀取數據庫,因此得添加如下註解 @SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class});
三、分佈式jpa須要在啓動類上添加@EntityScan("com.javaxl.*.*");
四、消費者須要添加配置類獲取org.springframework.web.client.RestTemplate,springcloud底層是經過RestTemplate來調用提供者的服務的。
傳統項目拆分紅微服務架構圖
建立父工程microservice
父工程是一個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.cjh</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> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> <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.cjh</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>
Student.java
package com.cjh.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; } }
microserviceCommonApplication.java
package com.cjh.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); } }
建立服務提供者: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.cjh</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.javaxl</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>
<dependency>
<groupId>com.cjh</groupId>
<artifactId>microservice-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-eureka-client</artifactId>
<version>1.4.5.RELEASE</version>
<scope>compile</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>
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/t224?useUnicode=true&characterEncoding=utf8 username: root password: 123 jpa: hibernate: ddl-auto: update show-sql: true
MicroserviceStudentProvider1001Application.java
package com.cjh.microservicestudentprovider1001; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @EntityScan("com.cjh.*.*") @EnableEurekaClient @SpringBootApplication public class MicroserviceStudentProvider1001Application { public static void main(String[] args) { SpringApplication.run(MicroserviceStudentProvider1001Application.class, args); } }
StudentRepository.java
package com.cjh.microservicestudentprovider1001.repository; import com.cjh.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.java
package com.cjh.microservicestudentprovider1001.service; import com.cjh.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.java
package com.cjh.microservicestudentprovider1001.service.impl; import com.cjh.microservicecommon.entity.Student; import com.cjh.microservicestudentprovider1001.repository.StudentRepository; import com.cjh.microservicestudentprovider1001.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author * @site * @company * @create 2019-11-18 18:02 */ @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.java
package com.cjh.microservicestudentprovider1001.controller; import com.cjh.microservicecommon.entity.Student; import com.cjh.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.cjh</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.javaxl</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>
<dependency>
<groupId>com.cjh</groupId>
<artifactId>microservice-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</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.java
package com.cjh.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.java
package com.cjh.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.java
package com.cjh.microservicestudentconsumer80.controller; import com.cjh.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; } } }
成功結果圖以下:
http://localhost:1001/student/list 服務者訪問
http://localhost/student/list 消費者訪問
Eureka是Netflix開發的服務發現框架,自己是一個基於REST的服務,主要用於定位運行在AWS域中的中間層服務,以達到負載均衡和中間層服務故障轉移的目的。SpringCloud將它集成在其子項目spring-cloud-netflix中,以實現SpringCloud的服務發現功能。
Eureka包含兩個組件:Eureka Server和Eureka Client。
Eureka Server提供服務註冊服務,各個節點啓動後,會在Eureka Server中進行註冊,這樣EurekaServer中的服務註冊表中將會存儲全部可用服務節點的信息,服務節點的信息能夠在界面中直觀的看到。
Eureka Client是一個java客戶端,用於簡化與Eureka Server的交互,客戶端同時也就別一個內置的、使用輪詢(round-robin)負載算法的負載均衡器。
在應用啓動後,將會向Eureka Server發送心跳,默認週期爲30秒,若是Eureka Server在多個心跳週期內沒有接收到某個節點的心跳,Eureka Server將會從服務註冊表中把這個服務節點移除(默認90秒)。
Eureka Server之間經過複製的方式完成數據的同步,Eureka還提供了客戶端緩存機制,即便全部的Eureka Server都掛掉,客戶端依然能夠利用緩存中的信息消費其餘服務的API。綜上,Eureka經過心跳檢查、客戶端緩存等機制,確保了系統的高可用性、靈活性和可伸縮性。
相似zookeeper,Eureka也是一個服務註冊和發現組件,是SpringCloud的一個優秀子項目,不過比較坑的是,Eureka2版本已經中止更新了。可是Eureka1版本仍是很穩定,功能足夠用,因此仍是有必要學習下。
可是這裏有幾個經常使用的服務註冊與發現組件比對;
前面說過eureka是c/s模式的 server服務端就是服務註冊中心,其餘的都是client客戶端,服務端用來管理全部服務,客戶端經過註冊中心,來調用具體的服務;
咱們先來搭建下服務端,也就是服務註冊中心;
新建 module microservice-eureka-server-2001;
在pom文件中加入eureka-server依賴;
在yml文件中添加Eureka服務端相關信息;
在啓動類中添加@EnableEurekaServer註解;
pom依賴
<?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.cjh</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>
application.yml
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註冊中心交互的地址,查詢服務和註冊服務用到
MicroserviceEurekaServer2001Application.java
package com.cjh.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); } }
測試鏈接
搭建成功截圖以下
向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註冊中心
在啓動類加@EnableEurekaServer註解:
package com.cjh.microservicestudentprovider1001; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @EntityScan("com.cjh.*.*") @EnableEurekaClient @SpringBootApplication public class MicroserviceStudentProvider1001Application { public static void main(String[] args) { SpringApplication.run(MicroserviceStudentProvider1001Application.class, args); } }
而後咱們測試下,先啓動服務註冊中心microservice-student-provider-1001 Application,再啓動這個服務提供者MicroserviceEurekaServer2001Application;
服務提供者成功註冊截圖以下
點擊實例狀態結果以下
解決方案以下
一、首先在服務提供者項目microservice-student-provider-1001 pom.xml里加入actuator監控依賴:
<!-- actuator監控引入 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
二、最後服務提供者項目application.yml加上info配置:
info: groupId: com.javaxl.testSpringcloud artifactId: microservice-student-provider-1001 version: 1.0-SNAPSHOT userName: http://javaxl.com phone: 123456
結果圖