一.简介
SpringCloudBus是SpringCloud的消息总线,通过消息组件代理各个连接分布点,当配置文件发生变化后可以通过SpringCloudBus实现配置信息动态抓取,实现配置项的动态更新。
二.实现
1.Config Server服务都增加以下依赖库
<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>
2.配置Config Server
server:
port: 8060
spring:
application:
name: config-server
cloud:
config:
server:
git:
clone-on-start: true
uri: https://gitee.com/vincent-java-test/spring-cloud-config.git
username: xxxxxx@163.com
password: xxxxxx
search-paths: service-user
rabbitmq:
username: admin
password: admin
eureka:
client:
service-url:
defaultZone: http://admin:admin@localhost:8010/eureka
management:
security:
# 禁用endpoint 安全校验
enabled: false
3.启动Config Server,并访问http://localhost:15672
Config Server服务启动后将会在RabbitMQ中新建springCloudBus名称的topic Exechange。
4.配置service-user微服务的bootstrap.yml
spring:
application:
name: service-user
cloud:
config:
name: service-user
label: master
profile: prod
discovery:
enabled: true
service-id: config-server
rabbitmq:
username: admin
password: admin
eureka:
client:
service-url:
defaultZone: http://admin:admin@localhost:8010/eureka
management:
security:
enabled: false
5.配置service-user微服务的service-user-prod.yml,并推送到git
server:
port: 8020
spring:
application:
name: service-user #定义微服务名称
eureka:
client:
service-url:
defaultZone: http://admin:admin@localhost:8010/eureka
#需要跟新的数据信息
application:
version: 1.0
6.service-user微服务添加动态内容请求Controller
package com.vincent.user.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class TestController {
@Value("${application.version}")
private String version;
@GetMapping("/version")
public Object version(){
return this.version;
}
}
@RefreshScope 标注的类表示需要动态更新。
7.启动service-user微服务,查看RabbitMQ中Queues将可以看到多了一个队列
8.访问service-user微服务,http://localhost:8020/version
9.修改service-user-prod.yml配置文件,并提交到git服务器
10.通过POST方式请求 http://localhost:8060/bus/refresh,刷新配置服务Config Server
11.再次访问service-user微服务,http://localhost:8020/version
动态抓取配置信息成功。
三.总结
SpringCloud通过消息组件代理(如RabbitMQ) 连接各个分布点,通过Topic方式实现配置文件动态抓取更新。