1
0
mirror of https://gitee.com/mirrors/Spring-Cloud-Alibaba.git synced 2021-06-26 13:25:11 +08:00

support spring.cloud.nacos.config.enabled

This commit is contained in:
flystar32 2019-02-19 16:31:17 +08:00
parent 5a5ff5c444
commit 4fe795166b
5 changed files with 80 additions and 57 deletions

View File

@ -17,6 +17,7 @@
package org.springframework.cloud.alibaba.nacos;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -27,15 +28,17 @@ import org.springframework.context.annotation.Configuration;
@Configuration
public class NacosConfigBootstrapConfiguration {
@Bean
public NacosPropertySourceLocator nacosPropertySourceLocator() {
return new NacosPropertySourceLocator();
}
@Bean
@ConditionalOnMissingBean
public NacosConfigProperties nacosConfigProperties() {
return new NacosConfigProperties();
}
@Bean
@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public NacosPropertySourceLocator nacosPropertySourceLocator(
NacosConfigProperties nacosConfigProperties) {
return new NacosPropertySourceLocator(nacosConfigProperties);
}
}

View File

@ -18,6 +18,7 @@ package org.springframework.cloud.alibaba.nacos;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -44,9 +45,14 @@ public class NacosConfigProperties {
public static final String PREFIX = "spring.cloud.nacos.config";
private static final Logger LOGGER = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(NacosConfigProperties.class);
/**
* whether to enable nacos config.
*/
private boolean enabled = true;
/**
* nacos config server address
*/
@ -137,11 +143,15 @@ public class NacosConfigProperties {
this.activeProfiles = environment.getActiveProfiles();
}
public void setActiveProfiles(String[] activeProfiles) {
this.activeProfiles = activeProfiles;
// todo sts support
public boolean isEnabled() {
return enabled;
}
// todo sts support
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getServerAddr() {
return serverAddr;
@ -243,10 +253,6 @@ public class NacosConfigProperties {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getActiveProfiles() {
return activeProfiles;
}
@ -275,6 +281,14 @@ public class NacosConfigProperties {
this.extConfig = extConfig;
}
public void setName(String name) {
this.name = name;
}
public void setActiveProfiles(String[] activeProfiles) {
this.activeProfiles = activeProfiles;
}
public static class Config {
/**
* the data id of extended configuration
@ -316,16 +330,17 @@ public class NacosConfigProperties {
@Override
public String toString() {
return "NacosConfigProperties{" + "serverAddr='" + serverAddr + '\''
+ ", encode='" + encode + '\'' + ", group='" + group + '\''
+ ", sharedDataids='" + this.sharedDataids + '\''
+ ", refreshableDataids='" + this.refreshableDataids + '\'' + ", prefix='"
+ prefix + '\'' + ", fileExtension='" + fileExtension + '\''
+ ", timeout=" + timeout + ", endpoint='" + endpoint + '\''
+ ", namespace='" + namespace + '\'' + ", accessKey='" + accessKey + '\''
+ ", secretKey='" + secretKey + '\'' + ", contextPath='" + contextPath
+ '\'' + ", clusterName='" + clusterName + '\'' + ", name='" + name + '\''
+ ", activeProfiles=" + Arrays.toString(activeProfiles) + '}';
return "NacosConfigProperties{" + "enabled=" + enabled + ", serverAddr='"
+ serverAddr + '\'' + ", encode='" + encode + '\'' + ", group='" + group
+ '\'' + ", prefix='" + prefix + '\'' + ", fileExtension='"
+ fileExtension + '\'' + ", timeout=" + timeout + ", endpoint='"
+ endpoint + '\'' + ", namespace='" + namespace + '\'' + ", accessKey='"
+ accessKey + '\'' + ", secretKey='" + secretKey + '\''
+ ", contextPath='" + contextPath + '\'' + ", clusterName='" + clusterName
+ '\'' + ", name='" + name + '\'' + ", activeProfiles="
+ Arrays.toString(activeProfiles) + ", sharedDataids='" + sharedDataids
+ '\'' + ", refreshableDataids='" + refreshableDataids + '\''
+ ", extConfig=" + extConfig + '}';
}
public ConfigService configServiceInstance() {
@ -348,7 +363,7 @@ public class NacosConfigProperties {
return configService;
}
catch (Exception e) {
LOGGER.error("create config service error!properties={},e=,", this, e);
log.error("create config service error!properties={},e=,", this, e);
return null;
}
}

View File

@ -33,7 +33,7 @@ import java.util.*;
* @author pbting
*/
public class NacosPropertySourceBuilder {
private static final Logger LOGGER = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(NacosPropertySourceBuilder.class);
private static final Properties EMPTY_PROPERTIES = new Properties();
@ -68,9 +68,6 @@ public class NacosPropertySourceBuilder {
NacosPropertySource build(String dataId, String group, String fileExtension,
boolean isRefreshable) {
Properties p = loadNacosData(dataId, group, fileExtension);
if (p == null) {
p = EMPTY_PROPERTIES;
}
NacosPropertySource nacosPropertySource = new NacosPropertySource(group, dataId,
propertiesToMap(p), new Date(), isRefreshable);
NacosPropertySourceRepository.collectNacosPropertySources(nacosPropertySource);
@ -82,7 +79,7 @@ public class NacosPropertySourceBuilder {
try {
data = configService.getConfig(dataId, group, timeout);
if (!StringUtils.isEmpty(data)) {
LOGGER.info(String.format("Loading nacos data, dataId: '%s', group: '%s'",
log.info(String.format("Loading nacos data, dataId: '%s', group: '%s'",
dataId, group));
if (fileExtension.equalsIgnoreCase("properties")) {
@ -101,21 +98,20 @@ public class NacosPropertySourceBuilder {
}
}
catch (NacosException e) {
LOGGER.error("get data from Nacos error,dataId:{}, ", dataId, e);
log.error("get data from Nacos error,dataId:{}, ", dataId, e);
}
catch (Exception e) {
LOGGER.error("parse data from Nacos error,dataId:{},data:{},", dataId, data,
e);
log.error("parse data from Nacos error,dataId:{},data:{},", dataId, data, e);
}
return null;
return EMPTY_PROPERTIES;
}
@SuppressWarnings("unchecked")
private Map<String, Object> propertiesToMap(Properties properties) {
Map<String, Object> result = new HashMap<>(16);
Enumeration<String> tmpKeys = (Enumeration<String>) properties.propertyNames();
while (tmpKeys.hasMoreElements()) {
String key = tmpKeys.nextElement();
Enumeration<String> keys = (Enumeration<String>) properties.propertyNames();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
Object value = properties.getProperty(key);
if (value != null) {
result.put(key, ((String) value).trim());
@ -126,4 +122,5 @@ public class NacosPropertySourceBuilder {
}
return result;
}
}

View File

@ -19,7 +19,6 @@ package org.springframework.cloud.alibaba.nacos.client;
import com.alibaba.nacos.api.config.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosConfigProperties;
import org.springframework.cloud.alibaba.nacos.NacosPropertySourceRepository;
import org.springframework.cloud.alibaba.nacos.refresh.NacosContextRefresher;
@ -40,7 +39,7 @@ import java.util.List;
@Order(0)
public class NacosPropertySourceLocator implements PropertySourceLocator {
private static final Logger LOGGER = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(NacosPropertySourceLocator.class);
private static final String NACOS_PROPERTY_SOURCE_NAME = "NACOS";
private static final String SEP1 = "-";
@ -49,22 +48,21 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
private static final List<String> SUPPORT_FILE_EXTENSION = Arrays.asList("properties",
"yaml", "yml");
@Autowired
private NacosPropertySourceBuilder nacosPropertySourceBuilder;
private NacosConfigProperties nacosConfigProperties;
public NacosPropertySourceLocator() {
public NacosPropertySourceLocator(NacosConfigProperties nacosConfigProperties) {
this.nacosConfigProperties = nacosConfigProperties;
}
private NacosPropertySourceBuilder nacosPropertySourceBuilder;
@Override
public PropertySource<?> locate(Environment env) {
ConfigService configService = nacosConfigProperties.configServiceInstance();
if (null == configService) {
LOGGER.warn(
"no instance of config service found, can't load config from nacos");
log.warn("no instance of config service found, can't load config from nacos");
return null;
}
long timeout = nacosConfigProperties.getTimeout();
@ -167,8 +165,7 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
private void loadNacosDataIfPresent(final CompositePropertySource composite,
final String dataId, final String group, String fileExtension,
boolean isRefreshable) {
if (NacosContextRefresher.loadCount.get() != 0) {
if (NacosContextRefresher.getRefreshCount() != 0) {
NacosPropertySource ps;
if (!isRefreshable) {
ps = NacosPropertySourceRepository.getNacosPropertySource(dataId);
@ -184,18 +181,22 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
fileExtension, isRefreshable);
composite.addFirstPropertySource(ps);
}
}
private static void checkDataIdFileExtension(String[] sharedDataIdArry) {
StringBuilder stringBuilder = new StringBuilder();
outline: for (int i = 0; i < sharedDataIdArry.length; i++) {
for (int i = 0; i < sharedDataIdArry.length; i++) {
boolean isLegal = false;
for (String fileExtension : SUPPORT_FILE_EXTENSION) {
if (sharedDataIdArry[i].indexOf(fileExtension) > 0) {
continue outline;
isLegal = true;
break;
}
}
stringBuilder.append(sharedDataIdArry[i] + ",");
// add tips
if (!isLegal) {
stringBuilder.append(sharedDataIdArry[i] + ",");
}
}
if (stringBuilder.length() > 0) {

View File

@ -19,6 +19,7 @@ package org.springframework.cloud.alibaba.nacos.refresh;
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.boot.context.event.ApplicationReadyEvent;
@ -51,10 +52,10 @@ import java.util.concurrent.atomic.AtomicLong;
public class NacosContextRefresher
implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {
private final static Logger LOGGER = LoggerFactory
private final static Logger log = LoggerFactory
.getLogger(NacosContextRefresher.class);
public static final AtomicLong loadCount = new AtomicLong(0);
private static final AtomicLong REFRESH_COUNT = new AtomicLong(0);
private final NacosRefreshProperties refreshProperties;
@ -110,7 +111,7 @@ public class NacosContextRefresher
listener = new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
loadCount.incrementAndGet();
refreshCountIncrement();
String md5 = "";
if (!StringUtils.isEmpty(configInfo)) {
try {
@ -120,16 +121,15 @@ public class NacosContextRefresher
}
catch (NoSuchAlgorithmException
| UnsupportedEncodingException e) {
LOGGER.warn("[Nacos] unable to get md5 for dataId: " + dataId,
log.warn("[Nacos] unable to get md5 for dataId: " + dataId,
e);
}
}
refreshHistory.add(dataId, md5);
applicationContext.publishEvent(
new RefreshEvent(this, null, "Refresh Nacos config"));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Refresh Nacos config group{},dataId{}", group,
dataId);
if (log.isDebugEnabled()) {
log.debug("Refresh Nacos config group{},dataId{}", group, dataId);
}
}
@ -149,4 +149,11 @@ public class NacosContextRefresher
}
}
public static long getRefreshCount() {
return REFRESH_COUNT.get();
}
public static void refreshCountIncrement() {
REFRESH_COUNT.incrementAndGet();
}
}