文章目錄
- 1、實現方法
- 2、配置依賴 + yaml
- 3、驗證效果
1、實現方法
環境:Nacos、Java、SpringBoot等
主要是在boostrap.yaml
中的data-id
屬性下配置refresh:true
來實現動態更新
2、配置依賴 + yaml
具體的版本參考官方的說明:官方版本說明
<!--讀取bootstrap文件--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency><!--統一配置管理--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><!--nacos 服務注冊發現--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency>
boostrap.yaml 配置
spring:application:name: xxx-service # 微服務名稱profiles:active: devcloud:nacos:server-addr: xxx.xxx.xxx.xxx:8848 # Nacos 地址config:namespace: xxxxxxxxxxxxxxxxxxx # 命名空間file-extension: yamlshared-configs:- data-id: shared-common.yamlrefresh: true # 要開啟刷新配置,下面的同理- data-id: shared-redis.yamlrefresh: true- data-id: shared-jdbc.yamlrefresh: true- data-id: shared-log.yamlrefresh: true- data-id: shared-swagger.yamlrefresh: true- data-id: shared-sentinel.yamlrefresh: truediscovery:namespace: xxxxxxxxxxxxxxxx # 命名空間
3、驗證效果
配置監聽,更新時打印配置到控制臺
package com.lingchuangdao.creator.config;import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;import java.util.Set;/*** 監聽配置變更事件,并打印所有變更的屬性。*/
@Component
@Slf4j
public class ConfigRefreshListener {private final Environment environment;public ConfigRefreshListener(Environment environment) {this.environment = environment;}@EventListenerpublic void onEnvironmentChangeEvent(EnvironmentChangeEvent event) {Set<String> keys = event.getKeys();log.info("配置已更新,變更的屬性數量: {}", keys.size());// 打印所有變更的配置項for (String key : keys) {log.info("配置變更 - 屬性: {}, 新值: {}", key, environment.getProperty(key));}}@EventListenerpublic void onRefreshScopeRefreshed(RefreshScopeRefreshedEvent event) {log.info("RefreshScope已刷新,Bean: {}", event.getName());}
}
控制臺輸出: