Spring Cloud 2-Bus 消息总线(九)
在分布式配置中,客户端获取远程最新配置时(比如:Git),要手动发送POST请求客户端来刷新.在集群环境下,不是很方便.使用Spring Cloud Bus总线可以自动刷新客户端配置.
1.服务端配置
pom.xml
<!-- config-server 服务配置中心 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<!-- bus 消息总线 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
application.yml
spring:
application:
name: config-bus-server
cloud:
config:
server:
git:
uri: https://github.com/xianghaizing/spring-cloud-learn
search-paths: config-repo
# 以下都是默认配置
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
server:
port: 8888
management:
endpoints:
web:
exposure:
include: bus-refresh # 暴露刷新节点 2.x版本需要手动开启
2.客户端配置
pom.xml
<!-- spring mvc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 配置中心client端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- bus 消息总线 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
application.yml
spring:
application:
name: config-bus-client
cloud:
config:
uri: http://localhost:8888
name: lyf # 远程文件的application名字
profile: dev
label: master
bus:
trace:
enabled: true
# 以下都是默认配置
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
server:
port: 8040
name
远程文件的application名字rabbitmq
RabbitMQ服务地址以及用户名和密码
Controller.java
@RefreshScope
@RestController
public class BusClientController {
@Value("${from}")
private String from;
@GetMapping("/from")
public String getFrom(){
return this.from;
}
}
@RefreshScope
必须添加才能自动刷新
3.自动刷新配置
依次启动:
- 启动RabbitMQ服务
- 启动服务端
- 启动多个客户端
验证顺序和方式跟之前一样.只是,现在要向服务端
发送请求,而不是客户端
!
POST: http://localhost:8888/actuator/bus-refresh
所有客户端的配置都已经更新.