手动刷新
背景:
我们在部署项目的时候,经常遇到这样的麻烦事情, 因为配置文件的错误,就需要重新改一遍配置,然后打包发布, 或者生产环境用户正在使用,但是因为不可控,需要调整配置的时候,那是不是还要重启?这时候,刷新配置就闪亮登场了。 继续用上一篇记录的项目,拷贝一份config-client出来,进行修修改改
- 老套路添加pom文件,这里面设计到刷新,必不可少,需要添加到actuator
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- bootstrap.yml配置文件不变,调整一下application.yml,这里需要说明一下默认情况下,只打开info,health等断点,所以需要添加
management.endpoints.web.exposure.include=*
配置,其他的不变
server:
port: 8002
spring:
application:
name: config-info
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
- @RefreshScope 注解:被@RefreshScope修饰的bean都是延迟加载的,只有在第一次访问的时候,才会被初始化,刷新bean也是同理,下次访问时候,会重新创建一个新的bean,这就达到了刷新的效果,我们这里创建一个测试的Controller,用到的env配置,还是上一节的
@RefreshScope
@RestController
public class TestController {
@Value("${env}")
private String env;
@GetMapping("test")
public String getEvn() {
return env;
}
}
测试:
1. 首先,直接访问`curl http://127.0.0.1:8002/test`,返回结果是`prod1`
2. 然后更改`config-info-prod.yml`的env为 prod111,然后调用刷新接口`curl -X POST http://localhost:8002/actuator/refresh`,会得到返回值`["env"]`,返回那些属性被刷新了。
3. 再次访问`curl http://127.0.0.1:8002/test`,返回结果是`prod111`,说明刷新成功
Bus热刷新
背景:
如果,就一个client,执行一下当前client的refresh也就罢了,万一要是十台二十台…那岂不是很麻烦,这时候,Bus热刷新就出来了。话不多说,把上一篇文章里面的源码拷贝一份,然后改改名字,改改路径,奉上源码。
跟上一篇的配置变化:
- server和client的pom都同时添加
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
- 对应的yml文件添加rabbit-mq的配置信息,这里如何安装rabbitmq,自行搜索。
spring:
cloud:
bus:
trace:
enabled: true
## 配置rabbitMQ 信息
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
- server端,为了暴露bus-refresh,需要添加一下如下配置,这里面跟上面的手动刷新正好是反着的,因为手动刷新的是客户端, 这里面是服务端刷新
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: ALWAYS
测试:
- 启动config-server-bus,端口是8003
- 启动两个config-client-bus,端口分别是8004和8005
- 分别访问
curl http://127.0.0.1:8004/env
,curl http://127.0.0.1:8005/env
返回结果应该都是prod1 - 把config-info-prod.yml里面的env的配置改成prod,然后执行一下
curl -X POST http://localhost:8003/actuator/bus-refresh
,在操作上一步3,返回结果应该都是prod了,说明咱们的配置可以成功了
注意:
- 因为咱们用的是native模式,所以就没有WebHooks的自动刷新功能,就没有通过WebHooks发送monitor,不需要添加monitor的依赖
结束语
通过学习提高工作效率和质量,在学习中留点记录,方便日后回忆,记录之处过于随意,如有错误或不当之处,还请客官指正,相互学习!
参考书籍:重新定义springcloud实战