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

sync & commit in finchley

This commit is contained in:
fangjian0423
2019-10-30 13:10:10 +08:00
parent 6be45914c8
commit 15465b5612
436 changed files with 7099 additions and 3202 deletions

View File

@@ -16,16 +16,16 @@
package com.alibaba.cloud.nacos;
import com.alibaba.cloud.nacos.refresh.NacosContextRefresher;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import com.alibaba.cloud.nacos.refresh.NacosRefreshProperties;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.cloud.nacos.refresh.NacosContextRefresher;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import com.alibaba.cloud.nacos.refresh.NacosRefreshProperties;
/**
* @author juven.xuxb
*/
@@ -41,8 +41,12 @@ public class NacosConfigAutoConfiguration {
return BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(),
NacosConfigProperties.class);
}
NacosConfigProperties nacosConfigProperties = new NacosConfigProperties();
return nacosConfigProperties;
return new NacosConfigProperties();
}
@Bean
public NacosConfigManager nacosConfigManager() {
return new NacosConfigManager();
}
@Bean
@@ -57,10 +61,10 @@ public class NacosConfigAutoConfiguration {
@Bean
public NacosContextRefresher nacosContextRefresher(
NacosConfigProperties nacosConfigProperties,
NacosConfigManager nacosConfigManager,
NacosRefreshProperties nacosRefreshProperties,
NacosRefreshHistory refreshHistory) {
return new NacosContextRefresher(nacosRefreshProperties, refreshHistory,
nacosConfigProperties.configServiceInstance());
nacosConfigManager.getConfigService());
}
}

View File

@@ -16,13 +16,13 @@
package com.alibaba.cloud.nacos;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
/**
* @author xiaojing
*/
@@ -36,10 +36,17 @@ public class NacosConfigBootstrapConfiguration {
return new NacosConfigProperties();
}
@Bean
@ConditionalOnMissingBean
public NacosConfigManager nacosConfigManager() {
return new NacosConfigManager();
}
@Bean
public NacosPropertySourceLocator nacosPropertySourceLocator(
NacosConfigManager nacosConfigManager,
NacosConfigProperties nacosConfigProperties) {
return new NacosPropertySourceLocator(nacosConfigProperties);
return new NacosPropertySourceLocator(nacosConfigManager, nacosConfigProperties);
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos;
import java.util.Objects;
import com.alibaba.cloud.nacos.diagnostics.analyzer.NacosConnectionFailureException;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author <a href="mailto:liaochunyhm@live.com">liaochuntao</a>
*/
public class NacosConfigManager {
private static ConfigService service = null;
@Autowired
private NacosConfigProperties properties;
public ConfigService getConfigService() {
if (Objects.isNull(service)) {
try {
service = NacosFactory
.createConfigService(properties.getConfigServiceProperties());
properties.initConfigService(service);
}
catch (NacosException e) {
throw new NacosConnectionFailureException(properties.getServerAddr(),
e.getMessage(), e);
}
}
return service;
}
}

View File

@@ -16,44 +16,76 @@
package com.alibaba.cloud.nacos;
import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY;
import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME;
import static com.alibaba.nacos.api.PropertyKeyConst.CONTEXT_PATH;
import static com.alibaba.nacos.api.PropertyKeyConst.ENCODE;
import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT;
import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT_PORT;
import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE;
import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY;
import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import javax.annotation.PostConstruct;
import com.alibaba.nacos.api.config.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY;
import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME;
import static com.alibaba.nacos.api.PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT;
import static com.alibaba.nacos.api.PropertyKeyConst.CONFIG_RETRY_TIME;
import static com.alibaba.nacos.api.PropertyKeyConst.CONTEXT_PATH;
import static com.alibaba.nacos.api.PropertyKeyConst.ENABLE_REMOTE_SYNC_CONFIG;
import static com.alibaba.nacos.api.PropertyKeyConst.ENCODE;
import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT;
import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT_PORT;
import static com.alibaba.nacos.api.PropertyKeyConst.MAX_RETRY;
import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE;
import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY;
import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR;
/**
* nacos properties
* Nacos properties.
*
* @author leijuan
* @author xiaojing
* @author pbting
* @author <a href="mailto:lyuzb@lyuzb.com">lyuzb</a>
*/
@ConfigurationProperties(NacosConfigProperties.PREFIX)
public class NacosConfigProperties {
/**
* Prefix of {@link NacosConfigProperties}.
*/
public static final String PREFIX = "spring.cloud.nacos.config";
private static final Logger log = LoggerFactory
.getLogger(NacosConfigProperties.class);
@Autowired
private Environment environment;
@PostConstruct
public void init() {
this.overrideFromEnv();
}
private void overrideFromEnv() {
if (StringUtils.isEmpty(this.getServerAddr())) {
String serverAddr = environment
.resolvePlaceholders("${spring.cloud.nacos.config.server-addr:}");
if (StringUtils.isEmpty(serverAddr)) {
serverAddr = environment
.resolvePlaceholders("${spring.cloud.nacos.server-addr:}");
}
this.setServerAddr(serverAddr);
}
}
/**
* nacos config server address
* nacos config server address.
*/
private String serverAddr;
@@ -68,9 +100,10 @@ public class NacosConfigProperties {
private String group = "DEFAULT_GROUP";
/**
* nacos config dataId prefix
* nacos config dataId prefix.
*/
private String prefix;
/**
* the suffix of nacos config dataId, also the file extension of config content.
*/
@@ -81,6 +114,30 @@ public class NacosConfigProperties {
*/
private int timeout = 3000;
/**
* nacos maximum number of tolerable server reconnection errors.
*/
private String maxRetry;
/**
* nacos get config long poll timeout.
*/
private String configLongPollTimeout;
/**
* nacos get config failure retry time.
*/
private String configRetryTime;
/**
* If you want to pull it yourself when the program starts to get the configuration
* for the first time, and the registered Listener is used for future configuration
* updates, you can keep the original code unchanged, just add the system parameter:
* enableRemoteSyncConfig = "true" ( But there is network overhead); therefore we
* recommend that you use {@link ConfigService#getConfigAndSignListener} directly.
*/
private boolean enableRemoteSyncConfig = false;
/**
* endpoint for Nacos, the domain name of a service, through which the server address
* can be dynamically obtained.
@@ -108,10 +165,13 @@ public class NacosConfigProperties {
private String contextPath;
/**
* nacos config cluster name
* nacos config cluster name.
*/
private String clusterName;
/**
* nacos config dataId name.
*/
private String name;
/**
@@ -174,6 +234,38 @@ public class NacosConfigProperties {
this.timeout = timeout;
}
public String getMaxRetry() {
return maxRetry;
}
public void setMaxRetry(String maxRetry) {
this.maxRetry = maxRetry;
}
public String getConfigLongPollTimeout() {
return configLongPollTimeout;
}
public void setConfigLongPollTimeout(String configLongPollTimeout) {
this.configLongPollTimeout = configLongPollTimeout;
}
public String getConfigRetryTime() {
return configRetryTime;
}
public void setConfigRetryTime(String configRetryTime) {
this.configRetryTime = configRetryTime;
}
public Boolean getEnableRemoteSyncConfig() {
return enableRemoteSyncConfig;
}
public void setEnableRemoteSyncConfig(Boolean enableRemoteSyncConfig) {
this.enableRemoteSyncConfig = enableRemoteSyncConfig;
}
public String getEndpoint() {
return endpoint;
}
@@ -262,15 +354,71 @@ public class NacosConfigProperties {
this.name = name;
}
/**
* @see NacosConfigManager#getConfigService() .
* @return ConfigService
*/
@Deprecated
public ConfigService configServiceInstance() {
return configService;
}
public void initConfigService(ConfigService configService) {
this.configService = configService;
}
public Properties getConfigServiceProperties() {
Properties properties = new Properties();
properties.put(SERVER_ADDR, Objects.toString(this.serverAddr, ""));
properties.put(ENCODE, Objects.toString(this.encode, ""));
properties.put(NAMESPACE, Objects.toString(this.namespace, ""));
properties.put(ACCESS_KEY, Objects.toString(this.accessKey, ""));
properties.put(SECRET_KEY, Objects.toString(this.secretKey, ""));
properties.put(CONTEXT_PATH, Objects.toString(this.contextPath, ""));
properties.put(CLUSTER_NAME, Objects.toString(this.clusterName, ""));
properties.put(MAX_RETRY, Objects.toString(this.maxRetry, ""));
properties.put(CONFIG_LONG_POLL_TIMEOUT,
Objects.toString(this.configLongPollTimeout, ""));
properties.put(CONFIG_RETRY_TIME, Objects.toString(this.configRetryTime, ""));
properties.put(ENABLE_REMOTE_SYNC_CONFIG,
Objects.toString(this.enableRemoteSyncConfig, ""));
String endpoint = Objects.toString(this.endpoint, "");
if (endpoint.contains(":")) {
int index = endpoint.indexOf(":");
properties.put(ENDPOINT, endpoint.substring(0, index));
properties.put(ENDPOINT_PORT, endpoint.substring(index + 1));
}
else {
properties.put(ENDPOINT, endpoint);
}
return properties;
}
@Override
public String toString() {
return "NacosConfigProperties{" + "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 + '\''
+ ", sharedDataids='" + sharedDataids + '\'' + ", refreshableDataids='"
+ refreshableDataids + '\'' + ", extConfig=" + extConfig + '}';
}
public static class Config {
/**
* the data id of extended configuration
* the data id of extended configuration.
*/
private String dataId;
/**
* the group of extended configuration, the default value is DEFAULT_GROUP
* the group of extended configuration, the default value is DEFAULT_GROUP.
*/
private String group = "DEFAULT_GROUP";
/**
* whether to support dynamic refresh, the default does not support .
*/
@@ -299,53 +447,7 @@ public class NacosConfigProperties {
public void setRefresh(boolean refresh) {
this.refresh = refresh;
}
}
@Override
public String toString() {
return "NacosConfigProperties{" + "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 + '\''
+ ", sharedDataids='" + sharedDataids + '\'' + ", refreshableDataids='"
+ refreshableDataids + '\'' + ", extConfig=" + extConfig + '}';
}
public ConfigService configServiceInstance() {
if (null != configService) {
return configService;
}
Properties properties = new Properties();
properties.put(SERVER_ADDR, Objects.toString(this.serverAddr, ""));
properties.put(ENCODE, Objects.toString(this.encode, ""));
properties.put(NAMESPACE, Objects.toString(this.namespace, ""));
properties.put(ACCESS_KEY, Objects.toString(this.accessKey, ""));
properties.put(SECRET_KEY, Objects.toString(this.secretKey, ""));
properties.put(CONTEXT_PATH, Objects.toString(this.contextPath, ""));
properties.put(CLUSTER_NAME, Objects.toString(this.clusterName, ""));
String endpoint = Objects.toString(this.endpoint, "");
if (endpoint.contains(":")) {
int index = endpoint.indexOf(":");
properties.put(ENDPOINT, endpoint.substring(0, index));
properties.put(ENDPOINT_PORT, endpoint.substring(index + 1));
}
else {
properties.put(ENDPOINT, endpoint);
}
try {
configService = NacosFactory.createConfigService(properties);
return configService;
}
catch (Exception e) {
log.error("create config service error!properties={},e=,", this, e);
return null;
}
}
}

View File

@@ -16,11 +16,11 @@
package com.alibaba.cloud.nacos;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.cloud.nacos.client.NacosPropertySource;
import com.google.common.collect.Lists;
/**
* @author xiaojing
@@ -34,9 +34,7 @@ public class NacosPropertySourceRepository {
* @return all nacos properties from application context
*/
public static List<NacosPropertySource> getAll() {
List<NacosPropertySource> result = new ArrayList<>();
result.addAll(NACOS_PROPERTY_SOURCE_REPOSITORY.values());
return result;
return Lists.newArrayList(NACOS_PROPERTY_SOURCE_REPOSITORY.values());
}
public static void collectNacosPropertySources(

View File

@@ -16,23 +16,22 @@
package com.alibaba.cloud.nacos.client;
import java.io.StringReader;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.util.StringUtils;
import com.alibaba.cloud.nacos.NacosPropertySourceRepository;
import com.alibaba.cloud.nacos.parser.NacosDataParserHandler;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
/**
* @author xiaojing
* @author pbting
@@ -83,24 +82,19 @@ public class NacosPropertySourceBuilder {
String data = null;
try {
data = configService.getConfig(dataId, group, timeout);
if (!StringUtils.isEmpty(data)) {
log.info(String.format("Loading nacos data, dataId: '%s', group: '%s'",
dataId, group));
if (fileExtension.equalsIgnoreCase("properties")) {
Properties properties = new Properties();
properties.load(new StringReader(data));
return properties;
}
else if (fileExtension.equalsIgnoreCase("yaml")
|| fileExtension.equalsIgnoreCase("yml")) {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(new ByteArrayResource(data.getBytes()));
return yamlFactory.getObject();
}
if (StringUtils.isEmpty(data)) {
log.warn(
"Ignore the empty nacos configuration and get it based on dataId[{}] & group[{}]",
dataId, group);
return EMPTY_PROPERTIES;
}
log.info(String.format(
"Loading nacos data, dataId: '%s', group: '%s', data: %s", dataId,
group, data));
Properties properties = NacosDataParserHandler.getInstance()
.parseNacosData(data, fileExtension);
return properties == null ? EMPTY_PROPERTIES : properties;
}
catch (NacosException e) {
log.error("get data from Nacos error,dataId:{}, ", dataId, e);
@@ -117,9 +111,9 @@ public class NacosPropertySourceBuilder {
Enumeration<String> keys = (Enumeration<String>) properties.propertyNames();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
Object value = properties.getProperty(key);
String value = properties.getProperty(key);
if (value != null) {
result.put(key, ((String) value).trim());
result.put(key, value.trim());
}
else {
result.put(key, null);

View File

@@ -16,23 +16,26 @@
package com.alibaba.cloud.nacos.client;
import java.util.Arrays;
import java.util.List;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.NacosPropertySourceRepository;
import com.alibaba.cloud.nacos.parser.NacosDataParserHandler;
import com.alibaba.cloud.nacos.refresh.NacosContextRefresher;
import com.alibaba.nacos.api.config.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.NacosPropertySourceRepository;
import com.alibaba.cloud.nacos.refresh.NacosContextRefresher;
import com.alibaba.nacos.api.config.ConfigService;
/**
* @author xiaojing
* @author pbting
@@ -42,25 +45,31 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
private static final Logger log = LoggerFactory
.getLogger(NacosPropertySourceLocator.class);
private static final String NACOS_PROPERTY_SOURCE_NAME = "NACOS";
private static final String SEP1 = "-";
private static final String DOT = ".";
private static final String SHARED_CONFIG_SEPARATOR_CHAR = "[,]";
private static final List<String> SUPPORT_FILE_EXTENSION = Arrays.asList("properties",
"yaml", "yml");
private NacosPropertySourceBuilder nacosPropertySourceBuilder;
private NacosConfigProperties nacosConfigProperties;
public NacosPropertySourceLocator(NacosConfigProperties nacosConfigProperties) {
private NacosConfigManager nacosConfigManager;
public NacosPropertySourceLocator(NacosConfigManager nacosConfigManager,
NacosConfigProperties nacosConfigProperties) {
this.nacosConfigManager = nacosConfigManager;
this.nacosConfigProperties = nacosConfigProperties;
}
@Override
public PropertySource<?> locate(Environment env) {
ConfigService configService = nacosConfigProperties.configServiceInstance();
ConfigService configService = nacosConfigManager.getConfigService();
if (null == configService) {
log.warn("no instance of config service found, can't load config from nacos");
@@ -99,14 +108,14 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
return;
}
String[] sharedDataIdArry = sharedDataIds.split(SHARED_CONFIG_SEPARATOR_CHAR);
checkDataIdFileExtension(sharedDataIdArry);
String[] sharedDataIdArray = sharedDataIds.split(SHARED_CONFIG_SEPARATOR_CHAR);
checkDataIdFileExtension(sharedDataIdArray);
for (int i = 0; i < sharedDataIdArry.length; i++) {
String dataId = sharedDataIdArry[i];
for (int i = 0; i < sharedDataIdArray.length; i++) {
String dataId = sharedDataIdArray[i];
String fileExtension = dataId.substring(dataId.lastIndexOf(".") + 1);
boolean isRefreshable = checkDataIdIsRefreshbable(refreshDataIds,
sharedDataIdArry[i]);
boolean isRefreshable = checkDataIdIsRefreshable(refreshDataIds,
sharedDataIdArray[i]);
loadNacosDataIfPresent(compositePropertySource, dataId, "DEFAULT_GROUP",
fileExtension, isRefreshable);
@@ -114,18 +123,18 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
}
private void loadExtConfiguration(CompositePropertySource compositePropertySource) {
if (nacosConfigProperties.getExtConfig() == null
|| nacosConfigProperties.getExtConfig().isEmpty()) {
List<NacosConfigProperties.Config> extConfigs = nacosConfigProperties
.getExtConfig();
if (CollectionUtils.isEmpty(extConfigs)) {
return;
}
List<NacosConfigProperties.Config> extConfigs = nacosConfigProperties
.getExtConfig();
checkExtConfiguration(extConfigs);
for (NacosConfigProperties.Config config : extConfigs) {
String dataId = config.getDataId();
String fileExtension = dataId.substring(dataId.lastIndexOf(".") + 1);
String fileExtension = dataId.substring(dataId.lastIndexOf(DOT) + 1);
loadNacosDataIfPresent(compositePropertySource, dataId, config.getGroup(),
fileExtension, config.isRefresh());
}
@@ -137,7 +146,7 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
String dataId = extConfigs.get(i).getDataId();
if (dataId == null || dataId.trim().length() == 0) {
throw new IllegalStateException(String.format(
"the [ spring.cloud.nacos.config.ext-config[%s] ] must give a dataid",
"the [ spring.cloud.nacos.config.ext-config[%s] ] must give a dataId",
i));
}
dataIds[i] = dataId;
@@ -152,8 +161,13 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
String fileExtension = properties.getFileExtension();
String nacosGroup = properties.getGroup();
// load directly once by default
loadNacosDataIfPresent(compositePropertySource, dataIdPrefix, nacosGroup,
fileExtension, true);
// load with suffix, which have a higher priority than the default
loadNacosDataIfPresent(compositePropertySource,
dataIdPrefix + DOT + fileExtension, nacosGroup, fileExtension, true);
// Loaded with profile, which have a higher priority than the suffix
for (String profile : environment.getActiveProfiles()) {
String dataId = dataIdPrefix + SEP1 + profile + DOT + fileExtension;
loadNacosDataIfPresent(compositePropertySource, dataId, nacosGroup,
@@ -164,56 +178,58 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
private void loadNacosDataIfPresent(final CompositePropertySource composite,
final String dataId, final String group, String fileExtension,
boolean isRefreshable) {
if (NacosContextRefresher.getRefreshCount() != 0) {
NacosPropertySource ps;
if (!isRefreshable) {
ps = NacosPropertySourceRepository.getNacosPropertySource(dataId);
}
else {
ps = nacosPropertySourceBuilder.build(dataId, group, fileExtension, true);
}
if (null == dataId || dataId.trim().length() < 1) {
return;
}
if (null == group || group.trim().length() < 1) {
return;
}
NacosPropertySource propertySource = this.loadNacosPropertySource(dataId, group,
fileExtension, isRefreshable);
this.addFirstPropertySource(composite, propertySource, false);
}
composite.addFirstPropertySource(ps);
private NacosPropertySource loadNacosPropertySource(final String dataId,
final String group, String fileExtension, boolean isRefreshable) {
if (NacosContextRefresher.getRefreshCount() != 0) {
if (!isRefreshable) {
return NacosPropertySourceRepository.getNacosPropertySource(dataId);
}
}
else {
NacosPropertySource ps = nacosPropertySourceBuilder.build(dataId, group,
fileExtension, isRefreshable);
composite.addFirstPropertySource(ps);
return nacosPropertySourceBuilder.build(dataId, group, fileExtension,
isRefreshable);
}
/**
* Add the nacos configuration to the first place and maybe ignore the empty
* configuration.
*/
private void addFirstPropertySource(final CompositePropertySource composite,
NacosPropertySource nacosPropertySource, boolean ignoreEmpty) {
if (null == nacosPropertySource || null == composite) {
return;
}
if (ignoreEmpty && nacosPropertySource.getSource().isEmpty()) {
return;
}
composite.addFirstPropertySource(nacosPropertySource);
}
private static void checkDataIdFileExtension(String[] dataIdArray) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < dataIdArray.length; i++) {
boolean isLegal = false;
for (String fileExtension : SUPPORT_FILE_EXTENSION) {
if (dataIdArray[i].indexOf(fileExtension) > 0) {
isLegal = true;
break;
}
}
// add tips
if (!isLegal) {
stringBuilder.append(dataIdArray[i] + ",");
}
}
if (stringBuilder.length() > 0) {
String result = stringBuilder.substring(0, stringBuilder.length() - 1);
throw new IllegalStateException(String.format(
"[%s] must contains file extension with properties|yaml|yml",
result));
if (dataIdArray == null || dataIdArray.length < 1) {
throw new IllegalStateException("The dataId cannot be empty");
}
// Just decide that the current dataId must have a suffix
NacosDataParserHandler.getInstance().checkDataId(dataIdArray);
}
private boolean checkDataIdIsRefreshbable(String refreshDataIds,
String sharedDataId) {
if (refreshDataIds == null || "".equals(refreshDataIds)) {
private boolean checkDataIdIsRefreshable(String refreshDataIds, String sharedDataId) {
if (StringUtils.isEmpty(refreshDataIds)) {
return false;
}
String[] refreshDataIdArry = refreshDataIds.split(SHARED_CONFIG_SEPARATOR_CHAR);
for (String refreshDataId : refreshDataIdArry) {
String[] refreshDataIdArray = refreshDataIds.split(SHARED_CONFIG_SEPARATOR_CHAR);
for (String refreshDataId : refreshDataIdArray) {
if (refreshDataId.equals(sharedDataId)) {
return true;
}

View File

@@ -31,7 +31,10 @@ public class NacosConnectionFailureAnalyzer
@Override
protected FailureAnalysis analyze(Throwable rootFailure,
NacosConnectionFailureException cause) {
return new FailureAnalysis("Application failed to connect to Nacos server",
"check your nacos server config", cause);
return new FailureAnalysis(
"Application failed to connect to Nacos server: \""
+ cause.getServerAddr() + "\"",
"Please check your Nacos server config", cause);
}
}

View File

@@ -24,29 +24,21 @@ package com.alibaba.cloud.nacos.diagnostics.analyzer;
*/
public class NacosConnectionFailureException extends RuntimeException {
private final String domain;
private final String serverAddr;
private final String port;
public NacosConnectionFailureException(String domain, String port, String message) {
public NacosConnectionFailureException(String serverAddr, String message) {
super(message);
this.domain = domain;
this.port = port;
this.serverAddr = serverAddr;
}
public NacosConnectionFailureException(String domain, String port, String message,
public NacosConnectionFailureException(String serverAddr, String message,
Throwable cause) {
super(message, cause);
this.domain = domain;
this.port = port;
this.serverAddr = serverAddr;
}
String getDomain() {
return domain;
}
String getPort() {
return port;
public String getServerAddr() {
return serverAddr;
}
}

View File

@@ -23,16 +23,17 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.NacosPropertySourceRepository;
import com.alibaba.cloud.nacos.client.NacosPropertySource;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
/**
* Endpoint for Nacos, contains config data and refresh history
* Endpoint for Nacos, contains config data and refresh history.
*
* @author xiaojing
*/
@Endpoint(id = "nacos-config")
@@ -42,12 +43,8 @@ public class NacosConfigEndpoint {
private final NacosRefreshHistory refreshHistory;
private ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
private ThreadLocal<DateFormat> dateFormat = ThreadLocal
.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
public NacosConfigEndpoint(NacosConfigProperties properties,
NacosRefreshHistory refreshHistory) {

View File

@@ -16,6 +16,10 @@
package com.alibaba.cloud.nacos.endpoint;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
@@ -25,9 +29,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
/**
* @author xiaojing
*/
@@ -39,6 +40,9 @@ public class NacosConfigEndpointAutoConfiguration {
@Autowired
private NacosConfigProperties nacosConfigProperties;
@Autowired
private NacosConfigManager nacosConfigManager;
@Autowired
private NacosRefreshHistory nacosRefreshHistory;
@@ -51,7 +55,6 @@ public class NacosConfigEndpointAutoConfiguration {
@Bean
public NacosConfigHealthIndicator nacosConfigHealthIndicator() {
return new NacosConfigHealthIndicator(nacosConfigProperties,
nacosConfigProperties.configServiceInstance());
return new NacosConfigHealthIndicator(nacosConfigManager.getConfigService());
}
}

View File

@@ -16,58 +16,27 @@
package com.alibaba.cloud.nacos.endpoint;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.util.StringUtils;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.NacosPropertySourceRepository;
import com.alibaba.cloud.nacos.client.NacosPropertySource;
import com.alibaba.nacos.api.config.ConfigService;
/**
* @author xiaojing
*/
public class NacosConfigHealthIndicator extends AbstractHealthIndicator {
private final NacosConfigProperties nacosConfigProperties;
private final List<String> dataIds;
private final ConfigService configService;
public NacosConfigHealthIndicator(NacosConfigProperties nacosConfigProperties,
ConfigService configService) {
this.nacosConfigProperties = nacosConfigProperties;
public NacosConfigHealthIndicator(ConfigService configService) {
this.configService = configService;
this.dataIds = new ArrayList<>();
for (NacosPropertySource nacosPropertySource : NacosPropertySourceRepository
.getAll()) {
this.dataIds.add(nacosPropertySource.getDataId());
}
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
for (String dataId : dataIds) {
try {
String config = configService.getConfig(dataId,
nacosConfigProperties.getGroup(),
nacosConfigProperties.getTimeout());
if (StringUtils.isEmpty(config)) {
builder.down().withDetail(String.format("dataId: '%s', group: '%s'",
dataId, nacosConfigProperties.getGroup()), "config is empty");
}
}
catch (Exception e) {
builder.down().withDetail(String.format("dataId: '%s', group: '%s'",
dataId, nacosConfigProperties.getGroup()), e.getMessage());
}
}
builder.up().withDetail("dataIds", dataIds);
builder.up();
String status = configService.getServerStatus();
builder.status(status);
}
}

View File

@@ -0,0 +1,157 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos.parser;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import com.alibaba.nacos.client.utils.StringUtils;
/**
* @author zkz
*/
public abstract class AbstractNacosDataParser {
protected static final String DOT = ".";
protected static final String VALUE = "value";
private String extension;
private AbstractNacosDataParser nextParser;
protected AbstractNacosDataParser(String extension) {
if (StringUtils.isEmpty(extension)) {
throw new IllegalArgumentException("extension cannot be empty");
}
this.extension = extension.toLowerCase();
}
/**
* Verify dataId extensions.
* @param extension file extension. json or xml or yml or yaml or properties
* @return valid or not
*/
public final boolean checkFileExtension(String extension) {
if (this.isLegal(extension.toLowerCase())) {
return true;
}
if (this.nextParser == null) {
return false;
}
return this.nextParser.checkFileExtension(extension);
}
/**
* Parsing nacos configuration content.
* @param data config data from Nacos
* @param extension file extension. json or xml or yml or yaml or properties
* @return result of Properties
* @throws IOException thrown if there is a problem parsing config.
*/
public final Properties parseNacosData(String data, String extension)
throws IOException {
if (extension == null || extension.length() < 1) {
throw new IllegalStateException("The file extension cannot be empty");
}
if (this.isLegal(extension.toLowerCase())) {
return this.doParse(data);
}
if (this.nextParser == null) {
throw new IllegalStateException(getTips(extension));
}
return this.nextParser.parseNacosData(data, extension);
}
/**
* Core logic for parsing.
* @param data config from Nacos
* @return result of Properties
* @throws IOException thrown if there is a problem parsing config.
*/
protected abstract Properties doParse(String data) throws IOException;
protected AbstractNacosDataParser setNextParser(AbstractNacosDataParser nextParser) {
this.nextParser = nextParser;
return this;
}
public AbstractNacosDataParser addNextParser(AbstractNacosDataParser nextParser) {
if (this.nextParser == null) {
this.nextParser = nextParser;
}
else {
this.nextParser.addNextParser(nextParser);
}
return this;
}
protected boolean isLegal(String extension) {
return this.extension.equalsIgnoreCase(extension)
|| this.extension.contains(extension);
}
/**
* Generate key-value pairs from the map.
*/
protected Properties generateProperties(Map<String, String> map) {
if (null == map || map.isEmpty()) {
return null;
}
Properties properties = new Properties();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
if (StringUtils.isBlank(key)) {
continue;
}
key = key.startsWith(DOT) ? key.replaceFirst("\\.", "") : key;
properties.put(key, entry.getValue());
}
return properties;
}
/**
* Reload the key ending in `value` if need.
*/
protected Map<String, String> reloadMap(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, String> result = new HashMap<>(map);
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
if (key.contains(DOT)) {
int idx = key.lastIndexOf(DOT);
String suffix = key.substring(idx + 1);
if (VALUE.equalsIgnoreCase(suffix)) {
result.put(key.substring(0, idx), entry.getValue());
}
}
}
return result;
}
public static String getTips(String fileName) {
return String.format(
"[%s] must contains file extension with properties|yaml|yml|xml|json",
fileName);
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos.parser;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import com.alibaba.nacos.client.utils.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author zkz
*/
public class NacosDataJsonParser extends AbstractNacosDataParser {
protected NacosDataJsonParser() {
super("json");
}
@Override
protected Properties doParse(String data) throws IOException {
if (StringUtils.isEmpty(data)) {
return null;
}
Map<String, String> map = parseJSON2Map(data);
return this.generateProperties(this.reloadMap(map));
}
/**
* JSON to Map.
* @param json json data
* @return the map convert by json string
* @throws IOException thrown if there is a problem parsing config.
*/
public static Map<String, String> parseJSON2Map(String json) throws IOException {
Map<String, String> map = new HashMap<>(32);
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(json);
if (null == jsonNode) {
return map;
}
parseJsonNode(map, jsonNode, "");
return map;
}
private static void parseJsonNode(Map<String, String> jsonMap, JsonNode jsonNode,
String parentKey) {
Iterator<String> fieldNames = jsonNode.fieldNames();
while (fieldNames.hasNext()) {
String name = fieldNames.next();
String fullKey = StringUtils.isEmpty(parentKey) ? name
: parentKey + DOT + name;
JsonNode resultValue = jsonNode.findValue(name);
if (null == resultValue) {
continue;
}
if (resultValue.isArray()) {
Iterator<JsonNode> iterator = resultValue.elements();
while (iterator != null && iterator.hasNext()) {
JsonNode next = iterator.next();
if (null == next) {
continue;
}
parseJsonNode(jsonMap, next, fullKey);
}
continue;
}
if (resultValue.isObject()) {
parseJsonNode(jsonMap, resultValue, fullKey);
continue;
}
jsonMap.put(fullKey, resultValue.asText());
}
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos.parser;
import java.io.IOException;
import java.util.Properties;
/**
* @author zkz
*/
public final class NacosDataParserHandler {
private AbstractNacosDataParser parser;
private NacosDataParserHandler() {
parser = this.createParser();
}
/**
* Parsing nacos configuration content.
* @param data config from Nacos
* @param extension file extension. json or xml or yml or yaml or properties
* @return result of properties
* @throws IOException thrown if there is a problem parsing config.
*/
public Properties parseNacosData(String data, String extension) throws IOException {
if (null == parser) {
parser = this.createParser();
}
return parser.parseNacosData(data, extension);
}
/**
* check the validity of file extensions in dataid.
* @param dataIdAry array of dataId
* @return dataId handle success or not
*/
public boolean checkDataId(String... dataIdAry) {
StringBuilder stringBuilder = new StringBuilder();
for (String dataId : dataIdAry) {
int idx = dataId.lastIndexOf(AbstractNacosDataParser.DOT);
if (idx > 0 && idx < dataId.length() - 1) {
String extension = dataId.substring(idx + 1);
if (parser.checkFileExtension(extension)) {
break;
}
}
// add tips
stringBuilder.append(dataId).append(",");
}
if (stringBuilder.length() > 0) {
String result = stringBuilder.substring(0, stringBuilder.length() - 1);
throw new IllegalStateException(AbstractNacosDataParser.getTips(result));
}
return true;
}
private AbstractNacosDataParser createParser() {
return new NacosDataPropertiesParser().addNextParser(new NacosDataYamlParser())
.addNextParser(new NacosDataXmlParser())
.addNextParser(new NacosDataJsonParser());
}
public static NacosDataParserHandler getInstance() {
return ParserHandler.HANDLER;
}
private static class ParserHandler {
private static final NacosDataParserHandler HANDLER = new NacosDataParserHandler();
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos.parser;
import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;
/**
* @author zkz
*/
public class NacosDataPropertiesParser extends AbstractNacosDataParser {
public NacosDataPropertiesParser() {
super("properties");
}
@Override
protected Properties doParse(String data) throws IOException {
Properties properties = new Properties();
properties.load(new StringReader(data));
return properties;
}
}

View File

@@ -0,0 +1,130 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos.parser;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import com.alibaba.nacos.client.utils.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* With relatively few usage scenarios, only simple parsing is performed to reduce jar
* dependencies.
*
* @author zkz
*/
public class NacosDataXmlParser extends AbstractNacosDataParser {
public NacosDataXmlParser() {
super("xml");
}
@Override
protected Properties doParse(String data) throws IOException {
if (StringUtils.isEmpty(data)) {
return null;
}
Map<String, String> map = parseXml2Map(data);
return this.generateProperties(this.reloadMap(map));
}
private Map<String, String> parseXml2Map(String xml) throws IOException {
xml = xml.replaceAll("\\r", "").replaceAll("\\n", "").replaceAll("\\t", "");
Map<String, String> map = new HashMap<>(32);
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document document = documentBuilder
.parse(new InputSource(new StringReader(xml)));
if (null == document) {
return null;
}
parseNodeList(document.getChildNodes(), map, "");
}
catch (Exception e) {
throw new IOException("The xml content parse error.", e.getCause());
}
return map;
}
private void parseNodeList(NodeList nodeList, Map<String, String> map,
String parentKey) {
if (nodeList == null || nodeList.getLength() < 1) {
return;
}
parentKey = parentKey == null ? "" : parentKey;
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
String value = node.getNodeValue();
value = value == null ? "" : value.trim();
String name = node.getNodeName();
name = name == null ? "" : name.trim();
if (StringUtils.isEmpty(name)) {
continue;
}
String key = StringUtils.isEmpty(parentKey) ? name : parentKey + DOT + name;
NamedNodeMap nodeMap = node.getAttributes();
parseNodeAttr(nodeMap, map, key);
if (node.getNodeType() == Node.ELEMENT_NODE && node.hasChildNodes()) {
parseNodeList(node.getChildNodes(), map, key);
continue;
}
if (value.length() < 1) {
continue;
}
map.put(parentKey, value);
}
}
private void parseNodeAttr(NamedNodeMap nodeMap, Map<String, String> map,
String parentKey) {
if (null == nodeMap || nodeMap.getLength() < 1) {
return;
}
for (int i = 0; i < nodeMap.getLength(); i++) {
Node node = nodeMap.item(i);
if (null == node) {
continue;
}
if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
if (StringUtils.isEmpty(node.getNodeName())) {
continue;
}
if (StringUtils.isEmpty(node.getNodeValue())) {
continue;
}
map.put(String.join(DOT, parentKey, node.getNodeName()),
node.getNodeValue());
}
}
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos.parser;
import java.util.Properties;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ByteArrayResource;
/**
* @author zkz
*/
public class NacosDataYamlParser extends AbstractNacosDataParser {
public NacosDataYamlParser() {
super(",yml,yaml,");
}
@Override
protected Properties doParse(String data) {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(new ByteArrayResource(data.getBytes()));
return yamlFactory.getObject();
}
}

View File

@@ -26,8 +26,15 @@ import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import com.alibaba.cloud.nacos.NacosPropertySourceRepository;
import com.alibaba.cloud.nacos.client.NacosPropertySource;
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;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.context.ApplicationContext;
@@ -35,12 +42,6 @@ import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.util.StringUtils;
import com.alibaba.cloud.nacos.NacosPropertySourceRepository;
import com.alibaba.cloud.nacos.client.NacosPropertySource;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
/**
* On application start up, NacosContextRefresher add nacos listeners to all application
* level dataIds, when there is a change in the data, listeners will refresh

View File

@@ -1,5 +1,16 @@
{
"properties": [
{
"name": "spring.cloud.nacos.server-addr",
"type": "java.lang.String",
"description": "nacos server address."
},
{
"name": "spring.cloud.nacos.config.server-addr",
"type": "java.lang.String",
"defaultValue": "${spring.cloud.nacos.server-addr}",
"description": "nacos config server address."
},
{
"name": "spring.cloud.nacos.config.encode",
"type": "java.lang.String",

View File

@@ -0,0 +1,42 @@
package com.alibaba.cloud.nacos;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author <a href="mailto:lyuzb@lyuzb.com">lyuzb</a>
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosConfigPropertiesServerAddressBothLevelTests.TestConfig.class, properties = {
"spring.cloud.nacos.config.server-addr=321,321,321,321:8848",
"spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT)
public class NacosConfigPropertiesServerAddressBothLevelTests {
@Autowired
private NacosConfigProperties properties;
@Test
public void testGetServerAddr() {
assertEquals("NacosConfigProperties server address was wrong",
"321,321,321,321:8848", properties.getServerAddr());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -0,0 +1,41 @@
package com.alibaba.cloud.nacos;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author <a href="mailto:lyuzb@lyuzb.com">lyuzb</a>
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosConfigPropertiesServerAddressTopLevelTests.TestConfig.class, properties = {
"spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT)
public class NacosConfigPropertiesServerAddressTopLevelTests {
@Autowired
private NacosConfigProperties properties;
@Test
public void testGetServerAddr() {
assertEquals("NacosConfigProperties server address was wrong",
"123.123.123.123:8848", properties.getServerAddr());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -16,12 +16,13 @@
package com.alibaba.cloud.nacos;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import com.alibaba.nacos.client.config.NacosConfigService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -31,6 +32,7 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -39,9 +41,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import com.alibaba.nacos.client.config.NacosConfigService;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
/**
* @author xiaojing

View File

@@ -16,14 +16,16 @@
package com.alibaba.cloud.nacos;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import com.alibaba.nacos.client.config.NacosConfigService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -33,6 +35,7 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -41,11 +44,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import com.alibaba.nacos.client.config.NacosConfigService;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
/**
* @author xiaojing

View File

@@ -0,0 +1,252 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import com.alibaba.nacos.client.config.NacosConfigService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.api.support.MethodProxy;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
/**
* @author zkz
*/
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ NacosConfigService.class })
@SpringBootTest(classes = NacosConfigurationXmlJsonTest.TestConfig.class, properties = {
"spring.application.name=xmlApp", "spring.profiles.active=dev",
"spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.config.namespace=test-namespace",
"spring.cloud.nacos.config.encode=utf-8",
"spring.cloud.nacos.config.timeout=1000",
"spring.cloud.nacos.config.group=test-group",
"spring.cloud.nacos.config.name=test-name",
"spring.cloud.nacos.config.cluster-name=test-cluster",
"spring.cloud.nacos.config.file-extension=xml",
"spring.cloud.nacos.config.contextPath=test-contextpath",
"spring.cloud.nacos.config.ext-config[0].data-id=ext-json-test.json",
"spring.cloud.nacos.config.ext-config[1].data-id=ext-common02.properties",
"spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
"spring.cloud.nacos.config.shared-dataids=shared-data1.properties",
"spring.cloud.nacos.config.accessKey=test-accessKey",
"spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
public class NacosConfigurationXmlJsonTest {
static {
try {
Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
String.class, String.class, long.class);
MethodProxy.proxy(method, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if ("xmlApp.xml".equals(args[0]) && "test-group".equals(args[1])) {
return "<top>\n" + " <first>one</first>\n"
+ " <sencond value=\"two\">\n"
+ " <third>three</third>\n" + " </sencond>\n"
+ "</top>";
}
if ("test-name.xml".equals(args[0]) && "test-group".equals(args[1])) {
return "<Server port=\"8005\" shutdown=\"SHUTDOWN\"> \n"
+ " <Service name=\"Catalina\"> \n"
+ " <Connector value=\"第二个连接器\"> \n"
+ " <open>开启服务</open> \n"
+ " <init>初始化一下</init> \n"
+ " <process>\n" + " <top>\n"
+ " <first>one</first>\n"
+ " <sencond value=\"two\">\n"
+ " <third>three</third>\n"
+ " </sencond>\n"
+ " </top>\n" + " </process> \n"
+ " <destory>销毁一下</destory> \n"
+ " <close>关闭服务</close> \n"
+ " </Connector> \n" + " </Service> \n"
+ "</Server> ";
}
if ("test-name-dev.xml".equals(args[0])
&& "test-group".equals(args[1])) {
return "<application android:label=\"@string/app_name\" android:icon=\"@drawable/osg\">\n"
+ " <activity android:name=\".osgViewer\"\n"
+ " android:label=\"@string/app_name\" android:screenOrientation=\"landscape\">\n"
+ " <intent-filter>\n"
+ " <action android:name=\"android.intent.action.MAIN\" />\n"
+ " <category android:name=\"android.intent.category.LAUNCHER\" />\n"
+ " </intent-filter>\n" + " </activity>\n"
+ "</application>";
}
if ("ext-json-test.json".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "{\n" + " \"people\":{\n"
+ " \"firstName\":\"Brett\",\n"
+ " \"lastName\":\"McLaughlin\"\n" + " }\n"
+ "}";
}
if ("ext-config-common02.properties".equals(args[0])
&& "GLOBAL_GROUP".equals(args[1])) {
return "global-ext-config=global-config-value-2";
}
if ("shared-data1.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "shared-name=shared-value-1";
}
return "";
}
});
}
catch (Exception ignore) {
ignore.printStackTrace();
}
}
@Autowired
private NacosPropertySourceLocator locator;
@Autowired
private NacosConfigProperties properties;
@Autowired
private NacosRefreshHistory refreshHistory;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosPropertySourceLocator was not created", locator);
assertNotNull("NacosConfigProperties was not created", properties);
checkoutNacosConfigServerAddr();
checkoutNacosConfigNamespace();
checkoutNacosConfigClusterName();
checkoutNacosConfigAccessKey();
checkoutNacosConfigSecrectKey();
checkoutNacosConfigName();
checkoutNacosConfigGroup();
checkoutNacosConfigContextPath();
checkoutNacosConfigFileExtension();
checkoutNacosConfigTimeout();
checkoutNacosConfigEncode();
checkoutEndpoint();
}
private void checkoutNacosConfigServerAddr() {
assertEquals("NacosConfigProperties server address is wrong", "127.0.0.1:8848",
properties.getServerAddr());
}
private void checkoutNacosConfigNamespace() {
assertEquals("NacosConfigProperties namespace is wrong", "test-namespace",
properties.getNamespace());
}
private void checkoutNacosConfigClusterName() {
assertEquals("NacosConfigProperties' cluster is wrong", "test-cluster",
properties.getClusterName());
}
private void checkoutNacosConfigAccessKey() {
assertEquals("NacosConfigProperties' is access key is wrong", "test-accessKey",
properties.getAccessKey());
}
private void checkoutNacosConfigSecrectKey() {
assertEquals("NacosConfigProperties' is secret key is wrong", "test-secretKey",
properties.getSecretKey());
}
private void checkoutNacosConfigContextPath() {
assertEquals("NacosConfigProperties' context path is wrong", "test-contextpath",
properties.getContextPath());
}
private void checkoutNacosConfigName() {
assertEquals("NacosConfigProperties' name is wrong", "test-name",
properties.getName());
}
private void checkoutNacosConfigGroup() {
assertEquals("NacosConfigProperties' group is wrong", "test-group",
properties.getGroup());
}
private void checkoutNacosConfigFileExtension() {
assertEquals("NacosConfigProperties' file extension is wrong", "xml",
properties.getFileExtension());
}
private void checkoutNacosConfigTimeout() {
assertEquals("NacosConfigProperties' timeout is wrong", 1000,
properties.getTimeout());
}
private void checkoutNacosConfigEncode() {
assertEquals("NacosConfigProperties' encode is wrong", "utf-8",
properties.getEncode());
}
private void checkoutEndpoint() throws Exception {
NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties,
refreshHistory);
Map<String, Object> map = nacosConfigEndpoint.invoke();
assertEquals(map.get("NacosConfigProperties"), properties);
assertEquals(map.get("RefreshHistory"), refreshHistory.getRecords());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -16,11 +16,12 @@
package com.alibaba.cloud.nacos;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import com.alibaba.nacos.client.config.NacosConfigService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -30,6 +31,7 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -38,8 +40,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import com.alibaba.nacos.client.config.NacosConfigService;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
/**
* @author xiaojing

View File

@@ -16,16 +16,16 @@
package com.alibaba.cloud.nacos.endpoint;
import static org.junit.Assert.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import com.alibaba.cloud.nacos.NacosConfigAutoConfiguration;
import com.alibaba.cloud.nacos.NacosConfigBootstrapConfiguration;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import com.alibaba.nacos.client.config.NacosConfigService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
@@ -34,6 +34,7 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health.Builder;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -42,11 +43,8 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.alibaba.cloud.nacos.NacosConfigAutoConfiguration;
import com.alibaba.cloud.nacos.NacosConfigBootstrapConfiguration;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import com.alibaba.nacos.client.config.NacosConfigService;
import static org.junit.Assert.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
/**
* @author xiaojing
@@ -68,17 +66,13 @@ public class NacosConfigEndpointTests {
Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
String.class, String.class, long.class);
MethodProxy.proxy(method, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
MethodProxy.proxy(method, (proxy, method1, args) -> {
if ("test-name.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "user.name=hello\nuser.age=12";
}
return "";
if ("test-name.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "user.name=hello\nuser.age=12";
}
return "";
});
}
@@ -91,6 +85,9 @@ public class NacosConfigEndpointTests {
@Autowired
private NacosConfigProperties properties;
@Autowired
private NacosConfigManager nacosConfigManager;
@Autowired
private NacosRefreshHistory refreshHistory;
@@ -98,7 +95,7 @@ public class NacosConfigEndpointTests {
public void contextLoads() throws Exception {
checkoutEndpoint();
checkoutAcmHealthIndicator();
// checkoutAcmHealthIndicator();
}
@@ -107,18 +104,16 @@ public class NacosConfigEndpointTests {
Builder builder = new Builder();
NacosConfigHealthIndicator healthIndicator = new NacosConfigHealthIndicator(
properties, properties.configServiceInstance());
nacosConfigManager.getConfigService());
healthIndicator.doHealthCheck(builder);
Builder builder1 = new Builder();
List<String> dataIds = new ArrayList<>();
dataIds.add("test-name.properties");
builder1.up().withDetail("dataIds", dataIds);
builder1.up();
Assert.assertTrue(builder.build().equals(builder1.build()));
assertEquals(builder1.build(), builder.build());
}
catch (Exception ignoreE) {
catch (Exception ignore) {
}