在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 {@Autowiredprivate JdbcTemplate jdbcTemplate;private Map<String, String> configCache = new ConcurrentHashMap<>();@PostConstructpublic 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<>();@Autowiredpublic 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 {@Autowiredprivate StringRedisTemplate redisTemplate;private final Map<String, String> configCache = new ConcurrentHashMap<>();@PostConstructpublic 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;@Overridepublic 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() {@Overridepublic 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;}@Overridepublic 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;// 監聽特定配置變更@ApolloConfigChangeListenerpublic 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;@PostConstructpublic 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+事件 | ★★★ | ★★★ | 小型 | 事件觸發 |
總結
動態配置修改能夠提升系統的靈活性和可管理性,選擇合適的動態配置方案應綜合考慮應用規模、團隊熟悉度、基礎設施現狀和業務需求。
無論選擇哪種方案,確保配置的安全性、一致性和可追溯性都是至關重要的。