动态刷新配置
有时候需要对配置内容做些实时更新,那么spring cloud config
是否可以实现呢?肯定是可以的,下面对快速入门进行一些改造.
回顾一下快速入门,
-
config-repo-demo
:在git上新建的一项目模块,只要是做配置中心的,其中存储了应用名为zhihao
的多环境配置文件,配置文件中有二个配置参数from
和spring.datasource.name
-
config-server-git
:配置了git仓库的服务端 -
config-client
: 指定了config-server
为配置中心的客户端,应用名为zhihao
,用来访问配置服务器以获取配置信息。该应用中提供了一个/index
接口,访问config-repo-demo/zhihao.yml
中的from
和spring.datasource.name
属性,
当前配置文件:
from: git-pro-2.0
spring:
datasource:
username: user_pro
在线修改之后,
from: git-pro-3.0
spring:
datasource:
username: user_pro3
测试,http://localhost:8080/index
发现访问客户端的接口,页面显示还是
username=user_pro,form==git-pro-2.0
接下来,我们将config-client端做一些改造以实现配置信息的动态刷新。
- 在
config-client
的pom文件中新增spring-boot-starter-actuator
监控依赖,其中包含/refresh
端点的实现,该端点将用于实现客户端应用配置信息的重新获取与刷新。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 在客户端上需要注入配置值的类上加入注解
@RefreshScope
@RestController
@RefreshScope
public class ConfigClientController {
private Logger log = LoggerFactory.getLogger(getClass());
@Value("${spring.datasource.username}")
private String username;
@Value("${from}")
private String from;
@GetMapping("/index")
public String index(){
log.info("username="+username+",form=="+from);
return "username="+username+",form=="+from;
}
}
- 重新访问
config-client
,访问一次可以看到当前的配置 - 修改git上的配置
- 在次访问
http://localhost:8080/index
,看到配置信息没有改变 - 通过post请求发送到
localhost:8080/refresh
,可以看到返回的内容
➜ curl -X POST http://localhost:8080/refresh
["config.client.version","spring.datasource.username","from"]
- 再次访问
http://localhost:8080/index
,看到更新后的值了
username=user_pro3.0,form==git-pro-3.0
通过上面的介绍,该功能还可以同git仓库的web hook功能进行关联,当有git提交变化时,就给对应的配置主机发送/refresh
请求来实现配置信息的实时更新。但是,当我们的系统发展壮大之后,维护这样的刷新清单也将成为一个非常大的负担,而且很容易犯错,可以使用spring cloud bus
来解决这个问题。
相关官网文档的一些翻译
环境变更
The application will listen for an EnvironmentChangedEvent and react to the change in a couple of standard ways (additional ApplicationListeners can be added as @Beans by the user in the normal way). When an EnvironmentChangedEvent is observed it will have a list of key values that have changed, and the application will use those to:
- Re-bind any @ConfigurationProperties beans in the context
- Set the logger levels for any properties in logging.level.*
应用程序将监听一个EnvironmentChangedEvent
事件,并以几种标准方式对变化进行响应(用户可以通过常规方式将额外的ApplicationListener
添加为@Beans
)。 当观察到一个EnvironmentChangedEvent
事件时,它将有一个已经更改的键值列表,应用程序将使用以下内容:
- 在上下文中重新绑定任何
@ConfigurationProperties
实例 - 为
logging.level.*
中的任何属性设置日志级别。
Note that the Config Client does not by default poll for changes in the Environment, and generally we would not recommend that approach for detecting changes (although you could set it up with a @Scheduled annotation). If you have a scaled-out client application then it is better to broadcast the EnvironmentChangedEvent to all the instances instead of having them polling for changes (e.g. using the Spring Cloud Bus).
请注意,Config Client
不会对环境中的更改进行默认轮询拉取,通常我们不建议使用这种方式检测配置修改(尽管可以使用@Scheduled
注释进行设置)。 如果您有一个扩展的客户端应用程序,那么最好将EnvironmentChangedEvent
事件广播到所有实例,而不是让它们轮询更改(例如使用Spring Cloud Bus
)。(这个也是手动刷新的弊端,每个应用都需要去手动刷新)。
The EnvironmentChangedEvent covers a large class of refresh use cases, as long as you can actually make a change to the Environment and publish the event (those APIs are public and part of core Spring). You can verify the changes are bound to @ConfigurationProperties beans by visiting the /configprops endpoint (normal Spring Boot Actuator feature). For instance a DataSource can have its maxPoolSize changed at runtime (the default DataSource created by Spring Boot is an @ConfigurationProperties bean) and grow capacity dynamically. Re-binding @ConfigurationProperties does not cover another large class of use cases, where you need more control over the refresh, and where you need a change to be atomic over the whole ApplicationContext. To address those concerns we have @RefreshScope.
EnvironmentChangedEvent
涵盖了大量的刷新用例,只要您实际可以更改环境并发布事件(这些API是公开的,并且是Spring的一部分)。 您可以通过访问/configprops
端点(正常的Spring Boot监控的特征)来验证更改是否绑定到@ConfigurationProperties
实例。 例如,DataSource
可以在运行时更改其maxPoolSize
(Spring Boot创建的默认DataSource
是一个@ConfigurationProperties
实例)并动态增加容量。 重新绑定@ConfigurationProperties
不会覆盖另一个实例,您需要更多的控制刷新,并且您需要更改在整个ApplicationContext
上是原子的。 为了解决这些问题,我们有@RefreshScope
。
刷新范围(Refresh Scope)
A Spring @Bean that is marked as @RefreshScope will get special treatment when there is a configuration change. This addresses the problem of stateful beans that only get their configuration injected when they are initialized. For instance if a DataSource has open connections when the database URL is changed via the Environment, we probably want the holders of those connections to be able to complete what they are doing. Then the next time someone borrows a connection from the pool he gets one with the new URL.
当配置更改时,标记为@RefreshScope
的Spring @Bean
将受到特殊的处理。 这解决了有状态bean在初始化时只注入配置的问题。 例如,当我们在更改数据库的URL的时候已经有用户拿到了当前实例的连接,那么我们可能希望这些连接的持有人能够完成他们正在做的工作。 然后下一次有人从数据库连接池的连接就是从新的url连接上来拿。
Refresh scope beans are lazy proxies that initialize when they are used (i.e. when a method is called), and the scope acts as a cache of initialized values. To force a bean to re-initialize on the next method call you just need to invalidate its cache entry.
刷新范围bean是在使用时初始化的懒惰代理(即当调用方法时),并且作用域作为初始化值的缓存。 要强制bean重新初始化下一个方法调用,您只需要使其缓存条目无效。
The RefreshScope is a bean in the context and it has a public method refreshAll() to refresh all beans in the scope by clearing the target cache. There is also a refresh(String) method to refresh an individual bean by name. This functionality is exposed in the /refresh endpoint (over HTTP or JMX).
RefreshScope
是上下文中的一个bean,它有一个公共方法refreshAll()
通过清除目标缓存来刷新作用域中的所有bean。 还有一个refresh
方法来按名称刷新单个的bean。 此功能在/refresh端点(通过HTTP或JMX)中公开。
注意
@RefreshScope works (technically) on an @Configuration class, but it might lead to surprising behaviour: e.g. it does not mean that all the @Beans defined in that class are themselves @RefreshScope. Specifically, anything that depends on those beans cannot rely on them being updated when a refresh is initiated, unless it is itself in @RefreshScope (in which it will be rebuilt on a refresh and its dependencies re-injected, at which point they will be re-initialized from the refreshed @Configuration).
@RefreshScope
可以和@Configuration
类上作用起效果(技术上来说),但可能会意想不到的行为:例如这并不保证着该类中定义的所有@Beans
都是@RefreshScope
。 具体来说,依赖于这些bean的任何东西都不能依赖它们在刷新启动时被更新,除非它本身在@RefreshScope
中(它将在刷新中被重建,并且重新注入它的依赖项,那么它们将在从刷新的@Configuration
重新初始化)。
/refresh for re-loading the boot strap context and refreshing the @RefreshScope beans.
/refresh
端点重新加载带上下文并刷新@RefreshScope实例
参考资料
Environment Changes
Refresh Scope
本博客代码
代码地址
配置仓库
user服务配置仓库
order服务配置仓库