Spring Cloud
-
服务治理 Eureka
-
服务通信 Ribbon、Fegin
-
服务网关 Zuul
-
服务容错 Hystrix
-
服务配置 Config
-
服务监控 Actuator
-
服务跟踪 Zipkin
服务治理 Eureka
服务治理的核心由三部分组成:服务提供者、服务消费者、服务中心
-
在分布式系统中,每个微服务在启动时,将自己的信息存储在注册中心,叫做服务注册
-
服务消费者从注册中心获取提供者的网络信息,通过该信息调用服务,叫做服务发现
Eureka是Netflix开源的基于REST的服务治理解决方案,SpringCloud集成了Eureka,提供服务注册和服务发现的功能,可以和基于Spring Boot搭建的微服务应用轻松完成整合,开箱即用
SpringCloud Euraka
-
Eureka Server:注册中心
-
Eureka Client:所有要进行注册的微服务通过Eureka Client连接到Eureka Server,完成注册
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>orihgc</groupId>
<artifactId>AiSpringCloud</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>eurekaserver</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--解决jdk9以上没有JAXB API的问题-->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependences</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
- 在父工程下创建Module,pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
</dependencies>
- 创建配置文件application.yml,添加
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone:http://localhost:8761/eureka
属性说明
server.port:当前Eureka Server服务端口
eureka.client.register-with-eureka:是否将当前的Eureka Server服务作为客户端进行注册
eureka.client.fetch-fegistry:是否获取其他的Eureka Server服务的数据
eureka.client.service-url.defaultZone:注册中心的访问地址
- 创建启动类
package com.southwind;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class,args);
}
}
注解说明
@SpringBootApplication:声明该类是SpringBoot服务的入口
@EnableEurekaServer:声明该类是一个Eureka Server微服务,提供服务注册和服务发现功能,即注册中心
Eureka Client 代码实现
- 创建Moudle,pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
- 创建配置文件application.yml添加Eureka Client相关配置
server:
port: 8010
spring:
application:
name: provider
eureka:
client:
service-url:
defaultZone: http://localhost:8000/eureka/
instance:
prefer-ip-address: true
spring.application.name
:当前服务注册在Eureka Server上的名称
eureka.client.service-url.defaultZone
:注册中心的访问地址
eureka.instance.prefer-ip-address
:是否将当前服务的ip注册到Eureka Server
RestTemplate的使用
- 什么是RestTemplate?
RestTemplate是Spring框架提供的基于REST的服务组件,底层对HTTP请求及相应进行了封装,提供了很多访问REST服务的方法,可以简化代码开发。
- 如何使用RestTemplate?
1、创建maven工程
2、controller
@RestController
@RequestMapping("/student")
public class StudentHandler {
@Autowired
private StudentRepository studentRepository;
@GetMapping("/findAll")
public Collection<Student> findAll() {
return studentRepository.findAll();
}
@GetMapping("/findById/{id}")
public Student findById(@PathVariable("id")long id) {
return studentRepository.findById(id);
}
@PostMapping("/save")
public void save(@RequestBody Student student){
studentRepository.saveOrUpdate(student);
}
@PutMapping("/update")
public void update(@RequestBody Student student){
studentRepository.saveOrUpdate(student);
}
@DeleteMapping("/deleteById/{id}")
public void deleteById(@PathVariable("id") long id){
studentRepository.deleteById(id);
}
}
3、启动类
@SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
服务消费者consumer
- 创建maven工程,pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
- 创建配置文件
server:
port: 8020
spring:
application:
name: consumer
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
- 创建启动类
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
- Handler
@RestController
@RequestMapping("/consumer")
public class ConsumerHandler {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findAll")
public Collection<Student> findAll() {
return restTemplate.getForEntity("http://localhost:8010/student/findAll", Collection.class).getBody();
}
@GetMapping("/findAll2")
public Collection<Student> findAll2() {
return restTemplate.getForObject("http://localhost:8010/student/findAll", Collection.class);
}
@GetMapping("/findById/{id}")
public Student findById(@PathVariable("id") Long id) {
return restTemplate.getForEntity("http://localhost:8010/student/findById/{id}", Student.class, id).getBody();
}
@PostMapping("/save")
public void save(@RequestBody Student student) {
restTemplate.postForEntity("http://localhost:8010/student/save", student, null);
}
@PutMapping("/update")
public void update(@RequestBody Student student) {
restTemplate.put("http://localhost:8010/student/update", student);
}
@DeleteMapping("/deleteById/{id}")
public void deleteById(@PathVariable("id") Long id) {
restTemplate.delete("http://localhost:8010/student/deleteById/{id}",id);
}
}
Zuul 服务网关
Spring Cloud集成了Zuul组件,实现服务网关
- 什么是Zuul?
Zuul是Netflix提供的一个开源的API网关服务器,是客户端和网站后端所有请求的中间层,对外开放一个API,将所有请求导入统一的入口,屏蔽了服务端的具体逻辑实现,Zuul可以实现反向代理的功能,在网关内部实现动态路由、身份认证、IP过滤、数据监控等功能。
- 创建maven工程,pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
</dependencies>
- 配置文件application.yml
server:
port: 8030
spring:
application:
name: gateway
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
zuul:
routes:
provider: /p/**
属性说明:
zuul.routes.provider:给服务提供者provider设置映射
- 创建启动类
@EnableZuulProxy
@EnableAutoConfiguration
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class,args);
}
}
@EnableZuulProxy
:包含了@EnableZuulServer,设置该类是网关的启动类
@EnableAutConfiguration
:可以帮助SpringBoot应用将所有符合条件的@Configuration配置加载到当前SpringBoot创建并使用的IoC容器中。
- Zuul自带了负载均衡的功能,修改provider代码
Ribbon 负载均衡
- 什么是Ribbon?
SpringCloud Ribbon是一个负载均衡解决方案,Ribbon是NetFlix发布的,SpringCloud是基于NetFlix Ribbon实现的,是一个用于对HTTP请求控制的负载均衡器客户端
在注册中心对Ribbon进行注册之后,Ribbon就可以基于某种负载均衡算法,如轮询、随机、加权轮询、加权随机等自动帮助服务消费者调用接口,开发者可以很具具体需求自定义Ribbon负载均衡算法。实际开发中,SpringCloudRibbon需要结合SpringCloud Eureka来使用。Eureka Server提供所有可以调用的服务提供者列表,Ribbon基于特定的负载均衡算法从这些服务提供者中选择要调用的具体实例
- 创建maven工程,pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
- 创建配置文件
server:
port: 8040
spring:
application:
name: ribbon
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
- 创建启动类
@SpringBootApplication
public class RibbonApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class,args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
@LoadBalanced:声明一个基于Ribbon的负载均衡
- Handler
@RestController
@RequestMapping("/ribbon")
public class RibbonHandler {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findAll")
public Collection<Student> findAll(){
return restTemplate.getForObject("http://provider/student/findAll",Collection.class);
}
@GetMapping("/index")
public String index(){
return restTemplate.getForObject("http://provider/student/index",String.class);
}
}
Fegin
- 什么是Fegin?
与Ribbon一样也是由NetFlix提供的,Fegin是一个声明式的,模板化的Web Service客户端,它简化了开发者编写Web服务端的操作,开发者可以通过简单的接口和注解来调用Http API。SpringCloud Fegin,它整合了Ribbon和Hystrix,具有可插拔、基于注解、负载均衡、服务熔断等一系列便捷功能
相比较于Ribbon+RestTemplate的方式,Fegin可以大大简化代码的开发,Fegin支持多种注解,包括Fegin注解、JAX-RS注解、SpringMVC注解,SpringCloud对Fegin进行了优化,整合了Ribbon和Eureka,从而让Fegin的使用更加方便
- Ribbon和Fegin的区别
Ribbon是一个通用的HTTP客户端工具,Fegin是基于Ribbon实现的
Feigin的特点
1、Fegin是声明式的WebService客户端
2、支持Fegin注解、SpringMVC注解、JAX-RS注解
3、基于Ribbon,更加简单
4、集成了Hystrix,具备服务熔断功能
- 创建maven工程,pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
- 创建配置文件applicaton.yml
server:
port: 8050
spring:
application:
name: fegin
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
- 创建启动类
@SpringBootApplication
@EnableFeignClients
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class,args);
}
}
- 创建声明式接口
@FeignClient(value = "provider")
public interface FeignProviderClient {
@GetMapping("/student/findAll")
public Collection<Student> findAll();
@GetMapping("/student/index")
public String index();
}
- 服务熔断,application.yml添加熔断机制
server:
port: 8050
spring:
application:
name: fegin
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
feign:
hystrix:
enabled: true
feign.hystrix.enabled
:是否开启熔断器
- 创建FeignProviderClient接口的实现类FeignError,定义熔断处理逻辑,通过@Commonent将FeignError实例注入IoC 容器中
@Component
public class FeignError implements FeignProviderClient {
@Override
public Collection<Student> findAll() {
return null;
}
@Override
public String index() {
return "服务器维护中......";
}
}
- 在FeignProviderClient定义处通过
@FeignClient
的fallback属性设置映射
@FeignClient(value = "provider",fallback = FeignError.class)
public interface FeignProviderClient {
@GetMapping("/student/findAll")
public Collection<Student> findAll();
@GetMapping("/student/index")
public String index();
}
Hystrix 容错机制
在不改变各个微服务调用关系的前提下,针对错误情况进行预先处理。
- 设计原则
1、服务隔离机制
2、服务降级机制
3、熔断机制
4、提供实时监控和报警功能
5、提供实时的配置修改功能
Htstrix数据监控需要结合Spring Cloud Actuator来使用,Actuator提供了对服务的健康监控、数据统计,可以通过hystrix-stream节点获取监控的请求数据,提供了可视化的监控界面。
- 创建maven
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
</dependencies>
- 创建配置文件
server:
port: 8060
spring:
application:
name: hystrix
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
feign:
hystrix:
enabled: true
management:
endpoints:
web:
exposure:
include: 'hystrix.stream'
- 创建启动类
@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrixDashboard
public class HystrixApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixApplication.class,args);
}
}
注解说明
@EnableCircuitBreaker
:声明启用数据监控
@EnableHystrixDashboard
:声明启用可视化的数据监控
- Handler
@RestController
@RequestMapping("/hystrix")
public class HystrixHandler {
@Autowired
private FeignProviderClient feignProviderClient;
@GetMapping("/findAll")
public Collection<Student> findAll(){
return feignProviderClient.findAll();
}
@GetMapping("/index")
public String index(){
return feignProviderClient.index();
}
}
启动成功后,访问http://localhost:8060/actuator/hystrix.stream
可以监控请求到的数据
访问http://localhost:8060/hystrix
,可以看到可视化的监控界面,输入要监控的地址节点,即可看到该节点的可视化数据监控
Spring Cloud 配置中心
SpringCloud Config,通过服务端,可以为多个客户端提供配置服务。Spring Cloud Config可以将配置文件存储在本地,也可以存放在远程的Git仓库,Config Server,通过它来管理所有的配置文件,所有微服务通过它来读取配置文件
本地文件系统
- 创建maven工程,pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
- 创建application.yml
server:
port: 8762
spring:
application:
name: nativeconfigserver
profiles:
active: native
cloud:
config:
server:
native:
search-locations: classpath:/shared
注解说明
profiles.active
:配置文件的获取方式
cloud.config.server.native.search-locations
:本地配置文件存放的路径
- resources路径下创建shared文件夹,并在此目录下创建configclient-dev.yml
server:
port: 8070
foo: foo version 1
- 创建启动类
@SpringBootApplication
@EnableConfigServer
public class NativeConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(NativeConfigServerApplication.class,args);
}
}
注解说明
@EnableConfigServer
:声明配置中心。
- 创建客户端读取本地配置中心的配置文件
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
</dependencies>
- 创建配置文件bootstrap.yml,配置读取本地配置中心的相关信息
spring:
application:
name: configclient
profiles:
active: dev
cloud:
config:
uri: http://localhost:8762
fail-fast: true
注解说明
cloud.config.uri
:本地Config Server的访问路径
cloud.config.fail-fast
:设置客户端优先判断Config Server获取是否正常。
通过spring.application.name
结合spring.profiles.active
拼接目标配置文件名,configclient-dev.yml,去Config Server中查找该文件。
- 创建客户端的启动类
@SpringBootApplication
public class NativeConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(NativeConfigClientApplication.class,args);
}
}
- Handler
@RestController
@RequestMapping("/native")
public class NativeConfigHandler {
@Value("${server.port}")
private String port;
@Value("${foo}")
private String foo;
@GetMapping("/index")
public String index(){
return this.port+"-"+this.foo;
}
}
Spring Cloud Config远程配置
- 创建配置文件,上传至GitHub
server:
port: 8070
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
spring:
application:
name: configclient
- 创建ConfigServer,新建maven工程,pom
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
- 创建配置文件application.yml
server:
port: 8888
spring:
application:
name: configserver
cloud:
config:
server:
git:
uri: https://github.com/orihgc/SpringCloud.git
search-paths: config
username: orihgc
password: 369369upme
label: master
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
- 创建启动类
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class,args);
}
}
- 创建Config Client,创建maven工程,pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
- 创建bootstrap.yml
spring:
cloud:
config:
name: configclient
label: master
discovery:
enabled: true
service-id: configserver
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
注解说明
spring.cloud.config.name
:当前服务注册在Eureka Server上的名称,与远程仓库的配置文件名对应。
spring.cloud.config.label
:Git Repository的分支
spring.cloud.config.discovery.enabled
:是否开启Config服务发现支持
spring.cloud.config.discovery.service-id
:配置中心在Eureka Server上注册的名称
创建启动类
@SpringBootApplication
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class,args);
}
}
- Handler
@SpringBootApplication
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class,args);
}
}
服务跟踪
Spring Cloud Zipkin
ZipKin是一个可以采集并且跟踪分布式系统中请求数据的组件,让开发者可以更加直观地监控到请求在各个微服务所耗费的时间等,Zipkin:Zipkin Server、Zipkin Client。
创建服务端
- 创建maven工程
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-server</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-autoconfigure-ui</artifactId>
<version>2.9.4</version>
</dependency>
</dependencies>
- 创建配置文件application.yml
server:
port: 9090
spring:
main:
allow-bean-definition-overriding: true
- 创建启动类
@SpringBootApplication
@EnableZipkinServer
public class ZipkinApplication {
public static void main(String[] args) {
SpringApplication.run(ZipkinApplication.class,args);
}
}
注解说明
@EnableZipkinServer
:声明启用Zipkin Server
创建客户端 ZipkinClient
- 创建maven,pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
</dependencies>
- 创建配置文件application.yml
server:
port: 8090
spring:
application:
name: zipkinclient
sleuth:
web:
client:
enabled: true
sampler:
probability: 1.0
zipkin:
base-url: http://localhost:9090/
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
属性说明
spring.sleuth.web.client.enabled
:设置开启请求跟踪
spring.sleuth.sampler.probility
:设置采样比例,默认是1.0
spring.zipkin.base-url
:Zipkin Server的地址
- 创建启动类
@RestController
@RequestMapping("/zipkin")
public class ZipkinHandler {
@Value("${server.port}")
private String port;
@GetMapping("/index")
public String index(){
return this.port;
}
}