栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

@RefreshScope 刷新配置使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

@RefreshScope 刷新配置使用

RefeshScope 简易剥析

@RefreshScope详解

Springboot 使用@RefreshScope 注解,实现配置文件的动态加载

简易应用:

1、添加@RefreshScope注解

如果是使用@Value("${test.message}"),在引用类上添加注解

@Slf4j
@RefreshScope
@RestController
@RequestMapping("/test")
public class TestController {

    @Value("${test.message}") //引入配置
    private String message;


    @GetMapping("/testMethod")
    public Response>> testMethod() {
        log.info("message:" + message);
        return Response.success(message);
    }
}

如果是使用自定义注解配置类@ConfigurationProperties(prefix = "test"),在配置类添加注解,使用类直接引入

@Data
@Component
@RefreshScope
@ConfigurationProperties(prefix = "test")
public class ErrorMsgConfigProperties {

    
    private List> errorMsgList;

}
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private ErrorMsgConfigProperties errorMsgConfigProperties;

    @GetMapping("/testMethod")
    public Response>> testMethod() {
        List> errorMsgList = errorMsgConfigProperties.getErrorMsgList();
        return Response.success(errorMsgList);
    }
}

2、引入必要依赖和配置

        
        
            org.springframework.boot
            spring-boot-starter-actuator
            2.6.0
        
        
        
            org.springframework.cloud
            spring-cloud-context
            3.0.4
        

application.yml添加配置项

#注意2.0.3版本后暴露/refresh接入点的方式与旧版本不同,需要手动设置暴露点。
management:
  endpoints:
    web:
      exposure:
        include: "*" #默认值暴露 /actuator/info和/actuator/health,没有暴露/actuator/bus-refresh,这里把所有endpoints都暴露
#  server:
#    port: 1234 #actuator的端口可以单独定义,如果不定义的话,默认为{server.port}

3、运行项目,检验结果

推荐使用外部依赖jar启动(将application.yml文件置于启动jar的同等级目录),查看直观且方便修改,随后启动: jar -jar xxxx.jar

初步运行 localhost:9232/api/v1/test/testMethod,结果为:

{
    "code": "0",
    "message": "success",
    "requestId": null,
    "data": [
        {
            "code": "default",
            "message": "服务异常,请稍后重试!"
        }
    ]
}

接着修改配置文件内容(注,该配置文件为编译后文件,使用编译器的话,在target下;使用命令打包后启动的话,在classes下),直接打开外部依赖文件,修改内容后,

运行刷新链接:localhost:9232/api/v1/actuator/refresh  ,

因为配置了项目链接前缀,没配置的 请求: localhost:9232/actuator/refresh

[
    "test.info[0].message"
]

刷新结果会展示出你修改的参数,把涉及修改后差异的参数名返回,流程可参看顶部的“@RefreshScope详解”

现在再运行请求 localhost:9232/api/v1/test/testMethod,结果为:

{
    "code": "0",
    "message": "success",
    "requestId": null,
    "data": [
        {
            "code": "default",
            "message": "服务异常,请稍后重试!123123"
        }
    ]
}

刷新结果实现!

4、扩展实践

可自行探讨下,如何实现通过请求接口方式修改配置文件参数内容,实现动态刷新。

会有人反馈为啥不存储数据库,一步到位,流程也好操作?!

这是根据业务场景来,后续有空再补充。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/583289.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号