Spring Cloud Config(四):手动刷新配置

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/u010647035/article/details/85413224

1、概述

当实现了配置信息与代码分离以后,我们必然会考虑如何在修改配置文件后,不重启服务的前提下,动态刷新服务实例上下文的配置信息呢?本节就来学习一下 spring cloud Config “半自动”刷新的方式,之所以称为“半自动”刷新,是因为修改配置文件后需要手动请求一下刷新api来刷新服务实例的配置信息,当然还有全自动刷新的方式,完全不需要手动干预,该方式将在下文介绍,言归正传,开始我的学习旅程。

服务名称 地址 描述
lkf-cloud-eureka localhost:8888 注册中心
lkf-cloud-config-jdbc localhost:1000 配置中心
lkf-eureka-client localhost:8000 业务服务实例

lkf-eureka-client 从 lkf-cloud-config-jdbc(配置中心) 拉取配置信息,注册服务到 lkf-cloud-eureka (注册中心)

2、lkf-eureka-client 配置

需要引入 actuator 监控模块,用于动态刷新配置信息,spring-boot-starter-actuator 具有监控的功能,actuator 创建了多个监控端点,如/beans、/health 等,可以监控程序在运行时状态,其中也包括 /refresh 动态刷新的功能。

2.1、引入依赖项:

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

2.2、配置文件:

#配置环境
spring.cloud.config.profile=dev
#配置中心地址
spring.cloud.config.uri=http://localhost:1000/lkf
#配置文件名称
spring.cloud.config.name=eureka-client
#配置文件版本号
spring.cloud.config.label=v0.0.1

2.3、添加测试类:

给加载变量的类标注 @RefreshScope, 使用该注解的类,在执行 /refresh 的时候就会 更新变量值,

@RequestMapping(value = "/lkf")
@RefreshScope
@RestController
public class TestController {
    @Value("${refresh.scope.value}")
    private String refreshScope;

    @GetMapping(value = "/test")
    public String testMethod() {
        return refreshScope;
    }
}

4、lkf-cloud-config-jdbc 注册中心配置

采用 Spring Cloud Config(三):基于JDBC搭建配置中心,作为本文的配置中心。在数据库中添加 lkf-eureka-client 服务实例所需要的配置文件,如下:

在这里插入图片描述

5、测试验证

启动注册中心:lkf-cloud-eureka

启动配置中心:lkf-cloud-config-jdbc

启动服务实例:lkf-eureka-client

在注册中心看到 lkf-eureka-client 服务时,说明已经成功从配置中心读取配置文件。

请求 http://localhost:8000/lkf/test 地址,看到刚才在MySQL中添加的变量 refresh.scope.value 的值为 I’m testing。

在这里插入图片描述

接着修改配置中心的配置,将变量 refresh.scope.value 值,修改为 I’m testing2,然后请求地址:curl -X POST http://localhost:8000/actuator/refresh,执行成功后,再次访问地址:
http://localhost:8000/lkf/test,我们发现修改的变量值已经生效了。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u010647035/article/details/85413224
今日推荐