1. Implement the configuration
1. The bootstrap configuration
2. Implement the InitializingBean interface
NacosConfig.java
@Configuration
public class NacosConfig {
/** * Prerequisites serverAddr, Namespace, and Group must use spring Cloud nacos config in bootstrap.yml. *@return* /
@Bean
public Map<String, Class> nacosConfigLocalCacheInfoMap(a) {
// key:dataId, value: corresponding data type
Map<String, Class> map = new HashMap<>();
map.put("sumJSON", User.class); // A custom JSON format entity class maps sumJSON to the configuration file dataId on nacOS
map.put("testText", String.class);
map.put("testJson1", List.class);
map.put("testJson2", User.class);
map.put("testInteger", Integer.class);
returnmap; }}Copy the code
NacosConfigInfo.java
package com.findme.demo.config;
import org.springframework.context.annotation.Configuration;
/** * nacOS configuration information */
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(a) {}private String serverAddr;
private String namespace;
/** * get nacos groupId * <p> default nacosconstant. GROUP_ID</p> **@return nacos groupId
*/
private String group;
/** * get nacos dataId **@return nacos dataId
*/
private String dataId;
private boolean refresh = true;
private Class cls = String.class;
public String getServerAddr(a) {
return serverAddr;
}
public void setServerAddr(String serverAddr) {
this.serverAddr = serverAddr;
}
public String getNamespace(a) {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public String getGroup(a) {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getDataId(a) {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public boolean isRefresh(a) {
return refresh;
}
public void setRefresh(boolean refresh) {
this.refresh = refresh;
}
public Class getCls(a) {
return cls;
}
public void setCls(Class cls) {
this.cls = cls;
}
public long getTimeout(a) {
return 5000L; }}Copy the code
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<String, Object> localCatchMap = new HashMap<>();
@Resource(name = "nacosConfigLocalCacheInfoMap")
private Map<String, Class> 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();
/** * The bean initializes to trigger execution **@throws Exception
*/
@Override
public void afterPropertiesSet(a) 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() {
/** * listen - worker thread pool *@return* /
@Override
public Executor getExecutor(a) {
return threadPoolExecutor;
}
/** * Received Nacos configuration information change **@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);
/ / initialization
compile(config, nacosConfigInfo);
/ / to monitor
configService.addListener(nacosConfigInfo.getDataId(), nacosConfigInfo.getGroup(), listener);
} catch (NacosException e) {
e.printStackTrace();
throw new RuntimeException("Nacos Server listening exception! dataId = "+ nacosConfigInfo.getDataId()); }}private void compile(String config, NacosConfigInfo nacosConfigInfo) {
Object initValue = JSON.parseObject(config, nacosConfigInfo.getCls());
localCatchMap.put(nacosConfigInfo.getDataId(), initValue);
}
/** * Get 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);
// If set to public, the console will print circularly
// properties.put(PropertyKeyConst.NAMESPACE, nameSpace);
ConfigService configService;
try {
configService = NacosFactory.createConfigService(properties);
} catch (NacosException e) {
e.printStackTrace();
throw new RuntimeException("Nacos config configuration exception");
}
return configService;
}
public <T> T get(String dataId, Class<T> cls) {
if(cls ! = nacosConfigLocalCacheInfoMap.get(dataId)) {throw new IllegalArgumentException("Abnormal type");
}
return(T) localCatchMap.get(dataId); }}Copy the code
testController.java
@Autowired
private NacosConfigLocalCatch nacosConfigLocalCatch;
@RequestMapping("/test2")
public String test2(a) {
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;
}
Copy the code
3. Pom configuration file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2. RELEASE</version>
<relativePath/> <! -- lookup parent from repository -->
</parent>
<groupId>com.findme</groupId>
<artifactId>demo</artifactId>
<version>0.0.1 - the SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2020.0.0</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<! -- nacos-config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.4. RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR8</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Copy the code