jv运行期间动态调整配置
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
里面包含了/refresh端点,用于配置的刷新。
@RestController
@RefreshScope //会在配置更改的时候,特殊的处理
public class ConfigClientController {
@Value("${profile}")
private String profile;
@GetMapping("/profile")
public String hello() {
return this.profile;
}
}
http://localhost:8081/profile
更改了git之后,
http://localhost:8081/refresh
再次访问,就变成更改之后的了
使用spring Cloud Bus自动刷新
cloud bus使用轻量级的消息代理,连接分布式的节点。
广播传播状态的更改
想象成分布式的的spring boot actuator
即是: 有一个项目 /bus/refresh,会给bus 发消息,bus收到之后,广播给其他服务
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
spring:
application:
name: microservice-config-server
cloud:
config:
server:
git:
uri: https://git.oschina.net/itmuch/spring-cloud-config-repo # 配置Git仓库的地址
username: # Git仓库的账号
password: # Git仓库的密码
bus:
trace:
enabled: true # 开启cloud bus的跟踪
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
#忽略权限拦截
management:
security:
enabled: false
security:
basic:
enabled: false 如果不行的话,在关闭这个security包的安全验证
访问:
http://localhost:8080/bus/refresh
然后在配置git仓库的 webHooks(一个推送,更改了就会往配置的请求推送),就可实现自动刷新
局部刷新
可通过 /bus/refresh 端点的destination参数来定位要刷新的应用程序
/bus/refresh?destination=customers:9000
9000是各个微服务的 applicationContext ID(默认为端口号)
/bus/refresh?destination=customers:**
customers微服务下的所有实例配置刷新
架构改进
config server也加入消息总线中,并使用config server的 /bus/refresh 端点来实现配置的刷新
即是:所有的微服务项目都引入bus,在配置中心 操作刷新
跟踪总线事件
spring:
application:
name: microservice-config-server
cloud:
config:
server:
git:
uri: https://git.oschina.net/itmuch/spring-cloud-config-repo # 配置Git仓库的地址
username: # Git仓库的账号
password: # Git仓库的密码
bus:
trace:
enabled: true # 开启cloud bus的跟踪
在访问 /trace 端点,就可得到 事件的传播细节
[
{
"timestamp": 1581145900623,
"info": {
"method": "POST",
"path": "/bus/refresh",
"headers": {
"request": {
"user-agent": "PostmanRuntime/7.22.0",
"accept": "*/*",
"cache-control": "no-cache",
"postman-token": "4e66919e-e038-49db-a1b4-a4bf03527927",
"host": "localhost:8080",
"accept-encoding": "gzip, deflate, br",
"content-length": "0",
"connection": "keep-alive"
},
"response": {
"X-Application-Context": "microservice-config-server:8080",
"status": "200"
}
},
"timeTaken": "5357"
}
},
{
"timestamp": 1581145895502,
"info": {
"signal": "spring.cloud.bus.sent",
"type": "RefreshRemoteApplicationEvent",
"id": "3ee40b9e-37fc-405f-8835-d49b05d85cec",
"origin": "microservice-config-server:8080",
"destination": "**:**"
}
},
{
"timestamp": 1581145895501,
"info": {
"destination": "**"
}
}
]