从nacos中读取自定义配置文件的两种方案

您所在的位置:网站首页 nacos读取配置文件 从nacos中读取自定义配置文件的两种方案

从nacos中读取自定义配置文件的两种方案

2023-06-14 16:32| 来源: 网络整理| 查看: 265

1.通过配置实现

1.bootstrap配置

2.通过实现InitializingBean接口实现 NacosConfig.java @Configuration public class NacosConfig { /** * 前提条件 要求 serverAddr、namespace、group使用bootstrap.yml 中 spring cloud nacos config 的。 * @return */ @Bean public Map nacosConfigLocalCacheInfoMap() { // key:dataId, value:对应数据类型 Map map = new HashMap(); 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; /** * nacos 配置 信息 */ 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; /** * 获取nacos groupId *

默认NacosConstant.GROUP_ID

* * @return nacos groupId */ private String group; /** * 获取nacos dataId * * @return nacos dataId */ 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 localCatchMap = new HashMap(); @Resource(name = "nacosConfigLocalCacheInfoMap") private Map nacosConfigLocalCacheInfoMap; @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(); /** * bean初始化 触发 执行 * * @throws Exception */ @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() { /** * 监听-工作线程池 * @return */ @Override public Executor getExecutor() { return threadPoolExecutor; } /** * 接受到Nacos 具体 配置信息变动 * * @param configInfo */ @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); } /** * 获取ConfigService * * @return */ 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; } public T 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 demo 0.0.1-SNAPSHOT demo Demo project for Spring Boot 1.8 2020.0.0 org.springframework.boot spring-boot-starter-web com.alibaba.cloud spring-cloud-starter-alibaba-nacos-config com.alibaba fastjson 1.2.75 org.projectlombok lombok com.alibaba.cloud spring-cloud-alibaba-dependencies 2.2.4.RELEASE pom import org.springframework.cloud spring-cloud-dependencies Hoxton.SR8 org.springframework.boot spring-boot-maven-plugin 复制代码


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3