spring cloud config学习五:手动刷新配置

动态刷新配置

有时候需要对配置内容做些实时更新,那么spring cloud config是否可以实现呢?肯定是可以的,下面对快速入门进行一些改造.

回顾一下快速入门,

  • config-repo-demo:在git上新建的一项目模块,只要是做配置中心的,其中存储了应用名为zhihao的多环境配置文件,配置文件中有二个配置参数fromspring.datasource.name
  • config-server-git:配置了git仓库的服务端
  • config-client: 指定了config-server为配置中心的客户端,应用名为zhihao,用来访问配置服务器以获取配置信息。该应用中提供了一个/index接口,访问config-repo-demo/zhihao.yml中的fromspring.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服务配置仓库

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容