走进Spring Cloud之十 高可用配置中心动态刷新(Greenwich版本)

走进Spring Cloud之十 高可用配置中心动态刷新(Greenwich版本)

动态刷新

前一篇章,我们演示了SpringCloud Config配置中心的远程配置加载和高可用,但是在实际开发中唯一不变的是配置在一直变化,同时我们需要我们的客户端能够时时与配置中心变化的配置保持一致。

这里我们一次启动我们的eureka-server注册中心/配置服务端config-server/配置客户端config-client

访问 http://localhost:8761/
8761

访问 http://localhost:8888/master/springcloud-config-pro.yml 测试config-server加载配置。
server

访问 http://localhost:8889/writer 测试config-client的配置读取。
client

这里需求出现改变,我们需要修改我们的配置信息

#springcloud-config-pro.yml
writer: jason(silent silent silent)

提交到我们的git仓库
git config

再次访问 http://localhost:8888/master/springcloud-config-pro.yml 测试config-server加载配置。
silent
很明显我们的server能够自动拿到最新的配置。

再次访问 http://localhost:8889/writer 测试config-client的配置读取。
client silent
很明显我们的配置信息不会更新。(这里是因为client在启动的时候就从配置中心拿到了配置信息并且保存在了本地)

很明显,这不是我们想要的。虽然我们可以重新启动client来加载我们的最新配置,当然这也是最不可取的。

refresh

上面的问题,我们可以通过spring-boot-starter-actuator来解决,spring-boot-starter-actuator是一套监控的功能,可以监控程序在运行时状态,其中就包括/refresh的功能。

接下来,我们将对config-client对应作出修改来达到我们的目标。

pom.xml

在pom.xml添加spring-boot-starter-actuator依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

application.yml

#关闭安全认证
management:
  security:
    enabled: false
  #refresh接入点显式暴露出来
  endpoints:
    web:
      exposure:
        include: refresh,health,info

开启更新机制

我们可以给需要加载变量的bean上面加载@RefreshScope注解,在客户端执行/refresh的时候就会更新此bean下面的变量值。
例如 :ConfigClientController.java

@RestController
@RefreshScope // 使用该注解的类,会在接到SpringCloud配置中心配置刷新的时候,自动将新的配置更新到该类对应的字段中。
public class ConfigClientController {

    @Value("${writer}")
    String writer;

    @RequestMapping(value = "/writer")
    public String writer(){
        return writer;
    }

}

启动测试

再次更新git仓库的配置
github

再次访问 http://localhost:8889/writer 测试config-client的配置读取。
在这里插入图片描述

很明显还是上一次的配置,那么我们应该怎么通知config-client进行配置更新呢?

#curl  -X POST http://localhost:8889/actuator/refresh
#["config.client.version","writer"]

再次访问 http://localhost:8889/writer 测试config-client的配置读取。

result

Webhooks

Webhooks 允许在Github上的某些事件(例如Push)发生时通知外部服务。当指定的事件发生时,GitHub将向您提供的每个URL发送一个POST请求。了解更多请访问 Webhooks Guide.如果我们设置了一个监测push事件的Webhook,那么每当你的这个项目有了任何提交,这个Webhook都会被触发,这时Github就会发送一个HTTP POST请求到你配置好的地址。

例如:如下案例,我们就可以用于自动通知配置更新。

github webhooks

GitHub源代码

猜你喜欢

转载自blog.csdn.net/weixin_43430036/article/details/83988780