服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring boot 应用实现动态刷新配置详解

Spring boot 应用实现动态刷新配置详解

2021-12-24 12:48lbl2018 Java教程

这篇文章主要介绍了spring boot 配置动态刷新实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

前面写过一篇《Spring Cloud Bus 实现配置实时更新》,是使用配置中心管理配置,使用spring cloud bus来实现实时通知。对于简单的SpringBoot应用,其实不需要使用配置中心也可以实现动态刷新配置。

参考:http://www.zzvips.com/article/215175.html

文章使用springboot版本:2.0.4.RELEASE springcloud版本Finchley.SR1

1. 依赖

需要引入下面三个依赖:

?
1
2
3
compile('org.springframework.cloud:spring-cloud-starter-config')
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-web')

(1)spring-cloud-starter-config是为了实现刷新配置

(2)spring-boot-starter-actuator是为了暴露修改/刷新配置的接口

(3)spring-boot-starter-web是为了可以访问暴露的修改/刷新配置的接口

2. 配置暴露接口

application.properties

?
1
2
3
4
#使用端口9999
server.port=9999
#暴露接口
management.endpoints.web.exposure.include=env,refresh

(1)env接口,可以获取配置(GET),也可以修改配置(POST)

(2)refresh接口,可以刷新配置(POST),使得@RefreshScope标注的value可以重新注入。

3. @RefreshScope

在需要实时刷新配置的地方加上@RefreshScope注解

4. 启动服务

5. 修改配置

访问localhost:9999/actuator/env(GET),可以获得此时的配置

访问localhost:9999/actuator/env(POST)

?
1
2
3
4
{
    "name":"somekey",
    "value":"newvalue"
}

如上可以把配置中somekey对应的值改为newvalue

6. 获取配置值

不调用刷新接口,直接获取注入的配置值,发现还是旧的值

7. 刷新配置 重新获取

访问localhost:9999/actuator/refresh(POST)刷新配置

重新获取注入的配置值,发现是新的值

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/lblblblblzdx/article/details/81784237

延伸 · 阅读

精彩推荐