不能自动更新配置。这里将介绍手动和自动两种方式来更新配置:
上图的架构将Config Server也纳入到消息总线中,并使用Config Server的/actuator/bus-refresh端点来实现配置的刷新。 这样做的好处就是,各个微服务仅仅需要关注自身的业务,而不需要承担刷新配置的职责了。
使用@RefreshScope + /actuator/bus-refresh端点手动刷新配置
手动刷新其实并不需要接入消息对了,@RefreshScope是关键。这里是为了下面做自动刷新才引入了消息队列
Step1. 添加依赖
根据上图的描述知道 Config Server和微服务都需要接入到消息队列中,Config Server 配置中心服务端 pom文件引入依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency>
order (同时也是config client)同样的也需要加入上述依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency>
Step2. 配置RabbitMQ信息
config (Config Server) 的 application.yml增加 RabbitMQ的配置信息如下:
spring: application: name: config cloud: config: server: git: uri: https://github.com/XiangYuXiHu/spring-cloud-config-center username: XiangYuXiHu password: basedir: D:/cloud-config force-pull: true rabbitmq: host: 192.168.223.139 username: guest password: guest eureka: client: service-url: defaultZone: http://localhost:8762/eureka/ server: port: 8082
Config Client的配置文件增加 RabbitMQ的配置信息如下,放到了远端的Git
通过config server 访问order 使用的配置文件dev分支的信息
Config Server暴露/actuator/bus-refresh端点
根据上面的架构,是通过Config Server暴露出来的endpoints来请求Config Server ,所以需要在Config Server暴露端点,这里设置默认全部暴露出来
确保依赖中有spring-boot-starter-actuator 。 因为 spring-cloud-config-server依赖了spring-boot-starter-actuator ,故无需重复引用。
#actuator 启用所有的监控端点 “*”号代表启用所有的监控端点,可以单独启用,例如,health,info,metrics # spring boot 升为 2.0 后,为了安全,默认 Actuator 只暴露了2个端点,heath 和 info management: endpoints: web: exposure: include: "*" endpoint: health: show-details: ALWAYS
启动RabbitMQ
启动config server微服务: 启动成功后,访问 http://localhost:8762/
登录RabbitMQ查看
可以看到config自动创建一个队列 。 (观察启动日志,可以看到创建过程 )
启动order 微服务
启动成功后查看注册中心
看下消息队列中的队列:
order微服务连接RabbitMQ,也自动创建了一个消息队列
Order中写个测试类 验证自动刷新
@RefreshScope 重点是这个注解
@RestController @RefreshScope public class ConfigClientController { @Value("${env}") private String env; @GetMapping("/env") public String getValueFromGit(){ return env; } }
在远端Git上的配置为 dev,访问下 http://localhost:8081/env
将env的值修改为 dev-test,再次访问下 http://localhost:8081/env
居然没有变化,手工刷新下 ,同时观察config 和 order微服务的日志
curl -v -X POST http://localhost:8082/actuator/bus-refresh
再次访问 http://localhost:8081/env
已经更新为修改后的值
使用Spring Cloud Bus自动更新配置