前言: 在不啟動服務(wù)的情況下,修改nacos配置文件,可以動態(tài)的獲取到配置文件的信息,實現(xiàn)動態(tài)刷新的效果。
文章來源:http://www.zghlxwxcb.cn/news/detail-706582.html
1、依賴jar包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos- config</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.9.9</version>
</dependency>
2、相關(guān)代碼
package com.tanhua.sso.config;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@RefreshScope
@Component
public class NacosConfigService {
private static final String ROUTE_CONFIG_ID = "bsc-auth- app. yml";
private static final String GROUP_ID = "DEFAULT GROUP";
@Autowired
private NacosConfigManager nacosconfigManager;
@SneakyThrows
public Map<String, String> getAuthAppInfo() {
Map<String, String> map = new HashMap<>();
//讀取nacos配置文件
String config = nacosconfigManager.getConfigService().getConfig(ROUTE_CONFIG_ID, GROUP_ID, 5000);
//將獲取到的yml配置文件轉(zhuǎn)為JSON字符串
JsonNode allNodes = new ObjectMapper(new YAMLFactory()).readTree(config);
//將節(jié)點數(shù)據(jù)封裝成所需要的格式,我需要map(此步驟省略)
return map;
}
}
3、注意事項
1、注解@RefreshScope為動態(tài)刷新,如果需要檢驗是否成功??梢詫懸粋€Junit測試,while(true)循環(huán)打印獲取到的信息。我們修改nacos配置文件,看測試打印的結(jié)果是否會動態(tài)修改。
2、獲取的nacos配置文件包含所有指定yml里的數(shù)據(jù)(包括自定義),我們可以只選取需要的部分進行封裝即可。文章來源地址http://www.zghlxwxcb.cn/news/detail-706582.html
到了這里,關(guān)于java動態(tài)獲取nacos配置文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!