使用/refresh端点手动刷新配置
1.复制项目microservice-config-client,将ArtifactId修改为microservice-config-client-refresh。
2.为项目添加spring-boot-starter-actuator的依赖,该依赖包含了/refresh端点,用于项目的刷新。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
3.在Controller上注解@RefreshScope。添加@RefreshScope的类会在配置更改时得到特殊的处理。
@RefreshScope
@RestController
public class ConfigClientController {
@Value("${profile}")
private String profile;
@GetMapping("/profile")
public String hello(){
return this.profile;
}
}
测试
1.启动microservice-config-server。
2.启动microservice-config-client-refresh。
3.访问http://localhost:8081/profile,可获得结果:dev-1.0。
4.修改Git仓库中的microservice-foo-dev.properties文件内容为profile=dev-1.0-change。
5.重新访问http://localhost:8081/profile,发现结果依然是dev-1.0,说明配置尚未刷新。
6.发送POST请求http://localhost:8081/refresh,例如:
curl -X POST http://localhost:8081/refresh
返回结果:“profile”,表示profile这个配置已经被刷新。
7.再次访问http://localhost:8081/profile,返回dev-1.0-change,说明配置已经刷新。
使用Spring Cloud Bus自动刷新配置
如果所有微服务节点的配置都需要手动去刷新,工作量可想而知。不仅如此,随着系统的不断扩张,会越来越难以维护。因此,实现配置的自动刷新很有必要,我们将使用Spring Cloud Bus实现配置的自动刷新。
Spring Cloud Bus简介
由图可知,微服务A的所有实例都通过消息总线连接到了一起,每个实例都会订阅配置更新事件。当其中一个微服务节点的/bus/refresh端点被请求时,该实例就会向消息总线发送一个配置更新事件,其他实例获得该事件后也会更新配置。
实现自动刷新
1.复制项目microservice-config-client-refresh,将ArtifactId修改为microservice-client-refresh-cloud-bus。
2.为项目添加spring-client-starter-bus-amqp的依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
3.在bootstrap.yml中添加以下内容:
spring:
ribbitmq:
host: localhost
port: 5672
username: guest
password: guest
测试
1.启动microserrvice-config-server。
2.启动microservice-config-client-refresh-cloud-bus,可发现控制台会输出:
3.将microservice-config-client-refresh-cloud-bus的端口改为8002,在启动一个节点。
局部刷新
某些场景下,若只想刷新部分微服务的配置,可通过/bus/refresh端点的destination参数来定位要刷新的应用程序。
例如: /actuator/bus/refresh?destination=costomers.9000,这样消息总线上的微服务就会根据destination参数的值来判断是否刷新。其中,customers:9000指的是各个微服务的ApplicationContextID。
destination参数也可以用来定位特定的微服务。例如:/actuator/bus/refresh?destination=costomers:**,这样就可以出发customers微服务所有实例的配置刷新。
本文大部分内容转载自周立的《Spring Cloud与Docker微服务架构实战》