引言
在springboot应用中,配置信息通常通过application.properties或application.yml文件静态定义,应用启动后这些配置就固定下来了。
但我们常常需要在不重启应用的情况下动态修改配置,以实现灰度发布、a/b测试、动态调整线程池参数、切换功能开关等场景。
本文将介绍springboot中10种实现配置动态修改的方法。
1. @refreshscope结合actuator刷新端点
spring cloud提供的@refreshscope注解是实现配置热刷新的基础方法。
实现步骤
- 添加依赖:
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-actuator</artifactid>
</dependency>
<dependency>
<groupid>org.springframework.cloud</groupid>
<artifactid>spring-cloud-starter</artifactid>
</dependency>
- 开启刷新端点:
management.endpoints.web.exposure.include=refresh
- 给配置类添加
@refreshscope注解:
@refreshscope
@restcontroller
public class configcontroller {
@value("${app.message:default message}")
private string message;
@getmapping("/message")
public string getmessage() {
return message;
}
}
- 修改配置后,调用刷新端点:
curl -x post http://localhost:8080/actuator/refresh
优缺点
优点
- 实现简单,利用spring cloud提供的现成功能
- 无需引入额外的配置中心
缺点
- 需要手动触发刷新
- 只能刷新单个实例,在集群环境中需要逐个调用
- 只能重新加载配置源中的值,无法动态添加新配置
2. spring cloud config配置中心
spring cloud config提供了一个中心化的配置服务器,支持配置文件的版本控制和动态刷新。
实现步骤
- 设置config server:
<dependency>
<groupid>org.springframework.cloud</groupid>
<artifactid>spring-cloud-config-server</artifactid>
</dependency>
@springbootapplication
@enableconfigserver
public class configserverapplication {
public static void main(string[] args) {
springapplication.run(configserverapplication.class, args);
}
}
spring.cloud.config.server.git.uri=https://github.com/your-repo/config
- 客户端配置:
<dependency>
<groupid>org.springframework.cloud</groupid>
<artifactid>spring-cloud-starter-config</artifactid>
</dependency>
<dependency>
<groupid>org.springframework.cloud</groupid>
<artifactid>spring-cloud-starter-bootstrap</artifactid>
</dependency>
# bootstrap.properties spring.application.name=my-service spring.cloud.config.uri=http://localhost:8888
<dependency>
<groupid>org.springframework.cloud</groupid>
<artifactid>spring-cloud-starter-bus-amqp</artifactid>
</dependency>
优缺点
优点
- 提供配置的版本控制
- 支持配置的环境隔离
- 通过spring cloud bus可实现集群配置的自动刷新
缺点
- 引入了额外的基础设施复杂性
- 依赖额外的消息总线实现集群刷新
- 配置更新有一定延迟
3. 基于数据库的配置存储
将配置信息存储在数据库中,通过定时任务或事件触发机制实现配置刷新。
实现方案
- 创建配置表:
create table app_config (
config_key varchar(100) primary key,
config_value varchar(500) not null,
description varchar(200),
update_time timestamp
);
- 实现配置加载和刷新:
@service
public class databaseconfigservice {
@autowired
private jdbctemplate jdbctemplate;
private map<string, string> configcache = new concurrenthashmap<>();
@postconstruct
public void init() {
loadallconfig();
}
@scheduled(fixeddelay = 60000) // 每分钟刷新
public void loadallconfig() {
list<map<string, object>> rows = jdbctemplate.queryforlist("select config_key, config_value from app_config");
for (map<string, object> row : rows) {
configcache.put((string) row.get("config_key"), (string) row.get("config_value"));
}
}
public string getconfig(string key, string defaultvalue) {
return configcache.getordefault(key, defaultvalue);
}
}
优缺点
优点
- 简单直接,无需额外组件
- 可以通过管理界面实现配置可视化管理
- 配置持久化,重启不丢失
缺点
- 刷新延迟取决于定时任务间隔
- 数据库成为潜在的单点故障
- 需要自行实现配置的版本控制和权限管理
4. 使用zookeeper管理配置
利用zookeeper的数据变更通知机制,实现配置的实时动态更新。
实现步骤
- 添加依赖:
<dependency>
<groupid>org.apache.curator</groupid>
<artifactid>curator-recipes</artifactid>
<version>5.1.0</version>
</dependency>
- 实现配置监听:
@component
public class zookeeperconfigmanager {
private final curatorframework client;
private final map<string, string> configcache = new concurrenthashmap<>();
@autowired
public zookeeperconfigmanager(curatorframework client) {
this.client = client;
initconfig();
}
private void initconfig() {
try {
string configpath = "/config";
if (client.checkexists().forpath(configpath) == null) {
client.create().creatingparentsifneeded().forpath(configpath);
}
list<string> keys = client.getchildren().forpath(configpath);
for (string key : keys) {
string fullpath = configpath + "/" + key;
byte[] data = client.getdata().forpath(fullpath);
configcache.put(key, new string(data));
// 添加监听器
nodecache nodecache = new nodecache(client, fullpath);
nodecache.getlistenable().addlistener(() -> {
byte[] newdata = nodecache.getcurrentdata().getdata();
configcache.put(key, new string(newdata));
system.out.println("config updated: " + key + " = " + new string(newdata));
});
nodecache.start();
}
} catch (exception e) {
throw new runtimeexception("failed to initialize config from zookeeper", e);
}
}
public string getconfig(string key, string defaultvalue) {
return configcache.getordefault(key, defaultvalue);
}
}
优缺点
优点
- 实时通知,配置变更后立即生效
- zookeeper提供高可用性保证
- 适合分布式环境下的配置同步
缺点
- 需要维护zookeeper集群
- 配置管理不如专用配置中心直观
- 存储大量配置时性能可能受影响
5. redis发布订阅机制实现配置更新
利用redis的发布订阅功能,实现配置变更的实时通知。
实现方案
- 添加依赖:
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>
- 实现配置刷新监听:
@component
public class redisconfigmanager {
@autowired
private stringredistemplate redistemplate;
private final map<string, string> configcache = new concurrenthashmap<>();
@postconstruct
public void init() {
loadallconfig();
subscribeconfigchanges();
}
private void loadallconfig() {
set<string> keys = redistemplate.keys("config:*");
if (keys != null) {
for (string key : keys) {
string value = redistemplate.opsforvalue().get(key);
configcache.put(key.replace("config:", ""), value);
}
}
}
private void subscribeconfigchanges() {
redistemplate.getconnectionfactory().getconnection().subscribe(
(message, pattern) -> {
string[] parts = new string(message.getbody()).split("=");
if (parts.length == 2) {
configcache.put(parts[0], parts[1]);
}
},
"config-channel".getbytes()
);
}
public string getconfig(string key, string defaultvalue) {
return configcache.getordefault(key, defaultvalue);
}
// 更新配置的方法(管理端使用)
public void updateconfig(string key, string value) {
redistemplate.opsforvalue().set("config:" + key, value);
redistemplate.convertandsend("config-channel", key + "=" + value);
}
}
优缺点
优点
- 实现简单,利用redis的发布订阅机制
- 集群环境下配置同步实时高效
- 可以与现有redis基础设施集成
缺点
- 依赖redis的可用性
- 需要确保消息不丢失
- 缺乏版本控制和审计功能
6. 自定义配置加载器和监听器
通过自定义spring的propertysource和文件监听机制,实现本地配置文件的动态加载。
实现方案
@component
public class dynamicpropertysource implements applicationcontextaware {
private static final logger logger = loggerfactory.getlogger(dynamicpropertysource.class);
private configurableapplicationcontext applicationcontext;
private file configfile;
private properties properties = new properties();
private filewatcher filewatcher;
@override
public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {
this.applicationcontext = (configurableapplicationcontext) applicationcontext;
try {
configfile = new file("config/dynamic.properties");
if (configfile.exists()) {
loadproperties();
registerpropertysource();
startfilewatcher();
}
} catch (exception e) {
logger.error("failed to initialize dynamic property source", e);
}
}
private void loadproperties() throws ioexception {
try (fileinputstream fis = new fileinputstream(configfile)) {
properties.load(fis);
}
}
private void registerpropertysource() {
mutablepropertysources propertysources = applicationcontext.getenvironment().getpropertysources();
propertiespropertysource propertysource = new propertiespropertysource("dynamic", properties);
propertysources.addfirst(propertysource);
}
private void startfilewatcher() {
filewatcher = new filewatcher(configfile);
filewatcher.setlistener(new filechangelistener() {
@override
public void filechanged() {
try {
properties newprops = new properties();
try (fileinputstream fis = new fileinputstream(configfile)) {
newprops.load(fis);
}
// 更新已有属性
mutablepropertysources propertysources = applicationcontext.getenvironment().getpropertysources();
propertiespropertysource oldsource = (propertiespropertysource) propertysources.get("dynamic");
if (oldsource != null) {
propertysources.replace("dynamic", new propertiespropertysource("dynamic", newprops));
}
// 发布配置变更事件
applicationcontext.publishevent(new environmentchangeevent(collections.singleton("dynamic")));
logger.info("dynamic properties reloaded");
} catch (exception e) {
logger.error("failed to reload properties", e);
}
}
});
filewatcher.start();
}
// 文件监听器实现(简化版)
private static class filewatcher extends thread {
private final file file;
private filechangelistener listener;
private long lastmodified;
public filewatcher(file file) {
this.file = file;
this.lastmodified = file.lastmodified();
}
public void setlistener(filechangelistener listener) {
this.listener = listener;
}
@override
public void run() {
try {
while (!thread.interrupted()) {
long newlastmodified = file.lastmodified();
if (newlastmodified != lastmodified) {
lastmodified = newlastmodified;
if (listener != null) {
listener.filechanged();
}
}
thread.sleep(5000); // 检查间隔
}
} catch (interruptedexception e) {
// 线程中断
}
}
}
private interface filechangelistener {
void filechanged();
}
}
优缺点
优点
- 不依赖外部服务,完全自主控制
- 可以监控本地文件变更实现实时刷新
- 适合单体应用或简单场景
缺点
- 配置分发需要额外机制支持
- 集群环境下配置一致性难以保证
- 需要较多自定义代码
7. apollo配置中心
携程开源的apollo是一个功能强大的分布式配置中心,提供配置修改、发布、回滚等完整功能。
实现步骤
- 添加依赖:
<dependency>
<groupid>com.ctrip.framework.apollo</groupid>
<artifactid>apollo-client</artifactid>
<version>2.0.1</version>
</dependency>
- 配置apollo客户端:
# app.properties app.id=your-app-id apollo.meta=http://apollo-config-service:8080
- 启用apollo:
@springbootapplication
@enableapolloconfig
public class application {
public static void main(string[] args) {
springapplication.run(application.class, args);
}
}
- 使用配置:
@component
public class sampleservice {
@value("${timeout:1000}")
private int timeout;
// 监听特定配置变更
@apolloconfigchangelistener
public void onconfigchange(configchangeevent event) {
if (event.ischanged("timeout")) {
configchange change = event.getchange("timeout");
system.out.println("timeout changed from " + change.getoldvalue() + " to " + change.getnewvalue());
// 可以在这里执行特定逻辑,如重新初始化线程池等
}
}
}
优缺点
优点
- 提供完整的配置管理界面
- 支持配置的灰度发布
- 具备权限控制和操作审计
- 集群自动同步,无需手动刷新
缺点
- 需要部署和维护apollo基础设施
- 学习成本相对较高
- 小型项目可能过于重量级
8. nacos配置管理
阿里开源的nacos既是服务发现组件,也是配置中心,广泛应用于spring cloud alibaba生态。
实现步骤
- 添加依赖:
<dependency>
<groupid>com.alibaba.cloud</groupid>
<artifactid>spring-cloud-starter-alibaba-nacos-config</artifactid>
</dependency>
- 配置nacos:
# bootstrap.properties spring.application.name=my-service spring.cloud.nacos.config.server-addr=127.0.0.1:8848 # 支持多配置文件 spring.cloud.nacos.config.extension-configs[0].data-id=database.properties spring.cloud.nacos.config.extension-configs[0].group=default_group spring.cloud.nacos.config.extension-configs[0].refresh=true
- 使用配置:
@restcontroller
@refreshscope
public class configcontroller {
@value("${uselocalcache:false}")
private boolean uselocalcache;
@getmapping("/cache")
public boolean getuselocalcache() {
return uselocalcache;
}
}
优缺点
优点
- 与spring cloud alibaba生态无缝集成
- 配置和服务发现功能二合一
- 轻量级,易于部署和使用
- 支持配置的动态刷新和监听
缺点
- 部分高级功能不如apollo丰富
- 需要额外维护nacos服务器
- 需要使用bootstrap配置机制
9. spring boot admin与actuator结合
spring boot admin提供了web ui来管理和监控spring boot应用,结合actuator的环境端点可以实现配置的可视化管理。
实现步骤
- 设置spring boot admin服务器:
<dependency>
<groupid>de.codecentric</groupid>
<artifactid>spring-boot-admin-starter-server</artifactid>
<version>2.7.0</version>
</dependency>
@springbootapplication
@enableadminserver
public class adminserverapplication {
public static void main(string[] args) {
springapplication.run(adminserverapplication.class, args);
}
}
- 配置客户端应用:
<dependency>
<groupid>de.codecentric</groupid>
<artifactid>spring-boot-admin-starter-client</artifactid>
<version>2.7.0</version>
</dependency>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-actuator</artifactid>
</dependency>
spring.boot.admin.client.url=http://localhost:8080 management.endpoints.web.exposure.include=* management.endpoint.env.post.enabled=true
- 通过spring boot admin ui修改配置
spring boot admin提供ui界面,可以查看和修改应用的环境属性。通过发送post请求到/actuator/env端点修改配置。
优缺点
优点
- 提供可视化操作界面
- 与spring boot自身监控功能集成
- 无需额外的配置中心组件
缺点
- 修改的配置不持久化,应用重启后丢失
- 安全性较弱,需要额外加强保护
- 不适合大规模生产环境的配置管理
10. 使用@configurationproperties结合eventlistener
利用spring的事件机制和@configurationproperties绑定功能,实现配置的动态更新。
实现方案
- 定义配置属性类:
@component
@configurationproperties(prefix = "app")
@setter
@getter
public class applicationproperties {
private int connectiontimeout;
private int readtimeout;
private int maxconnections;
private map<string, string> features = new hashmap<>();
// 初始化客户端的方法
public httpclient buildhttpclient() {
return httpclient.newbuilder()
.connecttimeout(duration.ofmillis(connectiontimeout))
.build();
}
}
- 添加配置刷新机制:
@component
@requiredargsconstructor
public class configrefresher {
private final applicationproperties properties;
private final applicationcontext applicationcontext;
private httpclient httpclient;
@postconstruct
public void init() {
refreshhttpclient();
}
@eventlistener(environmentchangeevent.class)
public void onenvironmentchange() {
refreshhttpclient();
}
private void refreshhttpclient() {
httpclient = properties.buildhttpclient();
system.out.println("httpclient refreshed with timeout: " + properties.getconnectiontimeout());
}
public httpclient gethttpclient() {
return this.httpclient;
}
// 手动触发配置刷新的方法
public void refreshproperties(map<string, object> newprops) {
propertiespropertysource propertysource = new propertiespropertysource(
"dynamic", converttoproperties(newprops));
configurableenvironment env = (configurableenvironment) applicationcontext.getenvironment();
env.getpropertysources().addfirst(propertysource);
// 触发环境变更事件
applicationcontext.publishevent(new environmentchangeevent(newprops.keyset()));
}
private properties converttoproperties(map<string, object> map) {
properties properties = new properties();
for (map.entry<string, object> entry : map.entryset()) {
properties.put(entry.getkey(), entry.getvalue().tostring());
}
return properties;
}
}
优缺点
优点
- 强类型的配置绑定
- 利用spring内置机制,无需额外组件
- 灵活性高,可与其他配置源结合
缺点
- 需要编写较多代码
- 配置变更通知需要额外实现
- 不适合大规模或跨服务的配置管理
方法比较与选择指南
| 方法 | 易用性 | 功能完整性 | 适用规模 | 实时性 |
|---|---|---|---|---|
| @refreshscope+actuator | ★★★★★ | ★★ | 小型 | 手动触发 |
| spring cloud config | ★★★ | ★★★★ | 中大型 | 需配置 |
| 数据库存储 | ★★★★ | ★★★ | 中型 | 定时刷新 |
| zookeeper | ★★★ | ★★★ | 中型 | 实时 |
| redis发布订阅 | ★★★★ | ★★★ | 中型 | 实时 |
| 自定义配置加载器 | ★★ | ★★★ | 小型 | 定时刷新 |
| apollo | ★★★ | ★★★★★ | 中大型 | 实时 |
| nacos | ★★★★ | ★★★★ | 中大型 | 实时 |
| spring boot admin | ★★★★ | ★★ | 小型 | 手动触发 |
| @configurationproperties+事件 | ★★★ | ★★★ | 小型 | 事件触发 |
总结
动态配置修改能够提升系统的灵活性和可管理性,选择合适的动态配置方案应综合考虑应用规模、团队熟悉度、基础设施现状和业务需求。
无论选择哪种方案,确保配置的安全性、一致性和可追溯性都是至关重要的。
以上就是springboot动态修改配置的十种方法的详细内容,更多关于springboot动态修改配置的资料请关注代码网其它相关文章!
发表评论