Spring Cloud Bus 通过轻量级的消息代理连接各个微服务,可以用来广播配置文件的更改,或者管理服务监控。
安装 RabbitMQ(需要安装 docker)
docker run -d --hostname my-rabbit --name javaboy-rabbit -p 15672:15672 5672:5672 rabbitmq:3-management
首先给 config-client 和 config-server 加上 Spring Cloud Bus 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
同时 config-server 要刷新接口,所以要加上 actuator 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
由于给 config-server 中的所有接口都添加了保护,所以刷新接口将无法直接访问,此时,可以修改 security 配置,对端点的权限做出修改:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.csrf().disable();
}
}
在这段配置中,开启了 HttpBasic 登录,这样,在发送刷新请求时,就可以直接通过 HttpBasic 配置认证信息了。
在 config-server、config-client 的 bootstrap.properties 中都配置 rabbitmq 内容:
首先容器的地址很好找就是192.168.99.100
,其次对外的提供服务的地址是 32773,也就是 5672(对外服务端口)对应的地址,都配置:
spring.rabbitmq.host=192.168.99.100
spring.rabbitmq.port=32773
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
在 config-server 上暴露 bus-refresh端口,配置 application.properties 文件:
management.endpoints.web.exposure.include=bus-refresh
最后分别启动 config-server、config-client,然后修改配置文件,提交到 Github
,刷新 config-client 接口,查看是否有变化
(1)未做任何操作提交访问http://localhost:8082/hello
接口:
(2)修改 client1-test.properties 文件,并提交到 Git
(3)访问 config-server 发现已经更新:
(4)访问 config-client 无更新:
(5) 用 postman 访问 config-server 的 bus-refresh 接口,在 Authorization 中选择 Basic Auth ,右侧输入用户名密码,可以按 HttpBasic 方式访问:
(6)访问 config-client 发现已更新:
这就是 Spring Cloud Bus 来完成 Git 配置文件更新,不用重启 config-client 就能加载配置文件的功能,原理是,当访问 bus-refresh 接口时,config-server 发送指令给 Spirng Cloud Bus ,也就是 rabbitmq,rabbitmq 通知各个 config-client 配置文件有更新,然后 config-client 从 config-server 更新配置文件,最后更新的内容来让应用程序使用。