之前讲的配置管理, 只有在应用启动时会读取到GIT的内容, 之后只要应用不重启,GIT中文件的修改,应用无法感知, 即使重启Config Server也不行。
比如上一单元(Spring Cloud 入门教程(02):配置管理)中的Hello World 应用,手动更新GIT中配置文件config-client-dev.properties的内容(别忘了用GIT push到服务器)
1 | hello=Hello World from GIT version 1 |
刷新 http://locahost/8881/hello ,页面内容仍然和之前一样,并没有反映GIT中最新改变, 重启config-server也一样,没有任何变化。
要让客户端应用感知到这个变哈, Spring Cloud提供了解决方案是,客户端用POST请求/refresh方法就可以刷新配置内容。
1. 让客户端支持 actuator/refresh方法
要让 actuator/refresh生效,客户端需要增加一些代码支持:
- 首先,在pom.xml中添加以下依赖。spring-boot-starter-actuator是一套监控的功能,可以监控程序在运行时状态,其中就包括/refresh的功能。
1 | <dependency> |
- 其次,开启refresh机制, 需要给加载变量的类上面加载@RefreshScope注解,其它代码可不做任何改变,那么在客户端执行/refresh的时候就会更新此类下面的变量值,包括通过config client从GIT获取的配置。
1 | package org.cwalzy.config.client; |
修改bootstrap.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
spring:
application:
name: config-client
cloud:
config:
label: master
profile: dev
# uri: http://localhost:8888/
discovery:
enabled: true
serviceId: config-server
server:
port: 8881
management:
security:
enabled: false
endpoints:
web:
exposure:
include: health, info, refresh, bus-refresh
endpoint:
bus-refresh:
enabled: true启动应用, 查看http://localhost:8881/hello
- 再次修改config-client-dev.properties的内容
1 | hello=Hello World from GIT version 2 |
用chome的postman发送POST请求:http://localhost:8881/actuator/refresh 可以从POST的结果看到,此次refresh刷新的配置变量有hello

再次访问 http://localhost:8881/hello ,可见到配置已经被刷新

2. 通过Webhook自动触发actuator/refresh方法刷新配置
以上每当GIT中配置文件被修改,仍然需要我们主动调用actuator/refresh方法(手动调用或者写代码调用), 有没有办法让GIT中配置有改动就自动触发客户端的rfresh机制呢? 答案是:有。可以通过GIT提供的githook来监听push命令,如果项目中使用了Jenkins等持续集成工具(也是利用githook来监听的),就可以监听事件处理中直接调用actuator/refresh方法就可以了。
本文转载自 https://www.cnblogs.com/chry/p/7260778.html
原文基于 spring boot 1.5.3.RELEASE 版本
而本文中有一些改动 是基于 spring boot 2.1.5.RELEASE 版本