SpringBoot讀取自定義格式的Nacos配置的示例詳解
前言
在開發(fā)的過程中,如果遇到一些特殊情況,例如Java項(xiàng)目讀取.net項(xiàng)目的配置問題,由于.net項(xiàng)目的配置文件是非標(biāo)準(zhǔn)格式(yaml、json等)的自定義文件,需要springboot項(xiàng)目讀取自定義格式的nacos配置文件;由于springboot不知道直接讀取,故需求使用一些其他方法;以下是springboot讀取.net的配置文件的live-common-setting自定義配置文件的案例
自定義Nacos加載Bean
自定義一個(gè)bean,該bean實(shí)現(xiàn)InitializingBean接口的afterPropertiesSet()
public class NacosConfigLocalCatch implements InitializingBean {
/**
* 實(shí)現(xiàn)加載Nacos配置的邏輯
*/
@Override
public void afterPropertiesSet() {
}
}
自定義一個(gè)監(jiān)聽器,用于監(jiān)聽遠(yuǎn)程nacos變更
Listener listener=new Listener(){
@Override
public Executor getExecutor() {
return threadPoolExecutor;
}
@Override
public void receiveConfigInfo(String configInfo) {
log.info("{}#receiveConfigInfo receive configInfo. configInfo={}", configInfo);
compile(configInfo, nacosConfigInfo);
}
}
自定義一個(gè)Nacos配置載體
package com.vzan.config.securityurl;
import lombok.Data;
/**
* @author 歐益強(qiáng)
* @date 2023年11月13日 下午2:14:37
*/
@Data
public class NacosConfigInfo {
private String serverAddr;
private String namespace;
private String group;
private String dataId;
private boolean refresh = true;
public NacosConfigInfo() {
}
public NacosConfigInfo(String serverAddr, String namespace, String group, String dataId, boolean refresh) {
this.serverAddr = serverAddr;
this.namespace = namespace;
this.group = group;
this.dataId = dataId;
this.refresh = refresh;
}
public long getTimeout() {
return 5000L;
}
}
獲取監(jiān)聽bean完整類
/**
*
*/
package com.vzan.config.securityurl;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.google.common.collect.Lists;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author eakom
* @date 2023年11月13日 下午2:11:46
*/
@Slf4j
public class NacosConfigLocalCatch implements InitializingBean {
/**
* 定義需要獲取nacos配置的dataId
*/
private List<String> nacosConfigLocalCacheInfoList = Lists.newArrayList("live-common-setting");
/**
* 定義一個(gè)map,存在配置到本定
*/
private Map<String, String> localCatchMap = new HashMap<>();
@Resource
private NacosConfigProperties nacosConfigProperties;
private static ThreadPoolExecutor threadPoolExecutor;
/**
* 初始化線程
*/
static {
threadPoolExecutor = new ThreadPoolExecutor(2, 4, 1, TimeUnit.SECONDS, new LinkedBlockingDeque<>(100),
new ThreadPoolExecutor.CallerRunsPolicy());
}
/**
* 實(shí)現(xiàn)加載Nacos配置的邏輯
*/
@Override
public void afterPropertiesSet() {
nacosConfigLocalCacheInfoList.forEach(k -> {
NacosConfigInfo nacosConfigInfo = new NacosConfigInfo(nacosConfigProperties.getServerAddr(),
nacosConfigProperties.getNamespace(), nacosConfigProperties.getGroup(), k, true);
this.intNacosConfig(nacosConfigInfo);
});
}
/**
* 獲取ConfigService
*
* @param nacosConfigInfo NacosConfigInfo
* @return configService
*/
private ConfigService getConfigService(NacosConfigInfo nacosConfigInfo) {
String serverAddr = nacosConfigInfo.getServerAddr();
String nameSpace = nacosConfigInfo.getNamespace();
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
if (!StringUtils.isEmpty(nameSpace)) {
properties.put(PropertyKeyConst.NAMESPACE, nameSpace);
}
ConfigService configService;
try {
configService = NacosFactory.createConfigService(properties);
} catch (NacosException e) {
e.printStackTrace();
throw new RuntimeException("Nacos config 配置 異常");
}
return configService;
}
/**
* 初始化Nacos配置
* @param nacosConfigInfo
*/
private void intNacosConfig(NacosConfigInfo nacosConfigInfo) {
ConfigService configService = this.getConfigService(nacosConfigInfo);
try {
String config = configService.getConfig(nacosConfigInfo.getDataId(),
nacosConfigInfo.getGroup(),nacosConfigInfo.getTimeout());
log.info("{}#afterPropertiesSet init configInfo. configInfo={}", config);
// 初始化
compile(config, nacosConfigInfo);
// 監(jiān)聽
configService.addListener(nacosConfigInfo.getDataId(), nacosConfigInfo.getGroup(),
new Listener(){
@Override
public Executor getExecutor() {
return threadPoolExecutor;
}
@Override
public void receiveConfigInfo(String configInfo) {
log.info("{}#receiveConfigInfo receive configInfo. configInfo={}", configInfo);
compile(configInfo, nacosConfigInfo);
}
});
} catch (NacosException e) {
e.printStackTrace();
throw new RuntimeException("nacos server 監(jiān)聽 異常! dataId = " + nacosConfigInfo.getDataId());
}
}
/**
* 加載nacos配置到本定環(huán)境
* @param config
* @param nacosConfigInfo
*/
private void compile(String config, NacosConfigInfo nacosConfigInfo) {
if ("live-common-setting".equals(nacosConfigInfo.getDataId())) {
LiveCommonSetting json = JSONUtil.toBean(config, LiveCommonSetting.class);
if (json == null) {
log.error("common配置解析失敗");
return;
}
}
localCatchMap.put(nacosConfigInfo.getDataId(), config);
}
public String get(String dataId) {
return localCatchMap.get(dataId);
}
/**
*獲取配置
*/
public LiveCommonSetting getLiveCommonSetting() {
String config = localCatchMap.get("live-common-setting");
LiveCommonSetting fromJson = JSONUtil.toBean(config, LiveCommonSetting.class);
return fromJson;
}
}
初始化bean
@Configuration(proxyBeanMethods = false)
public class SecurityUrlConfig {
@Bean
@ConditionalOnProperty(value = "enabled.securityUrl",matchIfMissing = false)
public NacosConfigLocalCatch initNacosConfigLocalCatch() {
NacosConfigLocalCatch config=new NacosConfigLocalCatch();
return config;
}
}
代碼中讀取配置直接getLiveCommonSetting() 這個(gè)方法即可。
到此這篇關(guān)于SpringBoot讀取自定義格式的Nacos配置的示例詳解的文章就介紹到這了,更多相關(guān)SpringBoot讀取Nacos配置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java.math.BigDecimal的用法及加減乘除計(jì)算
這篇文章主要介紹了java.math.BigDecimal的用法及加減乘除計(jì)算,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
Java服務(wù)端性能優(yōu)化之JVM垃圾回收策略詳解
JVM垃圾回收策略涵蓋了基本原理、常見策略(如SerialGC、ParallelGC、CMS、G1GC)以及優(yōu)化建議,選擇合適的策略和調(diào)整參數(shù),如堆大小和GC日志,可以提高應(yīng)用性能和響應(yīng)速度,持續(xù)監(jiān)控和分析是關(guān)鍵步驟2025-03-03
SpringBoot 監(jiān)控管理模塊actuator沒有權(quán)限的問題解決方法
這篇文章主要介紹了SpringBoot 監(jiān)控管理模塊actuator沒有權(quán)限的問題解決方法,需要的朋友可以參考下2017-12-12
springboot引用kettle實(shí)現(xiàn)對接oracle數(shù)據(jù)的示例代碼
這篇文章主要介紹了springboot引用kettle實(shí)現(xiàn)對接oracle數(shù)據(jù),其實(shí)kettle集成到springboot里面沒有多少代碼,這個(gè)功能最主要的還是ktr文件的編寫,只要ktr編寫好了,放到指定文件夾下,寫個(gè)定時(shí)任務(wù)就完事了,需要的朋友可以參考下2022-12-12
mybatis-plus雪花算法增強(qiáng)idworker的實(shí)現(xiàn)
今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,進(jìn)一步增強(qiáng)實(shí)現(xiàn)生成分布式唯一ID,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07

