spring cloud 配置文件热加载--@RefreshScope

spring cloud项目中,如果想要使配置文件中的配置修改后不用重启项目即生效,可以使用@RefreshScope配置来实现

1、添加Maven依赖

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

2、在配置类上加@RefreshScope注解,引入配置@Value

@Component
@RefreshScope
public class OtherConfig {
    /**是否需要保存切图*/
    @Value("${is.cut.save:false}")
    private String isCutSave;

    /**保存切图位置*/
    private static String cutSavePath;

    /** 静态字段赋值 */
    @Value("${cut.save.path:/server/files}")
    public void setCutSavePath(String cutSavePath) {
        OtherConfig.cutSavePath = cutSavePath;
    }

    public String getCutSavePath() {
        return cutSavePath;
    }

    public String getIsCutSave() {
        return isCutSave;
    }

    public void setIsCutSave(String isCutSave) {
        this.isCutSave = isCutSave;
    }
}

  tips:1.@Value给静态变量赋值,不能直接写在变量上,应该放在变量的set()方法上,且该方法不能被static修饰。其中需要在类上加入@Component注解。

     2.通过@Value(“${xxxx}”)可以获取属性文件中对应的值,但是如果属性文件中没有这个属性,则会报错。可以通过赋予默认值解决这个问题,如@Value("${xxxx:yyyy}")

3、配置文件

# 动态刷新配置--忽略权限拦截
management.security.enabled=false

# 是否需要保存切图
is.cut.save=false

# 保存切图位置
cut.save.path=/server/files

4、如果采用了consul配置中心:bootstrap.properties新增配置项

spring.cloud.consul.config.watch.enabled=true

项目启动后,更改注册中心配置,等待大约一秒后配置即可生效

5.1、如果采用的是本地配置文件:发送刷新请求

curl -X POST http://localhost:8080/refresh

management.security.enabled配置为false后,项目启动时可以在启动日志中发现下行日志,表明/refresh请求可用。我们修改配置文件后,调用该请求即可通知服务刷新配置,配置就生效了,无需重启项目。

5.2、在Spring Boot升级到2.0.3.RELEASE后需新增配置,此时刷新配置文件url为:http://localhost:8080/actuator/refresh

management.endpoints.web.exposure.include=refresh

  

参考资料:

1.Spring Cloud Consul实时动态更新配置:https://blog.csdn.net/fomeiherz/article/details/103525020?utm_medium=distribute.pc_relevant.none-task-blog-title-1&spm=1001.2101.3001.4242

2.Spring Cloud Config 实现配置中心,看这一篇就够了:https://www.cnblogs.com/fengzheng/p/11242128.html

原文地址:https://www.cnblogs.com/weihuang6620/p/13723219.html