1.通过配置实现
1.bootstrap配置
2.通过实现InitializingBean接口实现
NacosConfig.java
@Configuration
public class NacosConfig {
@Bean
public Map
// key:dataId, value:对应数据类型
Map
map.put(“sumJSON”, User.class); // 自定义json格式实体类映射 sumJSON为在nacos上的配置文件的dataId 具体数据为json格式数据
map.put(“testText”, String.class);
map.put(“testJson1”, List.class);
map.put(“testJson2”, User.class);
map.put(“testInteger”, Integer.class);
return map; }
}
NacosConfigInfo.java
package com.findme.demo.config;
import org.springframework.context.annotation.Configuration;
public class NacosConfigInfo {
public NacosConfigInfo(String serverAddr, String namespace, String group, String dataId, boolean refresh, Class cls) {
this.serverAddr = serverAddr;
this.namespace = namespace;
this.group = group;
this.dataId = dataId;
this.refresh = refresh;
this.cls = cls;
}
public NacosConfigInfo() {
}
private String serverAddr;
private String namespace;
private String dataId;
private boolean refresh = true;
private Class cls = String.class;
public String getServerAddr() {
return serverAddr;
}
public void setServerAddr(String serverAddr) {
this.serverAddr = serverAddr;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public boolean isRefresh() {
return refresh;
}
public void setRefresh(boolean refresh) {
this.refresh = refresh;
}
public Class getCls() {
return cls;
}
public void setCls(Class cls) {
this.cls = cls;
}
public long getTimeout() {
return 5000L;
}
}
NacosConfigLocalCatch.java
package com.findme.demo.config;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.fastjson.JSON
;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
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;
@Component
public class NacosConfigLocalCatch implements InitializingBean {
private Map
@Resource(name = "nacosConfigLocalCacheInfoMap") private MapnacosConfigLocalCacheInfoMap; @Autowired private NacosConfigProperties nacosConfigProperties; private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 2, 4, 1, TimeUnit.SECONDS, new linkedBlockingDeque<>(100), new ThreadPoolExecutor.CallerRunsPolicy() ); protected final Logger logger = LoggerFactory.getLogger(getClass()); protected final String clazzSimpleName = getClass().getSimpleName(); @Override public void afterPropertiesSet() throws Exception { nacosConfigLocalCacheInfoMap.forEach((k, v) -> { NacosConfigInfo nacosConfigInfo = new NacosConfigInfo(nacosConfigProperties.getServerAddr(), nacosConfigProperties.getNamespace(), nacosConfigProperties.getGroup(), k, true, nacosConfigLocalCacheInfoMap.get(k)); this.listener(nacosConfigInfo); }); } public void listener(NacosConfigInfo nacosConfigInfo) { Listener listener = new Listener() { @Override public Executor getExecutor() { return threadPoolExecutor; } @Override public void receiveConfigInfo(String configInfo) { logger.info("{}#receiveConfigInfo receive configInfo. configInfo={}", clazzSimpleName, configInfo); compile(configInfo, nacosConfigInfo); } }; ConfigService configService = this.getConfigService(nacosConfigInfo); String config = null; try { config = configService.getConfig(nacosConfigInfo.getDataId(), nacosConfigInfo.getGroup(), nacosConfigInfo.getTimeout()); logger.info("{}#afterPropertiesSet init configInfo. configInfo={}", clazzSimpleName, config); // 初始化 compile(config, nacosConfigInfo); // 监听 configService.addListener(nacosConfigInfo.getDataId(), nacosConfigInfo.getGroup(), listener); } catch (NacosException e) { e.printStackTrace(); throw new RuntimeException("nacos server 监听 异常! dataId = " + nacosConfigInfo.getDataId()); } } private void compile(String config, NacosConfigInfo nacosConfigInfo) { Object initValue = JSON.parseObject(config, nacosConfigInfo.getCls()); localCatchMap.put(nacosConfigInfo.getDataId(), initValue); } private ConfigService getConfigService(NacosConfigInfo nacosConfigInfo) { String serverAddr = nacosConfigInfo.getServerAddr(); String nameSpace = nacosConfigInfo.getNamespace(); Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr); // 设置为public后会控制台会循环打印
// properties.put(PropertyKeyConst.NAMESPACE, nameSpace);
ConfigService configService;
try {
configService = NacosFactory.createConfigService(properties);
} catch (NacosException e) {
e.printStackTrace();
throw new RuntimeException(“Nacos config 配置 异常”);
}
return configService;
}
publicT get(String dataId, Class cls) { if (cls != nacosConfigLocalCacheInfoMap.get(dataId)) { throw new IllegalArgumentException("类型异常"); } return (T) localCatchMap.get(dataId); }
}
testController.java
@Autowired
private NacosConfigLocalCatch nacosConfigLocalCatch;
@RequestMapping("/test2")
public String test2() {
logger.info("-------------test2---------------");
String testText = nacosConfigLocalCatch.get("testText", String.class);
List testJson1 = nacosConfigLocalCatch.get("testJson1", List.class);
User testJson2 = nacosConfigLocalCatch.get("testJson2", User.class);
Integer testInteger = nacosConfigLocalCatch.get("testInteger", Integer.class);
return testText+" , "+testJson1+" , "+testJson2+" , "+testInteger;
}
3.pom配置文件
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.2.RELEASE
com.findme demo0.0.1-SNAPSHOT demo Demo project for Spring Boot 1.8 2020.0.0 org.springframework.boot spring-boot-starter-webcom.alibaba.cloud spring-cloud-starter-alibaba-nacos-configcom.alibaba fastjson1.2.75 org.projectlombok lombokcom.alibaba.cloud spring-cloud-alibaba-dependencies2.2.4.RELEASE pom import org.springframework.cloud spring-cloud-dependenciesHoxton.SR8 org.springframework.boot spring-boot-maven-plugin



