问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Spring Cloud Config配置刷新详解

创作时间:
作者:
@小白创作中心

Spring Cloud Config配置刷新详解

引用
1
来源
1.
https://www.pianshen.com/article/5594871584/

本文将详细介绍Spring Cloud Config配置刷新的相关内容。通过添加actuator包、关闭权限认证、在controller上添加@RefreshScope注解以及执行刷新命令,可以实现配置的动态更新。

1. 添加actuator包

为了使/refresh URL处于可用状态,需要在项目中添加Spring Boot Actuator依赖。

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

2. 关闭权限认证

在手动测试时,需要关闭Actuator的安全认证,否则访问时会出现权限问题。

management:
  security:
    enabled: false

3. 添加@RefreshScope注解

在Controller类上添加@RefreshScope注解,这样在配置更改时,该类会进行特殊处理。

package com.thunisoft.thunisoftmicroservicetestconfig.controller;

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

@RefreshScope
@RestController
public class DisplayConfigController {

    @Value("${profile}")
    private String profile;

    @GetMapping("/")
    public String showConfig() {
        return this.profile;
    }
}

是否可以在其他使用配置的类上使用@RefreshScope注解,这一点尚未测试。

4. 刷新配置

使用curl命令刷新配置:

D:\curl\AMD64>curl -X POST http://localhost:7989/refresh
["config.client.version","profile"]
D:\curl\AMD64>

之后,配置会更新为最新值。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号