介绍
我们在Spring Cloud系列教程六 :分布式配置中心Spring Cloud Config(F版)中提到客户端想要获取最新的配置需要访问/actuator/refresh,虽然我们可以用webhook简化这一流程,但是当客户端越来越多的时候,这种方案也不太合适,我们可以用Spring Cloud Bus来解决这一问题
github地址:https://github.com/erlieStar/spring-cloud-learning
实现多客户端的配置更新
复制consumer-config-cluster(spring-cloud-config )为consumer-config-cluster-bus(spring-cloud-bus)
1.项目配置如下
pom.xml
<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-config</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-bus-amqp</artifactId>
</dependency>
bootstrap.yaml
server:
port: 6001
spring:
application:
name: javashitang # 要获取的配置的应用名
cloud:
config:
profile: dev
label: master
discovery:
enabled: true
service-id: config-cluster
bus:
enabled: true
trace:
enabled: true
rabbitmq:
host: myhost
port: 5672
username: guest
password: guest
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka
management:
endpoints:
web:
exposure:
include: bus-refresh
2.启动类如下
@RefreshScope
@RestController
@EnableEurekaClient
@SpringBootApplication
public class ConsumerConfigClusterBus {
public static void main(String[] args) {
SpringApplication.run(ConsumerConfigClusterBus.class);
}
@Value("${from}")
private String from;
@RequestMapping("from")
public String from() {
return this.from;
}
}
rabbitmq的安装及相关知识看我的博客,不再介绍
依次启动eureka-service(spring-cloud-eureka)
config-cluster(spring-cloud-config)
启动2个consumer-config-cluster-bus(spring-cloud-bus)
在idea中启动2个实例的方法,参见Spring Cloud系列教程二 :客户端负载均衡Spring Cloud Ribbon(F版)
访问
http://localhost:6001/from
http://localhost:6002/from
返回如下
javashitang-git-dev-update
将javashitang-dev.yaml内容改为如下,并提交到github
from: javashitang-git-dev
使用postman用post方式调用http://localhost:6001/actuator/bus-refresh/
再次访问
http://localhost:6001/from
http://localhost:6002/from
此时返回的都是
javashitang-git-dev
证明多个客户端配置同时刷新成功
欢迎关注
参考博客
[1]https://windmt.com/2018/04/19/spring-cloud-9-config-eureka-bus/