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

sync & commit in greenwich

This commit is contained in:
fangjian0423
2019-10-29 14:57:54 +08:00
parent 12b9091583
commit 980bc3fd7a
94 changed files with 2633 additions and 780 deletions

View File

@@ -14,29 +14,41 @@
* 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 org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
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 implements ApplicationContextAware {
public class NacosConfigManager {
private ConfigService configService;
private static ConfigService service = null;
@Autowired
private NacosConfigProperties properties;
public ConfigService getConfigService() {
return configService;
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;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
NacosConfigProperties properties = applicationContext
.getBean(NacosConfigProperties.class);
configService = properties.configServiceInstance();
}
}

View File

@@ -16,38 +16,37 @@
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 static com.alibaba.nacos.api.PropertyKeyConst.MAX_RETRY;
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.ENABLE_REMOTE_SYNC_CONFIG;
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.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
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
@@ -57,6 +56,9 @@ import com.alibaba.nacos.api.config.ConfigService;
@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
@@ -76,7 +78,7 @@ public class NacosConfigProperties {
.resolvePlaceholders("${spring.cloud.nacos.config.server-addr:}");
if (StringUtils.isEmpty(serverAddr)) {
serverAddr = environment
.resolvePlaceholders("${spring.cloud.nacos.server-addr}");
.resolvePlaceholders("${spring.cloud.nacos.server-addr:}");
}
this.setServerAddr(serverAddr);
}
@@ -101,6 +103,7 @@ public class NacosConfigProperties {
* nacos config dataId prefix.
*/
private String prefix;
/**
* the suffix of nacos config dataId, also the file extension of config content.
*/
@@ -351,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 .
*/
@@ -388,60 +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 + '}';
}
@Deprecated
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, ""));
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);
}
try {
configService = NacosFactory.createConfigService(properties);
return configService;
}
catch (Exception e) {
log.error("create config service error!properties={},e=,", this, e);
return null;
}
}
}

View File

@@ -44,9 +44,13 @@ 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 NacosPropertySourceBuilder nacosPropertySourceBuilder;
@@ -156,8 +160,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,
@@ -168,22 +177,41 @@ 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) {

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

@@ -32,7 +32,8 @@ import com.alibaba.cloud.nacos.client.NacosPropertySource;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
/**
* Endpoint for Nacos, contains config data and refresh history
* Endpoint for Nacos, contains config data and refresh history.
*
* @author xiaojing
*/
@Endpoint(id = "nacos-config")

View File

@@ -29,9 +29,11 @@ import com.alibaba.nacos.client.utils.StringUtils;
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) {
@@ -41,7 +43,11 @@ public abstract class AbstractNacosDataParser {
this.extension = extension.toLowerCase();
}
/** Verify file extensions */
/**
* 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;
@@ -53,7 +59,13 @@ public abstract class AbstractNacosDataParser {
}
/** Parsing nacos configuration content */
/**
* 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) {
@@ -68,7 +80,12 @@ public abstract class AbstractNacosDataParser {
return this.nextParser.parseNacosData(data, extension);
}
/** Core logic for parsing */
/**
* 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) {
@@ -76,7 +93,6 @@ public abstract class AbstractNacosDataParser {
return this;
}
/** add the next parser */
public AbstractNacosDataParser addNextParser(AbstractNacosDataParser nextParser) {
if (this.nextParser == null) {
this.nextParser = nextParser;
@@ -93,7 +109,7 @@ public abstract class AbstractNacosDataParser {
}
/**
* Generate key-value pairs from the map
* Generate key-value pairs from the map.
*/
protected Properties generateProperties(Map<String, String> map) {
if (null == map || map.isEmpty()) {
@@ -112,7 +128,7 @@ public abstract class AbstractNacosDataParser {
}
/**
* Reload the key ending in `value`,if you need
* Reload the key ending in `value` if need.
*/
protected Map<String, String> reloadMap(Map<String, String> map) {
if (map == null || map.isEmpty()) {

View File

@@ -44,7 +44,10 @@ public class NacosDataJsonParser extends AbstractNacosDataParser {
}
/**
* JSON to 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);

View File

@@ -22,9 +22,7 @@ import java.util.Properties;
/**
* @author zkz
*/
public class NacosDataParserHandler {
private static final NacosDataParserHandler HANDLER = new NacosDataParserHandler();
public final class NacosDataParserHandler {
private AbstractNacosDataParser parser;
@@ -32,7 +30,13 @@ public class NacosDataParserHandler {
parser = this.createParser();
}
/** Parsing nacos configuration content */
/**
* 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();
@@ -40,7 +44,11 @@ public class NacosDataParserHandler {
return parser.parseNacosData(data, extension);
}
/** check the validity of file extensions in dataid */
/**
* 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) {
@@ -68,7 +76,13 @@ public class NacosDataParserHandler {
}
public static NacosDataParserHandler getInstance() {
return HANDLER;
return ParserHandler.HANDLER;
}
private static class ParserHandler {
private static final NacosDataParserHandler HANDLER = new NacosDataParserHandler();
}
}

View File

@@ -25,17 +25,17 @@ 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;
import com.alibaba.nacos.client.utils.StringUtils;
/**
* With relatively few usage scenarios, only simple parsing is performed to reduce jar
* dependencies
* dependencies.
*
* @author zkz
*/
@@ -55,9 +55,7 @@ public class NacosDataXmlParser extends AbstractNacosDataParser {
}
private Map<String, String> parseXml2Map(String xml) throws IOException {
xml = xml.replaceAll("\\r", "")
.replaceAll("\\n", "")
.replaceAll("\\t", "");
xml = xml.replaceAll("\\r", "").replaceAll("\\n", "").replaceAll("\\t", "");
Map<String, String> map = new HashMap<>(32);
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()