SpringCloud config refresh(配置文件刷新)

现在来解决上一篇的遗留问题
在这里插入图片描述
Spring Cloud Config分服务端和客户端,服务端负责将git(svn)中存储的配置文件发布成REST接口,客户端可以从服务端REST接口获取配置。但客户端并不能主动感知到配置的变化,从而主动去获取新的配置。
客户端如何去主动获取新的配置信息呢,springcloud已经给我们提供了解决方案,每个客户端通过POST方法触发各自的/refresh。

修改 config-client 项目可以达到 refresh 的功能。

1.在pom.xml 中添加依赖

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

增加了spring-boot-starter-actuator包,spring-boot-starter-actuator是一套监控的功能,可以监控程序在运行时状态,其中就包括/refresh的功能

2.如何开启更新机制

需要给加载变量的类上面加上**@RefreshScope**,在客户端执行 /refresh 的时候就会更新此类下面的变量值。代码如下:

package com.example.configclient.web;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


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

    @Value("${neo.hello}")
    private String hello;

    @RequestMapping("/test")
    public String from() {
        return this.hello;
    }

}

springboot 1.5.X 以上默认开通了安全认证,且 springboot 2.x 默认只开启了info、health的访问,(*代表开启所有访问)
所以在配置文件bootstrap.yml 如下:

spring:
  application:
    name: config-client
  cloud:
    config:
      name: config-single-client
      profile: dev
      uri: http://localhost:8770/
      label: master
server:
  port: 8771



#特别注意:上面这些与spring-cloud相关的属性必须配置在bootstrap.yml,config部分内容才能被正确加载。
#因为config的相关配置会先于application.yml,而bootstrap.yml的加载也是先于application.yml。

management:
  security:
    enabled: false
  # springboot 1.5.X 以上默认开通了安全认证
  endpoints:
    web:
      exposure:
        include: "*"
        # include: refresh,health,info #打开部分
        # springboot 2.x 默认只开启了info、health的访问,*代表开启所有访问

增加了:

management:
  security:
    enabled: false
  # springboot 1.5.X 以上默认开通了安全认证
  endpoints:
    web:
      exposure:
        include: "*"
        # include: refresh,health,info #打开部分
        # springboot 2.x 默认只开启了info、health的访问,*代表开启所有访问

这样我们就改造完了。以post请求的方式来访问 http://localhost:8771/actuator/refresh 就会更新修改后的配置文件。

3.测试

启动 config-serve、 config-client 服务,浏览器访问: http://localhost:8771/test ,返回的信息如下:

config-single-client-dev

修改 github 库中 neo.hello=config-single-client-dev666666
可以在win上面打开cmd执行curl -X POST http://localhost:8771/actuator/refresh
也可以在postman 上执行,图如下:
在这里插入图片描述
再次在浏览器上访问:http://localhost:8771/test ,返回的信息如下:

config-single-client-dev666666

客户端已经得到了最新的值。

参考资料

http://www.ityouknow.com/springcloud/2017/05/23/springcloud-config-svn-refresh.html
https://blog.csdn.net/Anenan/article/details/85134208

我们还有更好的方法来处理配置文件的刷新,Spring Cloud给了我们更好解决方案(SpringCloud Bus 消息总线),后面文章来介绍。

发布了50 篇原创文章 · 获赞 75 · 访问量 8644

猜你喜欢

转载自blog.csdn.net/weixin_40991408/article/details/104189827