分布式配置动态刷新
当配置中心中的配置修改之后,客户端并不会进行动态的刷新,每次修改配置文件之后,都需要重启客户端,那么如何才能进行动态刷新呢
可以使用@RefreshScope注解配合actuator端点进行手动刷新,不需要重启客户端
需要引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置文件配置
# 端点管理
management:endpoints:web:exposure:include: "*" # 暴露端点,*表示全部暴露 刷新需要用到的是refresh端点
并在用到配置文件信息的类上增加@RefreshScope注解
@RestController
@RefreshScope
public class TestController {@Value("${version}")private String version;@RequestMapping("/test")public String test(){return version;}
}
此时git上的配置文件修改,只需要使用post请求调用http://ip:port/actuator/refresh
即可刷新配置,而不需要重启客户端,使用post请求
彩蛋
这里说一个彩蛋,我在看spring-cloud-config-client的源码的时候,发现一个ConfigClientWatch,是用来进行定时轮询读取config-server的配置,这个应该是之前老版本实现的
@Scheduled(initialDelayString = "${spring.cloud.config.watch.initialDelay:180000}",fixedDelayString = "${spring.cloud.config.watch.delay:500}")
public void watchConfigServer()
需要配置spring.cloud.config.watch.enabled
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ContextRefresher.class)
@ConditionalOnBean(ContextRefresher.class)
@ConditionalOnProperty("spring.cloud.config.watch.enabled")
protected static class ConfigClientWatchConfiguration {@Beanpublic ConfigClientWatch configClientWatch(ContextRefresher contextRefresher) {return new ConfigClientWatch(contextRefresher);}}
其内部使用的是ContextRefresher,感兴趣的话可以自己去了解一下
https://zhhll.icu/2021/框架/微服务/springcloud/配置中心/springCloudConfig/2.分布式配置动态刷新/