From 4fe795166ba6ec62c7763c54c263615219033508 Mon Sep 17 00:00:00 2001 From: flystar32 Date: Tue, 19 Feb 2019 16:31:17 +0800 Subject: [PATCH 01/18] support spring.cloud.nacos.config.enabled --- .../NacosConfigBootstrapConfiguration.java | 13 +++-- .../alibaba/nacos/NacosConfigProperties.java | 53 ++++++++++++------- .../client/NacosPropertySourceBuilder.java | 21 ++++---- .../client/NacosPropertySourceLocator.java | 29 +++++----- .../nacos/refresh/NacosContextRefresher.java | 21 +++++--- 5 files changed, 80 insertions(+), 57 deletions(-) diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigBootstrapConfiguration.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigBootstrapConfiguration.java index 076d884f..94933a4d 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigBootstrapConfiguration.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigBootstrapConfiguration.java @@ -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); + } + } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigProperties.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigProperties.java index abeec2d7..d19e8acf 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigProperties.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigProperties.java @@ -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; } } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceBuilder.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceBuilder.java index d7e0766f..d5369007 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceBuilder.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceBuilder.java @@ -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 propertiesToMap(Properties properties) { Map result = new HashMap<>(16); - Enumeration tmpKeys = (Enumeration) properties.propertyNames(); - while (tmpKeys.hasMoreElements()) { - String key = tmpKeys.nextElement(); + Enumeration keys = (Enumeration) 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; } + } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceLocator.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceLocator.java index 647856b1..5ce9afea 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceLocator.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceLocator.java @@ -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 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) { diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/refresh/NacosContextRefresher.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/refresh/NacosContextRefresher.java index 28a1d47e..1fc7e8b0 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/refresh/NacosContextRefresher.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/refresh/NacosContextRefresher.java @@ -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, 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(); + } } From 0581a923fe00055f4f63f8fe4848288f9c1b328c Mon Sep 17 00:00:00 2001 From: pbting <314226532@qq.com> Date: Tue, 19 Feb 2019 16:57:05 +0800 Subject: [PATCH 02/18] Update pom.xml remove spring-cloud-alicloud-context maven dependency --- .../nacos-discovery-provider-example/pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/pom.xml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/pom.xml index 0f28a7ac..9397b274 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/pom.xml +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/pom.xml @@ -29,11 +29,6 @@ org.springframework.boot spring-boot-starter-actuator - - - org.springframework.cloud - spring-cloud-alicloud-context - From edf04a5c422fdc90d38ecdd12214e6120efb6bd6 Mon Sep 17 00:00:00 2001 From: pbting <314226532@qq.com> Date: Tue, 19 Feb 2019 16:57:38 +0800 Subject: [PATCH 03/18] Update pom.xml remove spring-cloud-alicloud-context maven dependency --- .../nacos-discovery-consumer-example/pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/pom.xml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/pom.xml index fd6c6875..f8e1217a 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/pom.xml +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/pom.xml @@ -44,11 +44,6 @@ org.springframework.cloud spring-cloud-starter-alibaba-sentinel - - - org.springframework.cloud - spring-cloud-alicloud-context - From eeedf90d867b7f51f7ce04a5de538e5087a5b13f Mon Sep 17 00:00:00 2001 From: fangjian0423 Date: Tue, 19 Feb 2019 20:52:28 +0800 Subject: [PATCH 04/18] sentinel 1.x add jsr and update version of validation-api --- spring-cloud-alibaba-sentinel-datasource/pom.xml | 1 - .../datasource/config/AbstractDataSourceProperties.java | 3 +-- .../datasource/config/ApolloDataSourceProperties.java | 6 +++--- .../config/DataSourcePropertiesConfiguration.java | 6 ++++++ .../datasource/config/FileDataSourceProperties.java | 4 ++-- .../datasource/config/NacosDataSourceProperties.java | 6 +++--- .../datasource/config/ZookeeperDataSourceProperties.java | 4 ++-- .../cloud/alibaba/sentinel/SentinelProperties.java | 3 +++ 8 files changed, 20 insertions(+), 13 deletions(-) diff --git a/spring-cloud-alibaba-sentinel-datasource/pom.xml b/spring-cloud-alibaba-sentinel-datasource/pom.xml index b8d44fb7..141236e1 100644 --- a/spring-cloud-alibaba-sentinel-datasource/pom.xml +++ b/spring-cloud-alibaba-sentinel-datasource/pom.xml @@ -86,7 +86,6 @@ javax.validation validation-api - 2.0.1.Final true diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/AbstractDataSourceProperties.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/AbstractDataSourceProperties.java index f64a60a9..7b6f5a49 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/AbstractDataSourceProperties.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/AbstractDataSourceProperties.java @@ -16,7 +16,6 @@ package org.springframework.cloud.alibaba.sentinel.datasource.config; -import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import org.springframework.cloud.alibaba.sentinel.datasource.RuleType; @@ -37,7 +36,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; */ public class AbstractDataSourceProperties { - @NotEmpty + @NotNull private String dataType = "json"; @NotNull private RuleType ruleType; diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/ApolloDataSourceProperties.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/ApolloDataSourceProperties.java index cbc71110..acfb222e 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/ApolloDataSourceProperties.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/ApolloDataSourceProperties.java @@ -16,7 +16,7 @@ package org.springframework.cloud.alibaba.sentinel.datasource.config; -import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.ApolloDataSourceFactoryBean; @@ -28,9 +28,9 @@ import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.ApolloD */ public class ApolloDataSourceProperties extends AbstractDataSourceProperties { - @NotEmpty + @NotNull private String namespaceName; - @NotEmpty + @NotNull private String flowRulesKey; private String defaultFlowRuleValue; diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/DataSourcePropertiesConfiguration.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/DataSourcePropertiesConfiguration.java index ccd1b9b1..1f270cca 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/DataSourcePropertiesConfiguration.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/DataSourcePropertiesConfiguration.java @@ -4,6 +4,8 @@ import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; +import javax.validation.Valid; + import org.springframework.util.ObjectUtils; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -19,12 +21,16 @@ import com.fasterxml.jackson.annotation.JsonIgnore; */ public class DataSourcePropertiesConfiguration { + @Valid private FileDataSourceProperties file; + @Valid private NacosDataSourceProperties nacos; + @Valid private ZookeeperDataSourceProperties zk; + @Valid private ApolloDataSourceProperties apollo; public DataSourcePropertiesConfiguration() { diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/FileDataSourceProperties.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/FileDataSourceProperties.java index e44429cb..e1084260 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/FileDataSourceProperties.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/FileDataSourceProperties.java @@ -18,7 +18,7 @@ package org.springframework.cloud.alibaba.sentinel.datasource.config; import java.io.IOException; -import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.FileRefreshableDataSourceFactoryBean; import org.springframework.util.ResourceUtils; @@ -32,7 +32,7 @@ import org.springframework.util.StringUtils; */ public class FileDataSourceProperties extends AbstractDataSourceProperties { - @NotEmpty + @NotNull private String file; private String charset = "utf-8"; private long recommendRefreshMs = 3000L; diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/NacosDataSourceProperties.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/NacosDataSourceProperties.java index ed9b32ae..fd5eb195 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/NacosDataSourceProperties.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/NacosDataSourceProperties.java @@ -16,7 +16,7 @@ package org.springframework.cloud.alibaba.sentinel.datasource.config; -import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.NacosDataSourceFactoryBean; import org.springframework.util.StringUtils; @@ -31,10 +31,10 @@ public class NacosDataSourceProperties extends AbstractDataSourceProperties { private String serverAddr; - @NotEmpty + @NotNull private String groupId = "DEFAULT_GROUP"; - @NotEmpty + @NotNull private String dataId; private String endpoint; diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/ZookeeperDataSourceProperties.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/ZookeeperDataSourceProperties.java index 1307e771..6138b872 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/ZookeeperDataSourceProperties.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/config/ZookeeperDataSourceProperties.java @@ -16,7 +16,7 @@ package org.springframework.cloud.alibaba.sentinel.datasource.config; -import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.ZookeeperDataSourceFactoryBean; @@ -32,7 +32,7 @@ public class ZookeeperDataSourceProperties extends AbstractDataSourceProperties super(ZookeeperDataSourceFactoryBean.class.getName()); } - @NotEmpty + @NotNull private String serverAddr; private String path; diff --git a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelProperties.java b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelProperties.java index 53aea051..274d36de 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelProperties.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelProperties.java @@ -20,6 +20,8 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; +import javax.validation.Valid; + import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.alibaba.sentinel.datasource.config.DataSourcePropertiesConfiguration; import org.springframework.core.Ordered; @@ -55,6 +57,7 @@ public class SentinelProperties { /** * Configurations about datasource, like 'nacos', 'apollo', 'file', 'zookeeper'. */ + @Valid private Map datasource = new TreeMap<>( String.CASE_INSENSITIVE_ORDER); From 9168e60da4eb6d14167e97eb08fba94e09216254 Mon Sep 17 00:00:00 2001 From: fangjian0423 Date: Wed, 20 Feb 2019 17:08:20 +0800 Subject: [PATCH 05/18] refactor sentinel log --- .../converter/SentinelConverter.java | 4 ++-- .../SentinelWebAutoConfiguration.java | 4 ++-- .../custom/SentinelBeanPostProcessor.java | 10 ++++---- .../custom/SentinelDataSourceHandler.java | 24 +++++++++---------- .../custom/SentinelProtectInterceptor.java | 5 ---- 5 files changed, 21 insertions(+), 26 deletions(-) diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/converter/SentinelConverter.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/converter/SentinelConverter.java index bcb246c8..06d2f65b 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/converter/SentinelConverter.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/org/springframework/cloud/alibaba/sentinel/datasource/converter/SentinelConverter.java @@ -53,7 +53,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; public abstract class SentinelConverter implements Converter> { - private static final Logger logger = LoggerFactory.getLogger(SentinelConverter.class); + private static final Logger log = LoggerFactory.getLogger(SentinelConverter.class); private final ObjectMapper objectMapper; @@ -68,7 +68,7 @@ public abstract class SentinelConverter public List convert(String source) { List ruleList = new ArrayList<>(); if (StringUtils.isEmpty(source)) { - logger.warn("converter can not convert rules because source is empty"); + log.warn("converter can not convert rules because source is empty"); return ruleList; } try { diff --git a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelWebAutoConfiguration.java b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelWebAutoConfiguration.java index 8cb957b2..0280fb1d 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelWebAutoConfiguration.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelWebAutoConfiguration.java @@ -42,7 +42,7 @@ import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter; @EnableConfigurationProperties(SentinelProperties.class) public class SentinelWebAutoConfiguration { - private static final Logger logger = LoggerFactory + private static final Logger log = LoggerFactory .getLogger(SentinelWebAutoConfiguration.class); @Autowired @@ -65,7 +65,7 @@ public class SentinelWebAutoConfiguration { Filter filter = new CommonFilter(); registration.setFilter(filter); registration.setOrder(filterConfig.getOrder()); - logger.info("[Sentinel Starter] register Sentinel with urlPatterns: {}.", + log.info("[Sentinel Starter] register Sentinel with urlPatterns: {}.", filterConfig.getUrlPatterns()); return registration; diff --git a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/custom/SentinelBeanPostProcessor.java b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/custom/SentinelBeanPostProcessor.java index 29674e96..7b44dca7 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/custom/SentinelBeanPostProcessor.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/custom/SentinelBeanPostProcessor.java @@ -53,7 +53,7 @@ import com.alibaba.csp.sentinel.slots.block.BlockException; */ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProcessor { - private static final Logger logger = LoggerFactory + private static final Logger log = LoggerFactory .getLogger(SentinelBeanPostProcessor.class); private final ApplicationContext applicationContext; @@ -100,14 +100,14 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces return; } if (blockClass != void.class && StringUtils.isEmpty(blockMethod)) { - logger.error( + log.error( "{} class attribute exists but {} method attribute is not exists in bean[{}]", type, type, beanName); throw new IllegalArgumentException(type + " class attribute exists but " + type + " method attribute is not exists in bean[" + beanName + "]"); } else if (blockClass == void.class && !StringUtils.isEmpty(blockMethod)) { - logger.error( + log.error( "{} method attribute exists but {} class attribute is not exists in bean[{}]", type, type, beanName); throw new IllegalArgumentException(type + " method attribute exists but " @@ -123,7 +123,7 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces String argsStr = Arrays.toString(argList.toArray()); Method foundMethod = ClassUtils.getStaticMethod(blockClass, blockMethod, args); if (foundMethod == null) { - logger.error( + log.error( "{} static method can not be found in bean[{}]. The right method signature is {}#{}{}, please check your class name, method name and arguments", type, beanName, blockClass.getName(), blockMethod, argsStr); throw new IllegalArgumentException(type @@ -134,7 +134,7 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces } if (!ClientHttpResponse.class.isAssignableFrom(foundMethod.getReturnType())) { - logger.error( + log.error( "{} method return value in bean[{}] is not ClientHttpResponse: {}#{}{}", type, beanName, blockClass.getName(), blockMethod, argsStr); throw new IllegalArgumentException(type + " method return value in bean[" diff --git a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/custom/SentinelDataSourceHandler.java b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/custom/SentinelDataSourceHandler.java index 447629df..9e79ec48 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/custom/SentinelDataSourceHandler.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/custom/SentinelDataSourceHandler.java @@ -52,7 +52,7 @@ import com.alibaba.csp.sentinel.slots.block.AbstractRule; */ public class SentinelDataSourceHandler implements SmartInitializingSingleton { - private static final Logger logger = LoggerFactory + private static final Logger log = LoggerFactory .getLogger(SentinelDataSourceHandler.class); private List dataTypeList = Arrays.asList("json", "xml"); @@ -78,7 +78,7 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton { try { List validFields = dataSourceProperties.getValidField(); if (validFields.size() != 1) { - logger.error("[Sentinel Starter] DataSource " + dataSourceName + log.error("[Sentinel Starter] DataSource " + dataSourceName + " multi datasource active and won't loaded: " + dataSourceProperties.getValidField()); return; @@ -90,7 +90,7 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton { + validFields.get(0) + "-datasource"); } catch (Exception e) { - logger.error("[Sentinel Starter] DataSource " + dataSourceName + log.error("[Sentinel Starter] DataSource " + dataSourceName + " build error: " + e.getMessage(), e); } } @@ -109,8 +109,8 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton { } } catch (IllegalAccessException e) { - logger.error("[Sentinel Starter] DataSource " + dataSourceName - + " field: " + field.getName() + " invoke error"); + log.error("[Sentinel Starter] DataSource " + dataSourceName + " field: " + + field.getName() + " invoke error"); throw new RuntimeException("[Sentinel Starter] DataSource " + dataSourceName + " field: " + field.getName() + " invoke error", e); @@ -157,7 +157,7 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton { builder.addPropertyReference("converter", customConvertBeanName); } catch (ClassNotFoundException e) { - logger.error("[Sentinel Starter] DataSource " + dataSourceName + log.error("[Sentinel Starter] DataSource " + dataSourceName + " handle " + dataSourceProperties.getClass().getSimpleName() + " error, class name: " @@ -217,14 +217,14 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton { ruleConfig = dataSource.loadConfig(); } catch (Exception e) { - logger.error("[Sentinel Starter] DataSource " + dataSourceName + log.error("[Sentinel Starter] DataSource " + dataSourceName + " loadConfig error: " + e.getMessage(), e); return; } if (ruleConfig instanceof List) { List convertedRuleList = (List) ruleConfig; if (CollectionUtils.isEmpty(convertedRuleList)) { - logger.warn("[Sentinel Starter] DataSource {} rule list is empty.", + log.warn("[Sentinel Starter] DataSource {} rule list is empty.", dataSourceName); return; } @@ -235,23 +235,23 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton { } } if (matchCount == 0) { - logger.error("[Sentinel Starter] DataSource {} none rules are {} type.", + log.error("[Sentinel Starter] DataSource {} none rules are {} type.", dataSourceName, ruleClass.getSimpleName()); throw new IllegalArgumentException("[Sentinel Starter] DataSource " + dataSourceName + " none rules are " + ruleClass.getSimpleName() + " type."); } else if (matchCount != convertedRuleList.size()) { - logger.warn("[Sentinel Starter] DataSource {} all rules are not {} type.", + log.warn("[Sentinel Starter] DataSource {} all rules are not {} type.", dataSourceName, ruleClass.getSimpleName()); } else { - logger.info("[Sentinel Starter] DataSource {} load {} {}", dataSourceName, + log.info("[Sentinel Starter] DataSource {} load {} {}", dataSourceName, convertedRuleList.size(), ruleClass.getSimpleName()); } } else { - logger.error("[Sentinel Starter] DataSource " + dataSourceName + log.error("[Sentinel Starter] DataSource " + dataSourceName + " rule class is not List<" + ruleClass.getSimpleName() + ">. Class: " + ruleConfig.getClass()); throw new IllegalArgumentException("[Sentinel Starter] DataSource " diff --git a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/custom/SentinelProtectInterceptor.java b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/custom/SentinelProtectInterceptor.java index 49bd003f..f41601ab 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/custom/SentinelProtectInterceptor.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/custom/SentinelProtectInterceptor.java @@ -21,8 +21,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.cloud.alibaba.sentinel.annotation.SentinelRestTemplate; import org.springframework.cloud.alibaba.sentinel.rest.SentinelClientHttpResponse; import org.springframework.http.HttpRequest; @@ -44,9 +42,6 @@ import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException; */ public class SentinelProtectInterceptor implements ClientHttpRequestInterceptor { - private static final Logger logger = LoggerFactory - .getLogger(SentinelProtectInterceptor.class); - private final SentinelRestTemplate sentinelRestTemplate; public SentinelProtectInterceptor(SentinelRestTemplate sentinelRestTemplate) { From a03ce9fea83a196ae8013f486f1b4b1fa793500f Mon Sep 17 00:00:00 2001 From: flystar32 Date: Wed, 20 Feb 2019 19:02:17 +0800 Subject: [PATCH 06/18] add test case and nacos watch --- .../alibaba/nacos/NacosConfigProperties.java | 1 - .../client/NacosPropertySourceLocator.java | 8 +- .../NacosDiscoveryAutoConfiguration.java | 57 ++++- .../nacos/NacosDiscoveryProperties.java | 42 +++- .../{ => discovery}/NacosDiscoveryClient.java | 20 +- ...NacosDiscoveryClientAutoConfiguration.java | 20 +- .../alibaba/nacos/discovery/NacosWatch.java | 183 ++++++++++++++++ .../endpoint/NacosDiscoveryEndpoint.java | 5 +- ...cosDiscoveryEndpointAutoConfiguration.java | 7 +- .../NacosAutoServiceRegistration.java | 9 +- .../nacos/registry/NacosRegistration.java | 20 +- .../nacos/registry/NacosServiceRegistry.java | 38 ++-- .../NacosRibbonClientConfiguration.java | 5 +- .../alibaba/nacos/ribbon/NacosServerList.java | 17 +- ...itional-spring-configuration-metadata.json | 6 +- .../main/resources/META-INF/spring.factories | 5 +- .../NacosDiscoveryAutoConfigurationTests.java | 6 +- .../nacos/NacosDiscoveryClientTests.java | 127 +++++++++++ ...ceRegistrationIpNetworkInterfaceTests.java | 147 +++++++++++++ .../NacosAutoServiceRegistrationIpTests.java | 82 ++++++++ ...erviceRegistrationManagementPortTests.java | 88 ++++++++ ...NacosAutoServiceRegistrationPortTests.java | 82 ++++++++ .../NacosAutoServiceRegistrationTests.java | 199 ++++++++++++++++++ .../NacosRibbonClientConfigurationTests.java | 82 -------- .../nacos/ribbon/NacosServerListTests.java | 175 +++++++++++++++ .../alibaba/nacos/test/CommonTestConfig.java | 36 ++++ .../alibaba/nacos/test/NacosMockTest.java | 49 +++++ 27 files changed, 1338 insertions(+), 178 deletions(-) rename spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/{ => discovery}/NacosDiscoveryClient.java (85%) rename spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/{ => discovery}/NacosDiscoveryClientAutoConfiguration.java (58%) create mode 100644 spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosWatch.java create mode 100644 spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientTests.java create mode 100644 spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java create mode 100644 spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationIpTests.java create mode 100644 spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationManagementPortTests.java create mode 100644 spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationPortTests.java create mode 100644 spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationTests.java delete mode 100644 spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java create mode 100644 spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerListTests.java create mode 100644 spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/test/CommonTestConfig.java create mode 100644 spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/test/NacosMockTest.java diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigProperties.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigProperties.java index d19e8acf..c0e45492 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigProperties.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigProperties.java @@ -18,7 +18,6 @@ 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; diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceLocator.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceLocator.java index 5ce9afea..7a665d2b 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceLocator.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceLocator.java @@ -183,19 +183,19 @@ public class NacosPropertySourceLocator implements PropertySourceLocator { } } - private static void checkDataIdFileExtension(String[] sharedDataIdArry) { + private static void checkDataIdFileExtension(String[] dataIdArray) { StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < sharedDataIdArry.length; i++) { + for (int i = 0; i < dataIdArray.length; i++) { boolean isLegal = false; for (String fileExtension : SUPPORT_FILE_EXTENSION) { - if (sharedDataIdArry[i].indexOf(fileExtension) > 0) { + if (dataIdArray[i].indexOf(fileExtension) > 0) { isLegal = true; break; } } // add tips if (!isLegal) { - stringBuilder.append(sharedDataIdArry[i] + ","); + stringBuilder.append(dataIdArray[i] + ","); } } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java index 6e087422..f53a0562 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java @@ -16,16 +16,23 @@ package org.springframework.cloud.alibaba.nacos; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration; import org.springframework.cloud.alibaba.nacos.registry.NacosAutoServiceRegistration; import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration; import org.springframework.cloud.alibaba.nacos.registry.NacosServiceRegistry; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -38,19 +45,28 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnNacosDiscoveryEnabled @ConditionalOnClass(name = "org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent") @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) -@AutoConfigureBefore({ AutoServiceRegistrationAutoConfiguration.class, - NacosDiscoveryClientAutoConfiguration.class }) +@AutoConfigureBefore(NacosDiscoveryClientAutoConfiguration.class) +@AutoConfigureAfter(AutoServiceRegistrationConfiguration.class) public class NacosDiscoveryAutoConfiguration { @Bean - public NacosServiceRegistry nacosServiceRegistry() { - return new NacosServiceRegistry(); + @ConditionalOnMissingBean + public NacosDiscoveryProperties nacosProperties() { + return new NacosDiscoveryProperties(); + } + + @Bean + public NacosServiceRegistry nacosServiceRegistry( + NacosDiscoveryProperties nacosDiscoveryProperties) { + return new NacosServiceRegistry(nacosDiscoveryProperties); } @Bean @ConditionalOnBean(AutoServiceRegistrationProperties.class) - public NacosRegistration nacosRegistration() { - return new NacosRegistration(); + public NacosRegistration nacosRegistration( + NacosDiscoveryProperties nacosDiscoveryProperties, + ApplicationContext context) { + return new NacosRegistration(nacosDiscoveryProperties, context); } @Bean @@ -62,4 +78,31 @@ public class NacosDiscoveryAutoConfiguration { return new NacosAutoServiceRegistration(registry, autoServiceRegistrationProperties, registration); } + + @Bean + @ConditionalOnBean(NacosAutoServiceRegistration.class) // NacosAutoServiceRegistration + // should be present + @ConditionalOnNotWebApplication // Not Web Application + public ApplicationRunner applicationRunner( + final NacosAutoServiceRegistration nacosAutoServiceRegistration) { + + return new ApplicationRunner() { + @Override + public void run(ApplicationArguments args) throws Exception { + if (!nacosAutoServiceRegistration.isRunning()) { // If it's not running, + // let + // it start. + // FIXME: Please make sure "spring.cloud.nacos.discovery.port" must be + // configured on an available port, + // or the startup or Nacos health check will be failed. + nacosAutoServiceRegistration.start(); + // NacosAutoServiceRegistration will be stopped after its destroy() + // method + // is invoked. + // @PreDestroy destroy() -> stop() + } + } + }; + } + } \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java index 11fb1290..ecb0b136 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java @@ -27,7 +27,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.commons.util.InetUtils; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; - import javax.annotation.PostConstruct; import java.net.Inet4Address; import java.net.InetAddress; @@ -40,7 +39,7 @@ import static com.alibaba.nacos.api.PropertyKeyConst.*; /** * @author dungu.zpf * @author xiaojing - * @author pbting + * @author Mercy */ @ConfigurationProperties("spring.cloud.nacos.discovery") @@ -65,6 +64,11 @@ public class NacosDiscoveryProperties { */ private String namespace; + /** + * watch delay,duration to pull new service from nacos server. + */ + private long watchDelay = 5000; + /** * nacos naming log file name */ @@ -145,7 +149,14 @@ public class NacosDiscoveryProperties { @PostConstruct public void init() throws SocketException { + if (secure) { + metadata.put("secure", "true"); + } + serverAddr = Objects.toString(serverAddr, ""); + if (serverAddr.lastIndexOf("/") != -1) { + serverAddr.substring(0, serverAddr.length() - 1); + } endpoint = Objects.toString(endpoint, ""); namespace = Objects.toString(namespace, ""); logName = Objects.toString(logName, ""); @@ -158,7 +169,7 @@ public class NacosDiscoveryProperties { else { NetworkInterface netInterface = NetworkInterface .getByName(networkInterface); - if (null == networkInterface) { + if (null == netInterface) { throw new IllegalArgumentException( "no such interface " + networkInterface); } @@ -316,16 +327,25 @@ public class NacosDiscoveryProperties { this.namingLoadCacheAtStart = namingLoadCacheAtStart; } + public long getWatchDelay() { + return watchDelay; + } + + public void setWatchDelay(long watchDelay) { + this.watchDelay = watchDelay; + } + @Override public String toString() { return "NacosDiscoveryProperties{" + "serverAddr='" + serverAddr + '\'' + ", endpoint='" + endpoint + '\'' + ", namespace='" + namespace + '\'' - + ", logName='" + logName + '\'' + ", service='" + service + '\'' - + ", weight=" + weight + ", clusterName='" + clusterName + '\'' - + ", metadata=" + metadata + ", registerEnabled=" + registerEnabled - + ", ip='" + ip + '\'' + ", networkInterface='" + networkInterface + '\'' - + ", port=" + port + ", secure=" + secure + ", accessKey='" + accessKey - + ", namingLoadCacheAtStart=" + namingLoadCacheAtStart + '\'' + + ", watchDelay=" + watchDelay + ", logName='" + logName + '\'' + + ", service='" + service + '\'' + ", weight=" + weight + + ", clusterName='" + clusterName + '\'' + ", namingLoadCacheAtStart='" + + namingLoadCacheAtStart + '\'' + ", metadata=" + metadata + + ", registerEnabled=" + registerEnabled + ", ip='" + ip + '\'' + + ", networkInterface='" + networkInterface + '\'' + ", port=" + port + + ", secure=" + secure + ", accessKey='" + accessKey + '\'' + ", secretKey='" + secretKey + '\'' + '}'; } @@ -353,7 +373,7 @@ public class NacosDiscoveryProperties { } if (StringUtils.isEmpty(this.getClusterName())) { this.setClusterName(env.resolvePlaceholders( - "${spring.cloud.nacos.discovery.clusterName-name:}")); + "${spring.cloud.nacos.discovery.cluster-name:}")); } if (StringUtils.isEmpty(this.getEndpoint())) { this.setEndpoint( @@ -379,12 +399,12 @@ public class NacosDiscoveryProperties { try { namingService = NacosFactory.createNamingService(properties); - return namingService; } catch (Exception e) { LOGGER.error("create naming service error!properties={},e=,", this, e); return null; } + return namingService; } } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClient.java similarity index 85% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java rename to spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClient.java index eedc2ffe..1bc25ea5 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClient.java @@ -14,13 +14,14 @@ * limitations under the License. */ -package org.springframework.cloud.alibaba.nacos; +package org.springframework.cloud.alibaba.nacos.discovery; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; +import org.springframework.cloud.alibaba.nacos.NacosServiceInstance; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; @@ -30,7 +31,6 @@ import java.util.*; /** * @author xiaojing * @author renhaojun - * @author pbting */ public class NacosDiscoveryClient implements DiscoveryClient { @@ -38,9 +38,12 @@ public class NacosDiscoveryClient implements DiscoveryClient { .getLogger(NacosDiscoveryClient.class); public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client"; - @Autowired private NacosDiscoveryProperties discoveryProperties; + public NacosDiscoveryClient(NacosDiscoveryProperties discoveryProperties) { + this.discoveryProperties = discoveryProperties; + } + @Override public String description() { return DESCRIPTION; @@ -75,19 +78,24 @@ public class NacosDiscoveryClient implements DiscoveryClient { nacosServiceInstance.setHost(instance.getIp()); nacosServiceInstance.setPort(instance.getPort()); nacosServiceInstance.setServiceId(serviceId); - Map metadata = new HashMap(); + Map metadata = new HashMap<>(); metadata.put("instanceId", instance.getInstanceId()); metadata.put("weight", instance.getWeight() + ""); metadata.put("healthy", instance.isHealthy() + ""); metadata.put("cluster", instance.getClusterName() + ""); metadata.putAll(instance.getMetadata()); nacosServiceInstance.setMetadata(metadata); + + if (metadata.containsKey("secure")) { + boolean secure = Boolean.parseBoolean(metadata.get("secure")); + nacosServiceInstance.setSecure(secure); + } return nacosServiceInstance; } private static List hostToServiceInstanceList( List instances, String serviceId) { - List result = new ArrayList(instances.size()); + List result = new ArrayList<>(instances.size()); for (Instance instance : instances) { result.add(hostToServiceInstance(instance, serviceId)); } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java similarity index 58% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java rename to spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java index 05049f4b..5fe818b3 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java @@ -14,11 +14,16 @@ * limitations under the License. */ -package org.springframework.cloud.alibaba.nacos; +package org.springframework.cloud.alibaba.nacos.discovery; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.cloud.alibaba.nacos.ConditionalOnNacosDiscoveryEnabled; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; +import org.springframework.cloud.client.CommonsClientAutoConfiguration; import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -26,20 +31,21 @@ import org.springframework.context.annotation.Configuration; * @author xiaojing */ @Configuration -@ConditionalOnMissingBean(DiscoveryClient.class) @ConditionalOnNacosDiscoveryEnabled @EnableConfigurationProperties +@AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class, + CommonsClientAutoConfiguration.class }) public class NacosDiscoveryClientAutoConfiguration { @Bean - public DiscoveryClient nacosDiscoveryClient() { - return new NacosDiscoveryClient(); + public DiscoveryClient nacosDiscoveryClient( + NacosDiscoveryProperties discoveryProperties) { + return new NacosDiscoveryClient(discoveryProperties); } @Bean @ConditionalOnMissingBean - public NacosDiscoveryProperties nacosProperties() { - return new NacosDiscoveryProperties(); + public NacosWatch nacosWatch(NacosDiscoveryProperties nacosDiscoveryProperties) { + return new NacosWatch(nacosDiscoveryProperties); } - } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosWatch.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosWatch.java new file mode 100644 index 00000000..05e92fbc --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosWatch.java @@ -0,0 +1,183 @@ +/* + * Copyright (C) 2019 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 org.springframework.cloud.alibaba.nacos.discovery; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; + +import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.api.naming.listener.Event; +import com.alibaba.nacos.api.naming.listener.EventListener; +import com.alibaba.nacos.api.naming.pojo.ListView; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; +import org.springframework.cloud.client.discovery.event.HeartbeatEvent; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.ApplicationEventPublisherAware; +import org.springframework.context.SmartLifecycle; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; + +/** + * @author xiaojing + */ +public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycle { + + private static final Logger log = LoggerFactory.getLogger(NacosWatch.class); + + private final NacosDiscoveryProperties properties; + + private final TaskScheduler taskScheduler; + + private final AtomicLong nacosWatchIndex = new AtomicLong(0); + + private final AtomicBoolean running = new AtomicBoolean(false); + + private ApplicationEventPublisher publisher; + + private ScheduledFuture watchFuture; + + private Set cacheServices = new HashSet<>(); + + private HashMap subscribeListeners = new HashMap<>(); + + public NacosWatch(NacosDiscoveryProperties properties) { + this(properties, getTaskScheduler()); + } + + public NacosWatch(NacosDiscoveryProperties properties, TaskScheduler taskScheduler) { + this.properties = properties; + this.taskScheduler = taskScheduler; + } + + private static ThreadPoolTaskScheduler getTaskScheduler() { + ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); + taskScheduler.initialize(); + return taskScheduler; + } + + @Override + public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { + this.publisher = publisher; + } + + @Override + public boolean isAutoStartup() { + return true; + } + + @Override + public void stop(Runnable callback) { + this.stop(); + callback.run(); + } + + @Override + public void start() { + if (this.running.compareAndSet(false, true)) { + this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(new Runnable() { + @Override + public void run() { + NacosWatch.this.nacosServicesWatch(); + } + }, this.properties.getWatchDelay()); + } + } + + @Override + public void stop() { + if (this.running.compareAndSet(true, false) && this.watchFuture != null) { + this.watchFuture.cancel(true); + } + } + + @Override + public boolean isRunning() { + return false; + } + + @Override + public int getPhase() { + return 0; + } + + public void nacosServicesWatch() { + try { + + boolean changed = false; + NamingService namingService = properties.namingServiceInstance(); + + ListView listView = properties.namingServiceInstance() + .getServicesOfServer(1, Integer.MAX_VALUE); + + List serviceList = listView.getData(); + + // if there are new services found, publish event + Set currentServices = new HashSet<>(serviceList); + currentServices.removeAll(cacheServices); + if (currentServices.size() > 0) { + changed = true; + } + + // if some services disappear, publish event + if (cacheServices.removeAll(new HashSet<>(serviceList)) + && cacheServices.size() > 0) { + changed = true; + + for (String serviceName : cacheServices) { + namingService.unsubscribe(serviceName, + subscribeListeners.get(serviceName)); + subscribeListeners.remove(serviceName); + } + } + + cacheServices = new HashSet<>(serviceList); + + // subscribe services's node change, publish event if nodes changed + for (String serviceName : cacheServices) { + if (!subscribeListeners.containsKey(serviceName)) { + EventListener eventListener = new EventListener() { + @Override + public void onEvent(Event event) { + NacosWatch.this.publisher.publishEvent(new HeartbeatEvent( + NacosWatch.this, nacosWatchIndex.getAndIncrement())); + } + }; + subscribeListeners.put(serviceName, eventListener); + namingService.subscribe(serviceName, eventListener); + + } + } + + if (changed) { + this.publisher.publishEvent( + new HeartbeatEvent(this, nacosWatchIndex.getAndIncrement())); + } + + } + catch (Exception e) { + log.error("Error watching Nacos Service change", e); + } + } +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java index ef29eae1..be0907c6 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java @@ -26,7 +26,6 @@ import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.AbstractEndpoint; import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; @@ -39,11 +38,11 @@ public class NacosDiscoveryEndpoint extends AbstractEndpoint private static final Logger LOGGER = LoggerFactory .getLogger(NacosDiscoveryEndpoint.class); - @Autowired private NacosDiscoveryProperties nacosDiscoveryProperties; - public NacosDiscoveryEndpoint() { + public NacosDiscoveryEndpoint(NacosDiscoveryProperties nacosDiscoveryProperties) { super("nacos_discovery", false); + this.nacosDiscoveryProperties = nacosDiscoveryProperties; } /** diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java index eab95411..8e57c23a 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java @@ -18,7 +18,7 @@ package org.springframework.cloud.alibaba.nacos.endpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -31,8 +31,9 @@ public class NacosDiscoveryEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean - public NacosDiscoveryEndpoint nacosDiscoveryEndpoint() { - return new NacosDiscoveryEndpoint(); + public NacosDiscoveryEndpoint nacosDiscoveryEndpoint( + NacosDiscoveryProperties nacosDiscoveryProperties) { + return new NacosDiscoveryEndpoint(nacosDiscoveryProperties); } } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistration.java index 66df7944..05c638dc 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistration.java @@ -18,26 +18,25 @@ package org.springframework.cloud.alibaba.nacos.registry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; +import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.cloud.client.serviceregistry.ServiceRegistry; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * @author xiaojing + * @author Mercy */ public class NacosAutoServiceRegistration - extends AbstractAutoServiceRegistration { + extends AbstractAutoServiceRegistration { private static final Logger LOGGER = LoggerFactory .getLogger(NacosAutoServiceRegistration.class); - @Autowired private NacosRegistration registration; - public NacosAutoServiceRegistration( - ServiceRegistry serviceRegistry, + public NacosAutoServiceRegistration(ServiceRegistry serviceRegistry, AutoServiceRegistrationProperties autoServiceRegistrationProperties, NacosRegistration registration) { super(serviceRegistry, autoServiceRegistrationProperties); diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java index 3254bc75..584d454c 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java @@ -17,7 +17,6 @@ package org.springframework.cloud.alibaba.nacos.registry; import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.ManagementServerPortUtils; @@ -38,16 +37,20 @@ import com.alibaba.nacos.api.naming.NamingService; */ public class NacosRegistration implements Registration, ServiceInstance { - private static final String MANAGEMENT_PORT = "management.port"; - private static final String MANAGEMENT_CONTEXT_PATH = "management.context-path"; - private static final String MANAGEMENT_ADDRESS = "management.address"; + public static final String MANAGEMENT_PORT = "management.port"; + public static final String MANAGEMENT_CONTEXT_PATH = "management.context-path"; + public static final String MANAGEMENT_ADDRESS = "management.address"; - @Autowired private NacosDiscoveryProperties nacosDiscoveryProperties; - @Autowired private ApplicationContext context; + public NacosRegistration(NacosDiscoveryProperties nacosDiscoveryProperties, + ApplicationContext context) { + this.nacosDiscoveryProperties = nacosDiscoveryProperties; + this.context = context; + } + @PostConstruct public void init() { @@ -121,11 +124,6 @@ public class NacosRegistration implements Registration, ServiceInstance { return nacosDiscoveryProperties.namingServiceInstance(); } - public void setNacosDiscoveryProperties( - NacosDiscoveryProperties nacosDiscoveryProperties) { - this.nacosDiscoveryProperties = nacosDiscoveryProperties; - } - @Override public String toString() { return "NacosRegistration{" + "nacosDiscoveryProperties=" diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosServiceRegistry.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosServiceRegistry.java index 8f8803fb..d2d5fa67 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosServiceRegistry.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosServiceRegistry.java @@ -20,37 +20,43 @@ import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; +import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.cloud.client.serviceregistry.ServiceRegistry; import org.springframework.util.StringUtils; /** * @author xiaojing - * @author pbting + * @author Mercy */ -public class NacosServiceRegistry implements ServiceRegistry { +public class NacosServiceRegistry implements ServiceRegistry { private static Logger logger = LoggerFactory.getLogger(NacosServiceRegistry.class); - @Override - public void register(NacosRegistration registration) { + private final NacosDiscoveryProperties nacosDiscoveryProperties; + + private final NamingService namingService; + + public NacosServiceRegistry(NacosDiscoveryProperties nacosDiscoveryProperties) { + this.nacosDiscoveryProperties = nacosDiscoveryProperties; + this.namingService = nacosDiscoveryProperties.namingServiceInstance(); + } + + @Override + public void register(Registration registration) { - if (!registration.isRegisterEnabled()) { - logger.info("Nacos Registration is disabled..."); - return; - } if (StringUtils.isEmpty(registration.getServiceId())) { logger.info("No service to register for nacos client..."); return; } - NamingService namingService = registration.getNacosNamingService(); String serviceId = registration.getServiceId(); Instance instance = new Instance(); instance.setIp(registration.getHost()); instance.setPort(registration.getPort()); - instance.setWeight(registration.getRegisterWeight()); - instance.setClusterName(registration.getCluster()); + instance.setWeight(nacosDiscoveryProperties.getWeight()); + instance.setClusterName(nacosDiscoveryProperties.getClusterName()); instance.setMetadata(registration.getMetadata()); try { @@ -65,7 +71,7 @@ public class NacosServiceRegistry implements ServiceRegistry } @Override - public void deregister(NacosRegistration registration) { + public void deregister(Registration registration) { logger.info("De-registering from Nacos Server now..."); @@ -74,12 +80,12 @@ public class NacosServiceRegistry implements ServiceRegistry return; } - NamingService namingService = registration.getNacosNamingService(); + NamingService namingService = nacosDiscoveryProperties.namingServiceInstance(); String serviceId = registration.getServiceId(); try { namingService.deregisterInstance(serviceId, registration.getHost(), - registration.getPort(), registration.getCluster()); + registration.getPort(), nacosDiscoveryProperties.getClusterName()); } catch (Exception e) { logger.error("ERR_NACOS_DEREGISTER, de-register failed...{},", @@ -95,12 +101,12 @@ public class NacosServiceRegistry implements ServiceRegistry } @Override - public void setStatus(NacosRegistration registration, String status) { + public void setStatus(Registration registration, String status) { // nacos doesn't support set status of a particular registration. } @Override - public T getStatus(NacosRegistration registration) { + public T getStatus(Registration registration) { // nacos doesn't support query status of a particular registration. return null; } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfiguration.java index e3d1f732..ddd1696e 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfiguration.java @@ -19,6 +19,7 @@ package org.springframework.cloud.alibaba.nacos.ribbon; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ServerList; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -32,8 +33,8 @@ public class NacosRibbonClientConfiguration { @Bean @ConditionalOnMissingBean - public ServerList ribbonServerList(IClientConfig config) { - NacosServerList serverList = new NacosServerList(); + public ServerList ribbonServerList(IClientConfig config, NacosDiscoveryProperties nacosDiscoveryProperties) { + NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); serverList.initWithNiwsConfig(config); return serverList; } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java index 74dda2de..42fa9f8f 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java @@ -16,32 +16,26 @@ package org.springframework.cloud.alibaba.nacos.ribbon; +import com.alibaba.nacos.api.naming.pojo.Instance; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractServerList; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; import java.util.ArrayList; import java.util.List; -import com.alibaba.nacos.api.naming.pojo.Instance; - /** * @author xiaojing * @author renhaojun */ public class NacosServerList extends AbstractServerList { - @Autowired private NacosDiscoveryProperties discoveryProperties; private String serviceId; - public NacosServerList() { - } - - public NacosServerList(String serviceId) { - this.serviceId = serviceId; + public NacosServerList(NacosDiscoveryProperties discoveryProperties) { + this.discoveryProperties = discoveryProperties; } @Override @@ -68,7 +62,10 @@ public class NacosServerList extends AbstractServerList { } private List instancesToServerList(List instances) { - List result = new ArrayList<>(instances.size()); + List result = new ArrayList<>(); + if (null == instances) { + return result; + } for (Instance instance : instances) { result.add(new NacosServer(instance)); } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 27f753ff..d0e82a51 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -1,5 +1,4 @@ -{ - "properties": [ +{"properties": [ { "name": "spring.cloud.nacos.discovery.service", "type": "java.lang.String", @@ -12,5 +11,4 @@ "defaultValue": "false", "description": "naming load from local cache at application start ." } - ] -} +]} diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/spring.factories index 723407fe..2fe11df1 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/spring.factories @@ -1,6 +1,5 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration,\ org.springframework.cloud.alibaba.nacos.ribbon.RibbonNacosAutoConfiguration,\ - org.springframework.cloud.alibaba.nacos.endpoint.NacosDiscoveryEndpointAutoConfiguration -org.springframework.cloud.client.discovery.EnableDiscoveryClient=\ -org.springframework.cloud.alibaba.nacos.NacosDiscoveryClientAutoConfiguration + org.springframework.cloud.alibaba.nacos.endpoint.NacosDiscoveryEndpointAutoConfiguration,\ + org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java index 4be0dd92..7d6dfc8a 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java @@ -19,9 +19,9 @@ package org.springframework.cloud.alibaba.nacos; import org.junit.Before; import org.junit.Test; import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration; import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; import org.springframework.cloud.commons.util.InetUtils; @@ -44,7 +44,7 @@ public class NacosDiscoveryAutoConfigurationTests { this.context = new SpringApplicationBuilder(NacosDiscoveryTestConfiguration.class, NacosDiscoveryClientAutoConfiguration.class, NacosDiscoveryAutoConfiguration.class).web(false).run( - "--spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080", + "--spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", "--spring.cloud.nacos.discovery.port=18080", "--spring.cloud.nacos.discovery.service=myapp"); } @@ -55,7 +55,7 @@ public class NacosDiscoveryAutoConfigurationTests { NacosDiscoveryProperties properties = context .getBean(NacosDiscoveryProperties.class); assertThat(properties.getPort()).isEqualTo(18080); - assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8080"); + assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848"); assertThat(properties.getService()).isEqualTo("myapp"); } diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientTests.java new file mode 100644 index 00000000..a0c144f3 --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientTests.java @@ -0,0 +1,127 @@ +/* + * 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 org.springframework.cloud.alibaba.nacos; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; + +import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.pojo.ListView; + +import org.junit.Test; +import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClient; +import org.springframework.cloud.client.ServiceInstance; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.cloud.alibaba.nacos.test.NacosMockTest.serviceInstance; + +/** + * @author xiaojing + */ +public class NacosDiscoveryClientTests { + + private String host = "123.123.123.123"; + private int port = 8888; + private String serviceName = "test-service"; + + @Test + public void testGetServers() throws Exception { + + ArrayList instances = new ArrayList<>(); + + HashMap map = new HashMap<>(); + map.put("test-key", "test-value"); + map.put("secure", "true"); + + instances.add(serviceInstance(serviceName, false, host, port, map)); + + NacosDiscoveryProperties nacosDiscoveryProperties = mock( + NacosDiscoveryProperties.class); + + NamingService namingService = mock(NamingService.class); + + when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); + when(namingService.selectInstances(eq(serviceName), eq(true))) + .thenReturn(instances); + + NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient( + nacosDiscoveryProperties); + + List serviceInstances = discoveryClient + .getInstances(serviceName); + + assertThat(serviceInstances.size()).isEqualTo(1); + + ServiceInstance serviceInstance = serviceInstances.get(0); + + assertThat(serviceInstance.getServiceId()).isEqualTo(serviceName); + assertThat(serviceInstance.getHost()).isEqualTo(host); + assertThat(serviceInstance.getPort()).isEqualTo(port); + assertThat(serviceInstance.isSecure()).isEqualTo(true); + assertThat(serviceInstance.getUri().toString()) + .isEqualTo(getUri(serviceInstance)); + assertThat(serviceInstance.getMetadata().get("test-key")).isEqualTo("test-value"); + + } + + @Test + public void testGetAllService() throws Exception { + + ListView nacosServices = new ListView<>(); + + nacosServices.setData(new LinkedList()); + + nacosServices.getData().add(serviceName + "1"); + nacosServices.getData().add(serviceName + "2"); + nacosServices.getData().add(serviceName + "3"); + + NacosDiscoveryProperties nacosDiscoveryProperties = mock( + NacosDiscoveryProperties.class); + + NamingService namingService = mock(NamingService.class); + + NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient( + nacosDiscoveryProperties); + + when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); + when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE))) + .thenReturn(nacosServices); + + List services = discoveryClient.getServices(); + + assertThat(services.size()).isEqualTo(3); + assertThat(services.contains(serviceName + "1")); + assertThat(services.contains(serviceName + "2")); + assertThat(services.contains(serviceName + "3")); + + } + + private String getUri(ServiceInstance instance) { + + if (instance.isSecure()) { + return "https://" + host + ":" + port; + } + + return "http://" + host + ":" + port; + } +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java new file mode 100644 index 00000000..8ec4c7b1 --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java @@ -0,0 +1,147 @@ +/* + * 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 org.springframework.cloud.alibaba.nacos.registry; + +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.util.Enumeration; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +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.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration; +import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.cloud.commons.util.InetUtils; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = NacosAutoServiceRegistrationIpNetworkInterfaceTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848" }, webEnvironment = RANDOM_PORT) +public class NacosAutoServiceRegistrationIpNetworkInterfaceTests { + + @Autowired + private NacosRegistration registration; + + @Autowired + private NacosAutoServiceRegistration nacosAutoServiceRegistration; + + @Autowired + private NacosDiscoveryProperties properties; + + @Autowired + private InetUtils inetUtils; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("NacosRegistration was not created", registration); + assertNotNull("NacosDiscoveryProperties was not created", properties); + assertNotNull("NacosAutoServiceRegistration was not created", + nacosAutoServiceRegistration); + + checkoutNacosDiscoveryServiceIP(); + + } + + private void checkoutNacosDiscoveryServiceIP() { + assertEquals("NacosDiscoveryProperties service IP was wrong", + getIPFromNetworkInterface(TestConfig.netWorkInterfaceName), + registration.getHost()); + + } + + private String getIPFromNetworkInterface(String networkInterface) { + + if (!TestConfig.hasValidNetworkInterface) { + return inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(); + } + + try { + NetworkInterface netInterface = NetworkInterface.getByName(networkInterface); + + Enumeration inetAddress = netInterface.getInetAddresses(); + while (inetAddress.hasMoreElements()) { + InetAddress currentAddress = inetAddress.nextElement(); + if (currentAddress instanceof Inet4Address + && !currentAddress.isLoopbackAddress()) { + return currentAddress.getHostAddress(); + } + } + return networkInterface; + } + catch (Exception e) { + return networkInterface; + } + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + NacosDiscoveryClientAutoConfiguration.class, + NacosDiscoveryAutoConfiguration.class }) + public static class TestConfig { + + static boolean hasValidNetworkInterface = false; + static String netWorkInterfaceName; + + static { + + try { + Enumeration enumeration = NetworkInterface + .getNetworkInterfaces(); + while (enumeration.hasMoreElements() && !hasValidNetworkInterface) { + NetworkInterface networkInterface = enumeration.nextElement(); + Enumeration inetAddress = networkInterface + .getInetAddresses(); + while (inetAddress.hasMoreElements()) { + InetAddress currentAddress = inetAddress.nextElement(); + if (currentAddress instanceof Inet4Address + && !currentAddress.isLoopbackAddress()) { + hasValidNetworkInterface = true; + netWorkInterfaceName = networkInterface.getName(); + System.setProperty( + "spring.cloud.nacos.discovery.network-interface", + networkInterface.getName()); + break; + } + } + } + + } + catch (Exception e) { + + } + } + } + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationIpTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationIpTests.java new file mode 100644 index 00000000..872c22a1 --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationIpTests.java @@ -0,0 +1,82 @@ +/* + * 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 org.springframework.cloud.alibaba.nacos.registry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +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.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration; +import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = NacosAutoServiceRegistrationIpTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.discovery.ip=123.123.123.123" }, webEnvironment = RANDOM_PORT) +public class NacosAutoServiceRegistrationIpTests { + + @Autowired + private NacosRegistration registration; + + @Autowired + private NacosAutoServiceRegistration nacosAutoServiceRegistration; + + @Autowired + private NacosDiscoveryProperties properties; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("NacosRegistration was not created", registration); + assertNotNull("NacosDiscoveryProperties was not created", properties); + assertNotNull("NacosAutoServiceRegistration was not created", + nacosAutoServiceRegistration); + + checkoutNacosDiscoveryServiceIP(); + + } + + private void checkoutNacosDiscoveryServiceIP() { + assertEquals("NacosDiscoveryProperties service IP was wrong", "123.123.123.123", + registration.getHost()); + + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + NacosDiscoveryClientAutoConfiguration.class, + NacosDiscoveryAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationManagementPortTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationManagementPortTests.java new file mode 100644 index 00000000..74cf1a5b --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationManagementPortTests.java @@ -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 org.springframework.cloud.alibaba.nacos.registry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +import static org.springframework.cloud.alibaba.nacos.registry.NacosRegistration.MANAGEMENT_PORT; +import static org.springframework.cloud.alibaba.nacos.registry.NacosRegistration.MANAGEMENT_CONTEXT_PATH; + +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.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration; +import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = NacosAutoServiceRegistrationManagementPortTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", "management.port=8888", + "management.context-path=/test-context-path", + "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.discovery.port=8888" }, webEnvironment = RANDOM_PORT) +public class NacosAutoServiceRegistrationManagementPortTests { + + @Autowired + private NacosRegistration registration; + + @Autowired + private NacosAutoServiceRegistration nacosAutoServiceRegistration; + + @Autowired + private NacosDiscoveryProperties properties; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("NacosRegistration was not created", registration); + assertNotNull("NacosDiscoveryProperties was not created", properties); + assertNotNull("NacosAutoServiceRegistration was not created", + nacosAutoServiceRegistration); + + checkoutNacosDiscoveryManagementData(); + + } + + private void checkoutNacosDiscoveryManagementData() { + assertEquals("NacosDiscoveryProperties management port was wrong", "8888", + properties.getMetadata().get(MANAGEMENT_PORT)); + + assertEquals("NacosDiscoveryProperties management context path was wrong", + "/test-context-path", + properties.getMetadata().get(MANAGEMENT_CONTEXT_PATH)); + + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + NacosDiscoveryClientAutoConfiguration.class, + NacosDiscoveryAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationPortTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationPortTests.java new file mode 100644 index 00000000..ab76dc97 --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationPortTests.java @@ -0,0 +1,82 @@ +/* + * 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 org.springframework.cloud.alibaba.nacos.registry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +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.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration; +import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = NacosAutoServiceRegistrationPortTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.discovery.port=8888" }, webEnvironment = RANDOM_PORT) +public class NacosAutoServiceRegistrationPortTests { + + @Autowired + private NacosRegistration registration; + + @Autowired + private NacosAutoServiceRegistration nacosAutoServiceRegistration; + + @Autowired + private NacosDiscoveryProperties properties; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("NacosRegistration was not created", registration); + assertNotNull("NacosDiscoveryProperties was not created", properties); + assertNotNull("NacosAutoServiceRegistration was not created", + nacosAutoServiceRegistration); + + checkoutNacosDiscoveryServicePort(); + + } + + private void checkoutNacosDiscoveryServicePort() { + assertEquals("NacosDiscoveryProperties service Port was wrong", 8888, + registration.getPort()); + + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + NacosDiscoveryClientAutoConfiguration.class, + NacosDiscoveryAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationTests.java new file mode 100644 index 00000000..0bca8136 --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistrationTests.java @@ -0,0 +1,199 @@ +/* + * 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 org.springframework.cloud.alibaba.nacos.registry; + +import java.util.Map; + +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.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration; +import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; +import org.springframework.cloud.alibaba.nacos.endpoint.NacosDiscoveryEndpoint; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.cloud.commons.util.InetUtils; +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.junit.Assert.assertTrue; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = NacosAutoServiceRegistrationTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.discovery.endpoint=test-endpoint", + "spring.cloud.nacos.discovery.namespace=test-namespace", + "spring.cloud.nacos.discovery.log-name=test-logName", + "spring.cloud.nacos.discovery.weight=2", + "spring.cloud.nacos.discovery.clusterName=test-cluster", + "spring.cloud.nacos.discovery.namingLoadCacheAtStart=true", + "spring.cloud.nacos.discovery.secure=true", + "spring.cloud.nacos.discovery.accessKey=test-accessKey", + "spring.cloud.nacos.discovery.secretKey=test-secretKey" }, webEnvironment = RANDOM_PORT) +public class NacosAutoServiceRegistrationTests { + + @Autowired + private NacosRegistration registration; + + @Autowired + private NacosAutoServiceRegistration nacosAutoServiceRegistration; + + @LocalServerPort + private int port; + + @Autowired + private NacosDiscoveryProperties properties; + + @Autowired + private InetUtils inetUtils; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("NacosRegistration was not created", registration); + assertNotNull("NacosDiscoveryProperties was not created", properties); + assertNotNull("NacosAutoServiceRegistration was not created", + nacosAutoServiceRegistration); + + checkoutNacosDiscoveryServerAddr(); + checkoutNacosDiscoveryEndpoint(); + checkoutNacosDiscoveryNamespace(); + checkoutNacosDiscoveryLogName(); + checkoutNacosDiscoveryWeight(); + checkoutNacosDiscoveryClusterName(); + checkoutNacosDiscoveryCache(); + checkoutNacosDiscoverySecure(); + checkoutNacosDiscoveryAccessKey(); + checkoutNacosDiscoverySecrectKey(); + + checkoutNacosDiscoveryServiceName(); + checkoutNacosDiscoveryServiceIP(); + checkoutNacosDiscoveryServicePort(); + + checkAutoRegister(); + + checkoutEndpoint(); + + } + + private void checkAutoRegister() { + assertTrue("Nacos Auto Registration was not start", + nacosAutoServiceRegistration.isRunning()); + } + + private void checkoutNacosDiscoveryServerAddr() { + assertEquals("NacosDiscoveryProperties server address was wrong", + "127.0.0.1:8848", properties.getServerAddr()); + + } + + private void checkoutNacosDiscoveryEndpoint() { + assertEquals("NacosDiscoveryProperties endpoint was wrong", "test-endpoint", + properties.getEndpoint()); + + } + + private void checkoutNacosDiscoveryNamespace() { + assertEquals("NacosDiscoveryProperties namespace was wrong", "test-namespace", + properties.getNamespace()); + + } + + private void checkoutNacosDiscoveryLogName() { + assertEquals("NacosDiscoveryProperties logName was wrong", "test-logName", + properties.getLogName()); + } + + private void checkoutNacosDiscoveryWeight() { + assertEquals(2, properties.getWeight(), 0.00000001); + } + + private void checkoutNacosDiscoveryClusterName() { + assertEquals("NacosDiscoveryProperties cluster was wrong", "test-cluster", + properties.getClusterName()); + } + + private void checkoutNacosDiscoveryCache() { + assertEquals("NacosDiscoveryProperties naming load cache was wrong", "true", + properties.getNamingLoadCacheAtStart()); + } + + private void checkoutNacosDiscoverySecure() { + assertEquals("NacosDiscoveryProperties is secure was wrong", true, + properties.isSecure()); + assertEquals("NacosDiscoveryProperties is secure was wrong", "true", + properties.getMetadata().get("secure")); + } + + private void checkoutNacosDiscoveryAccessKey() { + assertEquals("NacosDiscoveryProperties is access key was wrong", "test-accessKey", + properties.getAccessKey()); + } + + private void checkoutNacosDiscoverySecrectKey() { + assertEquals("NacosDiscoveryProperties is secret key was wrong", "test-secretKey", + properties.getSecretKey()); + } + + private void checkoutNacosDiscoveryServiceName() { + assertEquals("NacosDiscoveryProperties service name was wrong", "myTestService1", + properties.getService()); + + } + + private void checkoutNacosDiscoveryServiceIP() { + assertEquals("NacosDiscoveryProperties service IP was wrong", + inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(), + registration.getHost()); + + } + + private void checkoutNacosDiscoveryServicePort() { + assertEquals("NacosDiscoveryProperties service Port was wrong", port, + registration.getPort()); + + } + + private void checkoutEndpoint() throws Exception { + NacosDiscoveryEndpoint nacosDiscoveryEndpoint = new NacosDiscoveryEndpoint( + properties); + Map map = nacosDiscoveryEndpoint.invoke(); + assertEquals(map.get("NacosDiscoveryProperties"), properties); + assertEquals(map.get("subscribe").toString(), + properties.namingServiceInstance().getSubscribeServices().toString()); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + NacosDiscoveryClientAutoConfiguration.class, + NacosDiscoveryAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java deleted file mode 100644 index c0f808d9..00000000 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.springframework.cloud.alibaba.nacos.ribbon; - -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import org.junit.Before; -import org.junit.Test; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration; -import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClientAutoConfiguration; -import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.commons.util.InetUtilsProperties; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.client.RestTemplate; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author xiaojing - */ -public class NacosRibbonClientConfigurationTests { - - private ConfigurableApplicationContext context; - - @Before - public void setUp() throws Exception { - this.context = new SpringApplicationBuilder(NacosRibbonTestConfiguration.class, - NacosDiscoveryAutoConfiguration.class, - NacosDiscoveryClientAutoConfiguration.class, - NacosRibbonClientConfiguration.class, RibbonNacosAutoConfiguration.class) - .web(false).run("--server.port=18080", - "--spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080", - "--spring.cloud.nacos.discovery.port=18080", - "--spring.cloud.nacos.discovery.service=myapp"); - } - - @Test - public void testProperties() { - - NacosServerList serverList = context.getBean(NacosServerList.class); - assertThat(serverList.getServiceId()).isEqualTo("myapp"); - } - - @Configuration - @AutoConfigureBefore(value = { NacosDiscoveryAutoConfiguration.class }) - static class NacosRibbonTestConfiguration { - - @Bean - @ConditionalOnMissingBean - AutoServiceRegistrationProperties autoServiceRegistrationProperties() { - return new AutoServiceRegistrationProperties(); - } - - @Bean - IClientConfig iClientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.setClientName("myapp"); - return config; - } - - @Bean - @LoadBalanced - RestTemplate restTemplate() { - return new RestTemplate(); - } - - @Bean - InetUtils inetUtils() { - return new InetUtils(new InetUtilsProperties()); - } - - } - -} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerListTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerListTests.java new file mode 100644 index 00000000..0dc13855 --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerListTests.java @@ -0,0 +1,175 @@ +/* + * 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 org.springframework.cloud.alibaba.nacos.ribbon; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; + +import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.api.naming.pojo.Instance; + +import com.netflix.client.config.IClientConfig; +import org.junit.Test; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.cloud.alibaba.nacos.test.NacosMockTest.serviceInstance; + +/** + * @author xiaojing + */ + +public class NacosServerListTests { + + @Test + @SuppressWarnings("unchecked") + public void testEmptyInstancesReturnsEmptyList() throws Exception { + NacosDiscoveryProperties nacosDiscoveryProperties = mock( + NacosDiscoveryProperties.class); + + NamingService namingService = mock(NamingService.class); + + when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); + when(namingService.selectInstances(anyString(), eq(true))).thenReturn(null); + + NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); + List servers = serverList.getInitialListOfServers(); + assertThat(servers).isEmpty(); + } + + @Test + @SuppressWarnings("unchecked") + public void testGetServers() throws Exception { + + ArrayList instances = new ArrayList<>(); + instances.add(serviceInstance("test-service", false, + Collections. emptyMap())); + + NacosDiscoveryProperties nacosDiscoveryProperties = mock( + NacosDiscoveryProperties.class); + + NamingService namingService = mock(NamingService.class); + + when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); + when(namingService.selectInstances(eq("test-service"), eq(true))) + .thenReturn(instances); + + IClientConfig clientConfig = mock(IClientConfig.class); + when(clientConfig.getClientName()).thenReturn("test-service"); + NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); + serverList.initWithNiwsConfig(clientConfig); + List servers = serverList.getInitialListOfServers(); + assertThat(servers).hasSize(1); + + servers = serverList.getUpdatedListOfServers(); + assertThat(servers).hasSize(1); + } + + @Test + @SuppressWarnings("unchecked") + public void testGetServersWithInstanceStatus() throws Exception { + ArrayList instances = new ArrayList<>(); + + HashMap map1 = new HashMap<>(); + map1.put("instanceNum", "1"); + HashMap map2 = new HashMap<>(); + map2.put("instanceNum", "2"); + instances.add(serviceInstance("test-service", false, map1)); + instances.add(serviceInstance("test-service", true, map2)); + + NacosDiscoveryProperties nacosDiscoveryProperties = mock( + NacosDiscoveryProperties.class); + + NamingService namingService = mock(NamingService.class); + + when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); + + List returnInstances = new LinkedList<>(); + + for (Instance instance : instances) { + if (instance.isHealthy()) { + returnInstances.add(instance); + } + } + + when(namingService.selectInstances(eq("test-service"), eq(true))) + .thenReturn(returnInstances); + + IClientConfig clientConfig = mock(IClientConfig.class); + when(clientConfig.getClientName()).thenReturn("test-service"); + NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); + serverList.initWithNiwsConfig(clientConfig); + List servers = serverList.getInitialListOfServers(); + assertThat(servers).hasSize(1); + + NacosServer nacosServer = servers.get(0); + + assertThat(nacosServer.getMetaInfo().getInstanceId()) + .isEqualTo(instances.get(1).getInstanceId()); + assertThat(nacosServer.getMetadata()).isEqualTo(map2); + assertThat(nacosServer.getInstance().isHealthy()).isEqualTo(true); + assertThat(nacosServer.getInstance().getServiceName()).isEqualTo("test-service"); + assertThat(nacosServer.getInstance().getMetadata().get("instanceNum")) + .isEqualTo("2"); + + } + + @Test + public void testUpdateServers() throws Exception { + ArrayList instances = new ArrayList<>(); + + HashMap map = new HashMap<>(); + map.put("instanceNum", "1"); + instances.add(serviceInstance("test-service", true, map)); + + NacosDiscoveryProperties nacosDiscoveryProperties = mock( + NacosDiscoveryProperties.class); + + NamingService namingService = mock(NamingService.class); + + when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); + + List returnInstances = new LinkedList<>(); + for (Instance instance : instances) { + if (instance.isHealthy()) { + returnInstances.add(instance); + } + } + + when(namingService.selectInstances(eq("test-service"), eq(true))) + .thenReturn(returnInstances); + + IClientConfig clientConfig = mock(IClientConfig.class); + when(clientConfig.getClientName()).thenReturn("test-service"); + NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); + serverList.initWithNiwsConfig(clientConfig); + + List servers = serverList.getUpdatedListOfServers(); + assertThat(servers).hasSize(1); + + assertThat(servers.get(0).getInstance().isHealthy()).isEqualTo(true); + assertThat(servers.get(0).getInstance().getMetadata().get("instanceNum")) + .isEqualTo("1"); + } +} \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/test/CommonTestConfig.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/test/CommonTestConfig.java new file mode 100644 index 00000000..3f9d2860 --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/test/CommonTestConfig.java @@ -0,0 +1,36 @@ +/* + * 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 org.springframework.cloud.alibaba.nacos.test; + +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +/** + * @author xiaojing + */ + +@Configuration +public class CommonTestConfig { + + @Bean + @LoadBalanced + RestTemplate loadBalancedRestTemplate() { + return new RestTemplate(); + } +} \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/test/NacosMockTest.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/test/NacosMockTest.java new file mode 100644 index 00000000..33efb8eb --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/test/NacosMockTest.java @@ -0,0 +1,49 @@ +/* + * 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 org.springframework.cloud.alibaba.nacos.test; + +import java.util.Map; +import java.util.UUID; + +import com.alibaba.nacos.api.naming.pojo.Instance; + +/** + * @author xiaojing + */ +public class NacosMockTest { + + public static Instance serviceInstance(String serviceName, boolean isHealthy, + Map metadata) { + Instance instance = new Instance(); + instance.setInstanceId(UUID.randomUUID().toString()); + instance.setServiceName(serviceName); + instance.setHealthy(isHealthy); + instance.setMetadata(metadata); + return instance; + } + + public static Instance serviceInstance(String serviceName, boolean isHealthy, + String host, int port, Map metadata) { + Instance instance = new Instance(); + instance.setIp(host); + instance.setPort(port); + instance.setServiceName(serviceName); + instance.setHealthy(isHealthy); + instance.setMetadata(metadata); + return instance; + } +} From 93defa99e2c3caf41969abd880408bf77cea0997 Mon Sep 17 00:00:00 2001 From: fangjian0423 Date: Thu, 21 Feb 2019 10:35:30 +0800 Subject: [PATCH 07/18] upgrade sentinel version to 1.4.2 --- spring-cloud-alibaba-dependencies/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-cloud-alibaba-dependencies/pom.xml b/spring-cloud-alibaba-dependencies/pom.xml index 1ab8d95d..228fa116 100644 --- a/spring-cloud-alibaba-dependencies/pom.xml +++ b/spring-cloud-alibaba-dependencies/pom.xml @@ -16,7 +16,7 @@ Spring Cloud Alibaba Dependencies - 1.4.1 + 1.4.2 3.1.0 0.8.1 0.1.3 From ac382c9e3f9381d134e60546ac759e9218d9985d Mon Sep 17 00:00:00 2001 From: flystar32 Date: Thu, 21 Feb 2019 11:38:22 +0800 Subject: [PATCH 08/18] format code and change logger to log --- spring-cloud-alicloud-acm/pom.xml | 2 + .../acm/bootstrap/AcmPropertySource.java | 38 +++--- .../bootstrap/AcmPropertySourceBuilder.java | 118 +++++++++--------- .../acm/endpoint/AcmHealthIndicator.java | 61 ++++----- .../acm/refresh/AcmContextRefresher.java | 5 +- 5 files changed, 115 insertions(+), 109 deletions(-) diff --git a/spring-cloud-alicloud-acm/pom.xml b/spring-cloud-alicloud-acm/pom.xml index 6b57a4f7..49012835 100644 --- a/spring-cloud-alicloud-acm/pom.xml +++ b/spring-cloud-alicloud-acm/pom.xml @@ -11,6 +11,7 @@ spring-cloud-alicloud-acm + Spring Cloud Alibaba Cloud ACM @@ -43,6 +44,7 @@ org.springframework.boot spring-boot-starter-actuator + provided true diff --git a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySource.java b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySource.java index 3ebae277..fb7b58ad 100644 --- a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySource.java +++ b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySource.java @@ -27,29 +27,29 @@ import java.util.Map; */ public class AcmPropertySource extends MapPropertySource { - private final String dataId; + private final String dataId; - private final Date timestamp; + private final Date timestamp; - private final boolean groupLevel; + private final boolean groupLevel; - AcmPropertySource(String dataId, Map source, Date timestamp, - boolean groupLevel) { - super(dataId, source); - this.dataId = dataId; - this.timestamp = timestamp; - this.groupLevel = groupLevel; - } + AcmPropertySource(String dataId, Map source, Date timestamp, + boolean groupLevel) { + super(dataId, source); + this.dataId = dataId; + this.timestamp = timestamp; + this.groupLevel = groupLevel; + } - public String getDataId() { - return dataId; - } + public String getDataId() { + return dataId; + } - public Date getTimestamp() { - return timestamp; - } + public Date getTimestamp() { + return timestamp; + } - public boolean isGroupLevel() { - return groupLevel; - } + public boolean isGroupLevel() { + return groupLevel; + } } diff --git a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySourceBuilder.java b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySourceBuilder.java index 2bf9cbba..7afabd83 100644 --- a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySourceBuilder.java +++ b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySourceBuilder.java @@ -33,64 +33,68 @@ import java.util.*; */ class AcmPropertySourceBuilder { - private Logger logger = LoggerFactory.getLogger(AcmPropertySourceBuilder.class); + private Logger log = LoggerFactory.getLogger(AcmPropertySourceBuilder.class); - /** - * 传入 ACM 的 DataId 和 groupID,获取到解析后的 AcmProperty 对象 - * - * @param dataId - * @param diamondGroup - * @param groupLevel - * @return - */ - AcmPropertySource build(String dataId, String diamondGroup, boolean groupLevel) { - Properties properties = loadDiamondData(dataId, diamondGroup); - if (properties == null) { - return null; - } - return new AcmPropertySource(dataId, toMap(properties), new Date(), groupLevel); - } + /** + * 传入 ACM 的 DataId 和 groupID,获取到解析后的 AcmProperty 对象 + * + * @param dataId + * @param diamondGroup + * @param groupLevel + * @return + */ + AcmPropertySource build(String dataId, String diamondGroup, boolean groupLevel) { + Properties properties = loadDiamondData(dataId, diamondGroup); + if (properties == null) { + return null; + } + return new AcmPropertySource(dataId, toMap(properties), new Date(), groupLevel); + } - private Properties loadDiamondData(String dataId, String diamondGroup) { - try { - String data = ConfigService.getConfig(dataId, diamondGroup, 3000L); - if (StringUtils.isEmpty(data)) { - return null; - } - if (dataId.endsWith(".properties")) { - Properties properties = new Properties(); - logger.info(String.format("Loading acm data, dataId: '%s', group: '%s'", - dataId, diamondGroup)); - properties.load(new StringReader(data)); - return properties; - } else if (dataId.endsWith(".yaml") || dataId.endsWith(".yml")) { - YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); - yamlFactory.setResources(new ByteArrayResource(data.getBytes())); - return yamlFactory.getObject(); - } - } catch (Exception e) { - if (e instanceof ConfigException) { - logger.error("DIAMOND-100500:" + dataId + ", " + e.toString(), e); - } else { - logger.error("DIAMOND-100500:" + dataId, e); - } - } - return null; - } + private Properties loadDiamondData(String dataId, String diamondGroup) { + try { + String data = ConfigService.getConfig(dataId, diamondGroup, 3000L); + if (StringUtils.isEmpty(data)) { + return null; + } + if (dataId.endsWith(".properties")) { + Properties properties = new Properties(); + log.info(String.format("Loading acm data, dataId: '%s', group: '%s'", + dataId, diamondGroup)); + properties.load(new StringReader(data)); + return properties; + } + else if (dataId.endsWith(".yaml") || dataId.endsWith(".yml")) { + YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); + yamlFactory.setResources(new ByteArrayResource(data.getBytes())); + return yamlFactory.getObject(); + } + } + catch (Exception e) { + if (e instanceof ConfigException) { + log.error("DIAMOND-100500:" + dataId + ", " + e.toString(), e); + } + else { + log.error("DIAMOND-100500:" + dataId, e); + } + } + return null; + } - @SuppressWarnings("unchecked") - private Map toMap(Properties properties) { - Map result = new HashMap<>(); - Enumeration keys = (Enumeration)properties.propertyNames(); - while (keys.hasMoreElements()) { - String key = keys.nextElement(); - Object value = properties.getProperty(key); - if (value != null) { - result.put(key, ((String)value).trim()); - } else { - result.put(key, null); - } - } - return result; - } + @SuppressWarnings("unchecked") + private Map toMap(Properties properties) { + Map result = new HashMap<>(); + Enumeration keys = (Enumeration) properties.propertyNames(); + while (keys.hasMoreElements()) { + String key = keys.nextElement(); + Object value = properties.getProperty(key); + if (value != null) { + result.put(key, ((String) value).trim()); + } + else { + result.put(key, null); + } + } + return result; + } } diff --git a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/endpoint/AcmHealthIndicator.java b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/endpoint/AcmHealthIndicator.java index 27569ec1..c6052ae1 100644 --- a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/endpoint/AcmHealthIndicator.java +++ b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/endpoint/AcmHealthIndicator.java @@ -33,39 +33,40 @@ import java.util.List; */ public class AcmHealthIndicator extends AbstractHealthIndicator { - private final AcmProperties acmProperties; + private final AcmProperties acmProperties; - private final AcmPropertySourceRepository acmPropertySourceRepository; + private final AcmPropertySourceRepository acmPropertySourceRepository; - private final List dataIds; + private final List dataIds; - public AcmHealthIndicator(AcmProperties acmProperties, - AcmPropertySourceRepository acmPropertySourceRepository) { - this.acmProperties = acmProperties; - this.acmPropertySourceRepository = acmPropertySourceRepository; + public AcmHealthIndicator(AcmProperties acmProperties, + AcmPropertySourceRepository acmPropertySourceRepository) { + this.acmProperties = acmProperties; + this.acmPropertySourceRepository = acmPropertySourceRepository; - this.dataIds = new ArrayList<>(); - for (AcmPropertySource acmPropertySource : this.acmPropertySourceRepository - .getAll()) { - this.dataIds.add(acmPropertySource.getDataId()); - } - } + this.dataIds = new ArrayList<>(); + for (AcmPropertySource acmPropertySource : this.acmPropertySourceRepository + .getAll()) { + this.dataIds.add(acmPropertySource.getDataId()); + } + } - @Override - protected void doHealthCheck(Health.Builder builder) throws Exception { - for (String dataId : dataIds) { - try { - String config = ConfigService.getConfig(dataId, acmProperties.getGroup(), - acmProperties.getTimeout()); - if (StringUtils.isEmpty(config)) { - builder.down().withDetail(String.format("dataId: '%s', group: '%s'", - dataId, acmProperties.getGroup()), "config is empty"); - } - } catch (Exception e) { - builder.down().withDetail(String.format("dataId: '%s', group: '%s'", - dataId, acmProperties.getGroup()), e.getMessage()); - } - } - builder.up().withDetail("dataIds", dataIds); - } + @Override + protected void doHealthCheck(Health.Builder builder) throws Exception { + for (String dataId : dataIds) { + try { + String config = ConfigService.getConfig(dataId, acmProperties.getGroup(), + acmProperties.getTimeout()); + if (StringUtils.isEmpty(config)) { + builder.down().withDetail(String.format("dataId: '%s', group: '%s'", + dataId, acmProperties.getGroup()), "config is empty"); + } + } + catch (Exception e) { + builder.down().withDetail(String.format("dataId: '%s', group: '%s'", + dataId, acmProperties.getGroup()), e.getMessage()); + } + } + builder.up().withDetail("dataIds", dataIds); + } } diff --git a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/refresh/AcmContextRefresher.java b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/refresh/AcmContextRefresher.java index 58457c07..18308b59 100644 --- a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/refresh/AcmContextRefresher.java +++ b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/refresh/AcmContextRefresher.java @@ -28,7 +28,6 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.cloud.alicloud.acm.AcmPropertySourceRepository; -import org.springframework.cloud.alicloud.acm.bootstrap.AcmPropertySource; import org.springframework.cloud.alicloud.context.acm.AcmIntegrationProperties; import org.springframework.cloud.context.refresh.ContextRefresher; import org.springframework.cloud.endpoint.event.RefreshEvent; @@ -50,7 +49,7 @@ import com.alibaba.edas.acm.listener.ConfigChangeListener; public class AcmContextRefresher implements ApplicationListener, ApplicationContextAware { - private Logger logger = LoggerFactory.getLogger(AcmContextRefresher.class); + private Logger log = LoggerFactory.getLogger(AcmContextRefresher.class); private final ContextRefresher contextRefresher; @@ -103,7 +102,7 @@ public class AcmContextRefresher } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { - logger.warn("unable to get md5 for dataId: " + dataId, e); + log.warn("unable to get md5 for dataId: " + dataId, e); } } refreshHistory.add(dataId, md5); From ee4d67a6facc700eb7509e1f59f0616201064f2c Mon Sep 17 00:00:00 2001 From: flystar32 Date: Thu, 21 Feb 2019 14:35:44 +0800 Subject: [PATCH 09/18] format code and change apache log to slf4j --- .../cloud/alicloud/ans/endpoint/AnsEndpoint.java | 6 +++--- .../cloud/alicloud/ans/migrate/MigrateEndpoint.java | 6 +++--- .../alicloud/ans/migrate/MigrateOnConditionClass.java | 7 ++++--- .../ans/migrate/MigrateOnConditionMissingClass.java | 8 ++++---- .../cloud/alicloud/ans/migrate/MigrateProxyManager.java | 6 +++--- .../alicloud/ans/migrate/MigrateRefreshEventListener.java | 7 ++++--- .../ans/migrate/MigrateRibbonBeanPostProcessor.java | 6 +++--- .../alicloud/ans/migrate/MigrateServiceRegistry.java | 7 ++++--- .../alicloud/ans/migrate/ServerListInvocationHandler.java | 7 ++++--- .../alicloud/ans/registry/AnsAutoServiceRegistration.java | 7 ++++--- .../cloud/alicloud/ans/registry/AnsServiceRegistry.java | 6 +++--- 11 files changed, 39 insertions(+), 34 deletions(-) diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/endpoint/AnsEndpoint.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/endpoint/AnsEndpoint.java index 7a35ef6f..056bd878 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/endpoint/AnsEndpoint.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/endpoint/AnsEndpoint.java @@ -18,8 +18,8 @@ package org.springframework.cloud.alicloud.ans.endpoint; import com.alibaba.ans.core.NamingService; import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.endpoint.AbstractEndpoint; import org.springframework.cloud.alicloud.context.ans.AnsProperties; @@ -34,7 +34,7 @@ import java.util.Set; */ public class AnsEndpoint extends AbstractEndpoint> { - private static final Log log = LogFactory.getLog(AnsEndpoint.class); + private static final Logger log = LoggerFactory.getLogger(AnsEndpoint.class); private AnsProperties ansProperties; diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpoint.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpoint.java index 53d559a1..e8609648 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpoint.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpoint.java @@ -1,7 +1,7 @@ package org.springframework.cloud.alicloud.ans.migrate; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.endpoint.AbstractEndpoint; import java.util.Map; @@ -13,7 +13,7 @@ import java.util.concurrent.ConcurrentMap; public class MigrateEndpoint extends AbstractEndpoint>> { - private static final Log log = LogFactory.getLog(MigrateEndpoint.class); + private static final Logger log = LoggerFactory.getLogger(MigrateEndpoint.class); public MigrateEndpoint() { super("migrate"); diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionClass.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionClass.java index 391173d2..9e99c9f8 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionClass.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionClass.java @@ -1,7 +1,7 @@ package org.springframework.cloud.alicloud.ans.migrate; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; @@ -10,7 +10,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata; */ public class MigrateOnConditionClass extends MigrateOnCondition { - protected static final Log log = LogFactory.getLog(MigrateOnConditionClass.class); + private static final Logger log = LoggerFactory + .getLogger(MigrateOnConditionClass.class); @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionMissingClass.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionMissingClass.java index da19cb3a..b5653bb7 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionMissingClass.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionMissingClass.java @@ -1,7 +1,7 @@ package org.springframework.cloud.alicloud.ans.migrate; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; @@ -9,8 +9,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata; * @author pbting */ public class MigrateOnConditionMissingClass extends MigrateOnConditionClass { - protected static final Log log = LogFactory - .getLog(MigrateOnConditionMissingClass.class); + private static final Logger log = LoggerFactory + .getLogger(MigrateOnConditionMissingClass.class); @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateProxyManager.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateProxyManager.java index 06f673fb..8b62c22e 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateProxyManager.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateProxyManager.java @@ -7,8 +7,8 @@ import com.netflix.loadbalancer.ServerList; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.aop.framework.ProxyFactory; import java.util.*; @@ -20,7 +20,7 @@ import java.util.concurrent.atomic.AtomicBoolean; */ final class MigrateProxyManager { - private final static Log log = LogFactory.getLog(MigrateProxyManager.class); + private static final Logger log = LoggerFactory.getLogger(MigrateProxyManager.class); private final static AtomicBoolean IS_PROXY = new AtomicBoolean(true); diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRefreshEventListener.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRefreshEventListener.java index f5144972..db941c84 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRefreshEventListener.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRefreshEventListener.java @@ -7,8 +7,8 @@ import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.cloud.context.named.NamedContextFactory; import org.springframework.cloud.endpoint.event.RefreshEvent; import org.springframework.context.ApplicationListener; @@ -22,7 +22,8 @@ import com.netflix.loadbalancer.ILoadBalancer; */ @Component public class MigrateRefreshEventListener implements ApplicationListener { - private final static Log log = LogFactory.getLog(MigrateRefreshEventListener.class); + private static final Logger log = LoggerFactory + .getLogger(MigrateRefreshEventListener.class); private final static int CHECK_INTERVAL = 1; diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRibbonBeanPostProcessor.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRibbonBeanPostProcessor.java index df246f18..74fa658a 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRibbonBeanPostProcessor.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRibbonBeanPostProcessor.java @@ -1,7 +1,7 @@ package org.springframework.cloud.alicloud.ans.migrate; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.config.BeanPostProcessor; @@ -16,7 +16,7 @@ import com.netflix.loadbalancer.ServerList; public class MigrateRibbonBeanPostProcessor implements BeanPostProcessor, BeanClassLoaderAware { - protected static final Log log = LogFactory.getLog(MigrateOnCondition.class); + private static final Logger log = LoggerFactory.getLogger(MigrateOnCondition.class); private ClassLoader classLoader; private IClientConfig clientConfig; diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateServiceRegistry.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateServiceRegistry.java index b6c709ca..8220d377 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateServiceRegistry.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateServiceRegistry.java @@ -2,8 +2,8 @@ package org.springframework.cloud.alicloud.ans.migrate; import java.util.concurrent.atomic.AtomicBoolean; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.cloud.alicloud.ans.registry.AnsRegistration; import org.springframework.cloud.alicloud.ans.registry.AnsServiceRegistry; @@ -19,7 +19,8 @@ import org.springframework.stereotype.Component; @Component public class MigrateServiceRegistry { - private static final Log log = LogFactory.getLog(MigrateServiceRegistry.class); + private static final Logger log = LoggerFactory + .getLogger(MigrateServiceRegistry.class); private AtomicBoolean running = new AtomicBoolean(false); diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerListInvocationHandler.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerListInvocationHandler.java index 5d6e108f..85ca5c3c 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerListInvocationHandler.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerListInvocationHandler.java @@ -4,8 +4,8 @@ import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.Server; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.cloud.alicloud.ans.ribbon.AnsServer; import org.springframework.cloud.alicloud.ans.ribbon.AnsServerList; @@ -21,7 +21,8 @@ import java.util.concurrent.atomic.AtomicLong; */ class ServerListInvocationHandler implements MethodInterceptor { - private final static Log log = LogFactory.getLog(ServerListInvocationHandler.class); + private static final Logger log = LoggerFactory + .getLogger(ServerListInvocationHandler.class); private final static ConcurrentMap SERVER_LIST_CONCURRENT_MAP = new ConcurrentHashMap<>(); diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java index 5ea2258c..aab75b96 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java @@ -16,8 +16,8 @@ package org.springframework.cloud.alicloud.ans.registry; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent; import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; @@ -35,7 +35,8 @@ import org.springframework.util.StringUtils; public class AnsAutoServiceRegistration extends AbstractAutoServiceRegistration { - private static final Log log = LogFactory.getLog(AnsAutoServiceRegistration.class); + private static final Logger log = LoggerFactory + .getLogger(AnsAutoServiceRegistration.class); private AnsRegistration registration; diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsServiceRegistry.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsServiceRegistry.java index 1ff187a3..924d2976 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsServiceRegistry.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsServiceRegistry.java @@ -19,8 +19,8 @@ package org.springframework.cloud.alicloud.ans.registry; import com.alibaba.ans.core.NamingService; import com.alibaba.ans.shaded.com.taobao.vipserver.client.ipms.NodeReactor; import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.cloud.client.serviceregistry.ServiceRegistry; import java.util.ArrayList; @@ -32,7 +32,7 @@ import java.util.Map; */ public class AnsServiceRegistry implements ServiceRegistry { - private static Log log = LogFactory.getLog(AnsServiceRegistry.class); + private static final Logger log = LoggerFactory.getLogger(AnsServiceRegistry.class); private static final String SEPARATOR = ","; From d81a8d9490969ccf78294e289e04d155f2465d94 Mon Sep 17 00:00:00 2001 From: flystar32 Date: Thu, 21 Feb 2019 15:47:02 +0800 Subject: [PATCH 10/18] fixed bug, can't not register --- .../cloud/alicloud/ans/AnsAutoConfiguration.java | 7 ++++--- .../alicloud/ans/registry/AnsAutoServiceRegistration.java | 4 ++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java index 144520fc..4a39ded0 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java @@ -16,6 +16,7 @@ package org.springframework.cloud.alicloud.ans; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -26,7 +27,7 @@ import org.springframework.cloud.alicloud.ans.registry.AnsAutoServiceRegistratio import org.springframework.cloud.alicloud.ans.registry.AnsRegistration; import org.springframework.cloud.alicloud.ans.registry.AnsServiceRegistry; import org.springframework.cloud.alicloud.context.ans.AnsProperties; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @@ -42,8 +43,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnClass(name = "org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent") @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) @ConditionalOnAnsEnabled -@AutoConfigureBefore({ AutoServiceRegistrationAutoConfiguration.class, - AnsDiscoveryClientAutoConfiguration.class }) +@AutoConfigureBefore(AnsDiscoveryClientAutoConfiguration.class) +@AutoConfigureAfter(AutoServiceRegistrationConfiguration.class) public class AnsAutoConfiguration { @Bean diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java index aab75b96..084f85a8 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java @@ -116,11 +116,11 @@ public class AnsAutoServiceRegistration @Override protected int getConfiguredPort() { - return registration.getPort(); + return this.getPort().get(); } @Override protected void setConfiguredPort(int port) { - this.registration.setPort(port); + this.getPort().set(port); } } From b9a08cf1e420e2d2652ad1d695846e82a20d06a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=97=E5=B0=91?= <314226532@qq.com> Date: Fri, 22 Feb 2019 20:49:14 +0800 Subject: [PATCH 11/18] =?UTF-8?q?1=E3=80=81change=20the=20nacos=20system?= =?UTF-8?q?=20properties=20named=202=E3=80=81upgrade=20nacos=20client=20de?= =?UTF-8?q?pendency=20with=200.8.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spring-cloud-alibaba-dependencies/pom.xml | 2 +- .../context/nacos/NacosDiscoveryParameterInitListener.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-cloud-alibaba-dependencies/pom.xml b/spring-cloud-alibaba-dependencies/pom.xml index 48b69819..21b18375 100644 --- a/spring-cloud-alibaba-dependencies/pom.xml +++ b/spring-cloud-alibaba-dependencies/pom.xml @@ -18,7 +18,7 @@ 1.4.0 3.1.0 - 0.8.1 + 0.8.2 0.1.3 1.0.8 1.0.1 diff --git a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListener.java b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListener.java index 3dbc548f..b0760fcf 100644 --- a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListener.java +++ b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListener.java @@ -65,7 +65,7 @@ public class NacosDiscoveryParameterInitListener edasChangeOrderConfiguration.getDauthSecretKey()); // step 2: set these properties for nacos client - properties.setProperty("webContext", "/vipserver"); - properties.setProperty("serverPort", "80"); + properties.setProperty("nacos.naming.web.context", "/vipserver"); + properties.setProperty("nacos.naming.exposed.port", "80"); } } \ No newline at end of file From 34bcd8b242621d3a14b3e30313daa168eb2ef816 Mon Sep 17 00:00:00 2001 From: xiaolongzuo <150349407@qq.com> Date: Thu, 21 Feb 2019 15:09:20 +0800 Subject: [PATCH 12/18] Add statistics for nacos discovery and test case # Conflicts: # spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java --- .../NacosDiscoveryParameterInitListener.java | 9 ++++---- .../statistics/StatisticsTaskStarter.java | 10 ++++++-- .../NacosDiscoveryAutoConfiguration.java | 23 +++++++++++++++++++ ...osDiscoveryParameterInitListenerTests.java | 21 +++++++++-------- 4 files changed, 47 insertions(+), 16 deletions(-) create mode 100644 spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java diff --git a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListener.java b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListener.java index 3dbc548f..6fd7a6f2 100644 --- a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListener.java +++ b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListener.java @@ -15,14 +15,15 @@ */ package org.springframework.cloud.alicloud.context.nacos; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfiguration; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; +import java.util.Properties; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; import org.springframework.cloud.alicloud.context.listener.AbstractOnceApplicationListener; -import java.util.Properties; +import com.alibaba.cloud.context.edas.EdasChangeOrderConfiguration; +import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; /** * @author pbting @@ -52,7 +53,7 @@ public class NacosDiscoveryParameterInitListener } // initialize nacos configuration Properties properties = System.getProperties(); - + properties.setProperty("spring.cloud.nacos.discovery.server-mode", "EDAS"); // step 1: set some properties for spring cloud alibaba nacos discovery properties.setProperty("spring.cloud.nacos.discovery.server-addr", ""); properties.setProperty("spring.cloud.nacos.discovery.endpoint", diff --git a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/statistics/StatisticsTaskStarter.java b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/statistics/StatisticsTaskStarter.java index 709315d8..e820d4a9 100644 --- a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/statistics/StatisticsTaskStarter.java +++ b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/statistics/StatisticsTaskStarter.java @@ -48,7 +48,9 @@ public class StatisticsTaskStarter implements InitializingBean { private static final String NACOS_CONFIG_SERVER_MODE_KEY = "spring.cloud.nacos.config.server-mode"; - private static final String NACOS_CONFIG_SERVER_MODE_VALUE = "EDAS"; + private static final String NACOS_DISCOVERY_SERVER_MODE_KEY = "spring.cloud.nacos.discovery.server-mode"; + + private static final String NACOS_SERVER_MODE_VALUE = "EDAS"; @Autowired(required = false) private AliCloudEdasSdk aliCloudEdasSdk; @@ -106,10 +108,14 @@ public class StatisticsTaskStarter implements InitializingBean { if (acmContextBootstrapConfiguration != null && acmEnableEdas) { components.add("SC-ACM"); } - if (NACOS_CONFIG_SERVER_MODE_VALUE + if (NACOS_SERVER_MODE_VALUE .equals(System.getProperty(NACOS_CONFIG_SERVER_MODE_KEY))) { components.add("SC-NACOS-CONFIG"); } + if (NACOS_SERVER_MODE_VALUE + .equals(System.getProperty(NACOS_DISCOVERY_SERVER_MODE_KEY))) { + components.add("SC-NACOS-DISCOVERY"); + } return components; } diff --git a/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java b/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java new file mode 100644 index 00000000..74ac28bc --- /dev/null +++ b/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java @@ -0,0 +1,23 @@ +/* + * 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 org.springframework.cloud.alibaba.nacos; + +/** + * @author xiaolongzuo + */ +public class NacosDiscoveryAutoConfiguration { +} diff --git a/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java b/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java index c9c6e8ab..f59b44de 100644 --- a/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java +++ b/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java @@ -16,15 +16,16 @@ package org.springframework.cloud.alicloud.context.nacos; -import com.alibaba.cloud.context.ans.AliCloudAnsInitializer; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + import org.junit.BeforeClass; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.springframework.cloud.alicloud.context.BaseAliCloudSpringApplication; import org.springframework.cloud.alicloud.utils.ChangeOrderUtils; -import static org.assertj.core.api.Assertions.assertThat; +import com.alibaba.cloud.context.ans.AliCloudAnsInitializer; +import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; /** * @author xiaolongzuo @@ -37,21 +38,21 @@ public class NacosDiscoveryParameterInitListenerTests @BeforeClass public static void setUp() { ChangeOrderUtils.mockChangeOrder(); - System.getProperties().setProperty("webContext", "/vipserver"); - System.getProperties().setProperty("serverPort", "80"); } @Test public void testNacosParameterInitListener() { - assertThat(System.getProperty("spring.cloud.nacos.config.server-addr")) + assertThat(System.getProperty("spring.cloud.nacos.discovery.server-mode")) + .isEqualTo("EDAS"); + assertThat(System.getProperty("spring.cloud.nacos.discovery.server-addr")) .isEqualTo(""); - assertThat(System.getProperty("spring.cloud.nacos.config.endpoint")) + assertThat(System.getProperty("spring.cloud.nacos.discovery.endpoint")) .isEqualTo("testDomain"); - assertThat(System.getProperty("spring.cloud.nacos.config.namespace")) + assertThat(System.getProperty("spring.cloud.nacos.discovery.namespace")) .isEqualTo("testTenantId"); - assertThat(System.getProperty("spring.cloud.nacos.config.access-key")) + assertThat(System.getProperty("spring.cloud.nacos.discovery.access-key")) .isEqualTo("testAK"); - assertThat(System.getProperty("spring.cloud.nacos.config.secret-key")) + assertThat(System.getProperty("spring.cloud.nacos.discovery.secret-key")) .isEqualTo("testSK"); assertThat(System.getProperties().getProperty("webContext")) .isEqualTo("/vipserver"); From 6ff11740bfe94443732ac0b12dce16644d6bb8af Mon Sep 17 00:00:00 2001 From: xiaolongzuo <150349407@qq.com> Date: Mon, 25 Feb 2019 16:42:45 +0800 Subject: [PATCH 13/18] Add statistics for nacos discovery and test case # Conflicts: # spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java --- .../context/nacos/NacosDiscoveryParameterInitListenerTests.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java b/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java index f59b44de..d06be81b 100644 --- a/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java +++ b/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java @@ -16,7 +16,7 @@ package org.springframework.cloud.alicloud.context.nacos; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.BeforeClass; import org.junit.Test; From 25f16d35289c1f8feb705688bcb9cb545dd33cff Mon Sep 17 00:00:00 2001 From: xiaolongzuo <150349407@qq.com> Date: Mon, 25 Feb 2019 14:35:39 +0800 Subject: [PATCH 14/18] Polish test cases for schedulerx --- .../cloud/examples/HelloController.java | 35 +++++++++++++++++ .../alibaba/cloud/examples/SimpleTask.java | 20 +++++----- .../cloud/examples/TestController.java | 39 +++++++++++++++++++ .../alibaba/cloud/examples/TestService.java | 6 +-- 4 files changed, 87 insertions(+), 13 deletions(-) create mode 100644 spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/HelloController.java create mode 100644 spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestController.java diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/HelloController.java b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/HelloController.java new file mode 100644 index 00000000..c11cbf98 --- /dev/null +++ b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/HelloController.java @@ -0,0 +1,35 @@ +/* + * 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 org.springframework.cloud.alibaba.cloud.examples; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author xiaolongzuo + */ +@RestController +public class HelloController { + + @RequestMapping("/") + @ResponseBody + public String hello() { + return "OK"; + } + +} diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/SimpleTask.java b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/SimpleTask.java index 09055da1..17ced464 100644 --- a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/SimpleTask.java +++ b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/SimpleTask.java @@ -16,25 +16,25 @@ package org.springframework.cloud.alibaba.cloud.examples; +import org.springframework.beans.factory.annotation.Autowired; + import com.alibaba.edas.schedulerx.ProcessResult; import com.alibaba.edas.schedulerx.ScxSimpleJobContext; import com.alibaba.edas.schedulerx.ScxSimpleJobProcessor; -import org.springframework.beans.factory.annotation.Autowired; /** * @author xiaolongzuo */ public class SimpleTask implements ScxSimpleJobProcessor { - @Autowired - private TestService testService; + @Autowired + private TestService testService; - @Override - public ProcessResult process(ScxSimpleJobContext context) { - System.out.println("-----------Hello world---------------"); - testService.test(); - ProcessResult processResult = new ProcessResult(true); - return processResult; - } + @Override + public ProcessResult process(ScxSimpleJobContext context) { + testService.test(); + ProcessResult processResult = new ProcessResult(true); + return processResult; + } } diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestController.java b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestController.java new file mode 100644 index 00000000..b237b279 --- /dev/null +++ b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestController.java @@ -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 org.springframework.cloud.alibaba.cloud.examples; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author xiaolongzuo + */ +@RestController +public class TestController { + + static AtomicInteger atomicInteger = new AtomicInteger(0); + + @RequestMapping("/test") + @ResponseBody + public String test() { + return String.valueOf(atomicInteger.get()); + } + +} diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestService.java b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestService.java index 1786d197..3352c05a 100644 --- a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestService.java +++ b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestService.java @@ -24,7 +24,7 @@ import org.springframework.stereotype.Service; @Service public class TestService { - public void test() { - System.out.println("---------IOC Success--------"); - } + public void test() { + TestController.atomicInteger.incrementAndGet(); + } } From 6ae1df0363aa0edeec67567e418d85bf0219de31 Mon Sep 17 00:00:00 2001 From: xiaolongzuo <150349407@qq.com> Date: Mon, 25 Feb 2019 15:00:11 +0800 Subject: [PATCH 15/18] Polish --- .../nacos/NacosDiscoveryParameterInitListenerTests.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java b/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java index d06be81b..0efec3d1 100644 --- a/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java +++ b/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java @@ -54,8 +54,9 @@ public class NacosDiscoveryParameterInitListenerTests .isEqualTo("testAK"); assertThat(System.getProperty("spring.cloud.nacos.discovery.secret-key")) .isEqualTo("testSK"); - assertThat(System.getProperties().getProperty("webContext")) + assertThat(System.getProperties().getProperty("nacos.naming.web.context")) .isEqualTo("/vipserver"); - assertThat(System.getProperties().getProperty("serverPort")).isEqualTo("80"); + assertThat(System.getProperties().getProperty("nacos.naming.exposed.port")) + .isEqualTo("80"); } } \ No newline at end of file From ac27dd9b30f2bede3214240ce8220744a21cbbc3 Mon Sep 17 00:00:00 2001 From: xiaolongzuo <150349407@qq.com> Date: Tue, 26 Feb 2019 10:49:42 +0800 Subject: [PATCH 16/18] Add scx and oss java doc. --- .../alicloud/context/oss/OssProperties.java | 20 +++++++++++++++++++ .../alicloud/context/scx/ScxProperties.java | 10 ++++++++++ 2 files changed, 30 insertions(+) diff --git a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/oss/OssProperties.java b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/oss/OssProperties.java index 59f64cc3..4897bf5f 100644 --- a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/oss/OssProperties.java +++ b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/oss/OssProperties.java @@ -31,13 +31,33 @@ import com.aliyun.oss.ClientBuilderConfiguration; @ConfigurationProperties("spring.cloud.alicloud.oss") public class OssProperties { + /** + * Authorization Mode, please see oss + * docs. + */ @Value("${spring.cloud.alicloud.oss.authorization-mode:AK_SK}") private AliCloudAuthorizationMode authorizationMode; + /** + * Endpoint, please see oss + * docs. + */ private String endpoint; + /** + * Sts token, please see oss + * docs. + */ private StsToken sts; + /** + * Client Configuration, please see oss + * docs. + */ private ClientBuilderConfiguration config; public AliCloudAuthorizationMode getAuthorizationMode() { diff --git a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/scx/ScxProperties.java b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/scx/ScxProperties.java index db6a00d6..5ddfb0ab 100644 --- a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/scx/ScxProperties.java +++ b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/scx/ScxProperties.java @@ -26,8 +26,18 @@ import com.alibaba.cloud.context.scx.ScxConfiguration; @ConfigurationProperties("spring.cloud.alicloud.scx") public class ScxProperties implements ScxConfiguration { + /** + * Group id, please see scx + * docs. + */ private String groupId; + /** + * Domain name, please see scx + * docs. + */ private String domainName; @Override From 2622f2c5bdad9933af423e4de1ddfda1283202d8 Mon Sep 17 00:00:00 2001 From: flystar32 Date: Thu, 28 Feb 2019 14:57:45 +0800 Subject: [PATCH 17/18] add ACM test case --- spring-cloud-alicloud-acm/pom.xml | 13 ++ .../DiamondConnectionFailureAnalyzer.java | 40 ---- .../DiamondConnectionFailureException.java | 52 ----- .../main/resources/META-INF/spring.factories | 3 - .../alicloud/acm/AcmConfigurationTests.java | 191 ++++++++++++++++++ .../acm/AcmGroupConfigurationTest.java | 105 ++++++++++ .../acm/endpoint/AcmEndpointTests.java | 152 ++++++++++++++ .../context/acm/AcmIntegrationProperties.java | 4 + 8 files changed, 465 insertions(+), 95 deletions(-) delete mode 100644 spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/diagnostics/analyzer/DiamondConnectionFailureAnalyzer.java delete mode 100644 spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/diagnostics/analyzer/DiamondConnectionFailureException.java create mode 100644 spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmConfigurationTests.java create mode 100644 spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmGroupConfigurationTest.java create mode 100644 spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/endpoint/AcmEndpointTests.java diff --git a/spring-cloud-alicloud-acm/pom.xml b/spring-cloud-alicloud-acm/pom.xml index 49012835..6f431517 100644 --- a/spring-cloud-alicloud-acm/pom.xml +++ b/spring-cloud-alicloud-acm/pom.xml @@ -67,6 +67,19 @@ spring-boot-starter-test test + + org.powermock + powermock-module-junit4 + 1.7.1 + test + + + + org.powermock + powermock-api-mockito + 1.7.1 + test + diff --git a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/diagnostics/analyzer/DiamondConnectionFailureAnalyzer.java b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/diagnostics/analyzer/DiamondConnectionFailureAnalyzer.java deleted file mode 100644 index 64d56be3..00000000 --- a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/diagnostics/analyzer/DiamondConnectionFailureAnalyzer.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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 org.springframework.cloud.alicloud.acm.diagnostics.analyzer; - -import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; -import org.springframework.boot.diagnostics.FailureAnalysis; - -/** - * A {@code FailureAnalyzer} that performs analysis of failures caused by a - * {@code DiamondConnectionFailureException}. - * - * @author juven.xuxb, 07/11/2016. - */ -public class DiamondConnectionFailureAnalyzer - extends AbstractFailureAnalyzer { - - @Override - protected FailureAnalysis analyze(Throwable rootFailure, - DiamondConnectionFailureException cause) { - return new FailureAnalysis( - "Application failed to connect to Diamond, unable to access http://" - + cause.getDomain() + ":" + cause.getPort() - + "/diamond-server/diamond", - "config the right endpoint", cause); - } -} diff --git a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/diagnostics/analyzer/DiamondConnectionFailureException.java b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/diagnostics/analyzer/DiamondConnectionFailureException.java deleted file mode 100644 index a1b10abf..00000000 --- a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/diagnostics/analyzer/DiamondConnectionFailureException.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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 org.springframework.cloud.alicloud.acm.diagnostics.analyzer; - -/** - * A {@code DiamondConnectionFailureException} is thrown when the application fails to - * connect to Diamond Server. - * - * @author juven.xuxb, 07/11/2016. - */ -public class DiamondConnectionFailureException extends RuntimeException { - - private final String domain; - - private final String port; - - public DiamondConnectionFailureException(String domain, String port, String message) { - super(message); - this.domain = domain; - this.port = port; - } - - public DiamondConnectionFailureException(String domain, String port, String message, - Throwable cause) { - super(message, cause); - this.domain = domain; - this.port = port; - } - - String getDomain() { - return domain; - } - - String getPort() { - return port; - } - -} diff --git a/spring-cloud-alicloud-acm/src/main/resources/META-INF/spring.factories b/spring-cloud-alicloud-acm/src/main/resources/META-INF/spring.factories index 4f39095f..3fc399da 100644 --- a/spring-cloud-alicloud-acm/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-alicloud-acm/src/main/resources/META-INF/spring.factories @@ -4,6 +4,3 @@ org.springframework.cloud.alicloud.acm.bootstrap.AcmPropertySourceLocator org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.cloud.alicloud.acm.AcmAutoConfiguration,\ org.springframework.cloud.alicloud.acm.endpoint.AcmEndpointAutoConfiguration - -org.springframework.boot.diagnostics.FailureAnalyzer=\ -org.springframework.cloud.alicloud.acm.diagnostics.analyzer.DiamondConnectionFailureAnalyzer \ No newline at end of file diff --git a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmConfigurationTests.java b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmConfigurationTests.java new file mode 100644 index 00000000..ea6a4bdb --- /dev/null +++ b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmConfigurationTests.java @@ -0,0 +1,191 @@ +/* + * 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 org.springframework.cloud.alicloud.acm; + +import static org.junit.Assert.assertArrayEquals; +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 com.alibaba.edas.acm.ConfigService; + +import org.junit.Assert; +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.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.cloud.alicloud.acm.bootstrap.AcmPropertySourceLocator; +import org.springframework.cloud.alicloud.acm.endpoint.AcmEndpointAutoConfiguration; +import org.springframework.cloud.alicloud.context.acm.AcmContextBootstrapConfiguration; +import org.springframework.cloud.alicloud.context.acm.AcmIntegrationProperties; +import org.springframework.cloud.alicloud.context.acm.AcmProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(PowerMockRunner.class) +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ ConfigService.class }) +@SpringBootTest(classes = AcmConfigurationTests.TestConfig.class, properties = { + "spring.application.name=test-name", "spring.profiles.active=dev,test", + "spring.cloud.alicloud.acm.server-list=127.0.0.1", + "spring.cloud.alicloud.acm.server-port=8848", + "spring.cloud.alicloud.acm.endpoint=test-endpoint", + "spring.cloud.alicloud.acm.namespace=test-namespace", + "spring.cloud.alicloud.acm.timeout=1000", + "spring.cloud.alicloud.acm.group=test-group", + "spring.cloud.alicloud.acm.refresh-enabled=false", + "spring.cloud.alicloud.acm.file-extension=properties" }, webEnvironment = NONE) +public class AcmConfigurationTests { + + static { + + try { + + Method method = PowerMockito.method(ConfigService.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 ("test-name.properties".equals(args[0]) + && "test-group".equals(args[1])) { + return "user.name=hello\nuser.age=12"; + } + + if ("test-name-dev.properties".equals(args[0]) + && "test-group".equals(args[1])) { + return "user.name=dev"; + } + return ""; + } + }); + + } + catch (Exception ignore) { + ignore.printStackTrace(); + + } + } + + @Autowired + private Environment environment; + + @Autowired + private AcmPropertySourceLocator locator; + + @Autowired + private AcmIntegrationProperties integrationProperties; + + @Autowired + private AcmProperties properties; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("AcmPropertySourceLocator was not created", locator); + assertNotNull("AcmProperties was not created", properties); + assertNotNull("AcmIntegrationProperties was not created", integrationProperties); + + checkoutAcmServerAddr(); + checkoutAcmServerPort(); + checkoutAcmEndpoint(); + checkoutAcmNamespace(); + checkoutAcmGroup(); + checkoutAcmFileExtension(); + checkoutAcmTimeout(); + checkoutAcmProfiles(); + checkoutAcmRefreshEnabled(); + checkoutDataLoad(); + } + + private void checkoutAcmServerAddr() { + assertEquals("AcmProperties server address is wrong", "127.0.0.1", + properties.getServerList()); + + } + + private void checkoutAcmServerPort() { + assertEquals("AcmProperties server port is wrong", "8848", + properties.getServerPort()); + + } + + private void checkoutAcmEndpoint() { + assertEquals("AcmProperties endpoint is wrong", "test-endpoint", + properties.getEndpoint()); + + } + + private void checkoutAcmNamespace() { + assertEquals("AcmProperties namespace is wrong", "test-namespace", + properties.getNamespace()); + + } + + private void checkoutAcmGroup() { + assertEquals("AcmProperties' group is wrong", "test-group", + properties.getGroup()); + } + + private void checkoutAcmFileExtension() { + assertEquals("AcmProperties' file extension is wrong", "properties", + properties.getFileExtension()); + } + + private void checkoutAcmTimeout() { + assertEquals("AcmProperties' timeout is wrong", 1000, properties.getTimeout()); + } + + private void checkoutAcmRefreshEnabled() { + assertEquals("AcmProperties' refresh enabled is wrong", false, + properties.isRefreshEnabled()); + } + + private void checkoutAcmProfiles() { + assertArrayEquals("AcmProperties' profiles is wrong", + new String[] { "dev", "test" }, + integrationProperties.getActiveProfiles()); + } + + private void checkoutDataLoad() { + Assert.assertEquals(environment.getProperty("user.name"), "dev"); + Assert.assertEquals(environment.getProperty("user.age"), "12"); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class, + AcmAutoConfiguration.class, AcmContextBootstrapConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmGroupConfigurationTest.java b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmGroupConfigurationTest.java new file mode 100644 index 00000000..2e8076ab --- /dev/null +++ b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmGroupConfigurationTest.java @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2019 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 org.springframework.cloud.alicloud.acm; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + +import com.alibaba.edas.acm.ConfigService; + +import org.junit.Assert; +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.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.cloud.alicloud.acm.endpoint.AcmEndpointAutoConfiguration; +import org.springframework.cloud.alicloud.context.acm.AcmContextBootstrapConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; + +/** + * @author xiaojing + */ + +@RunWith(PowerMockRunner.class) +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ ConfigService.class }) +@SpringBootTest(classes = AcmGroupConfigurationTest.TestConfig.class, properties = { + "spring.application.name=test-name", "spring.application.group=com.test.hello", + "spring.cloud.alicloud.acm.server-list=127.0.0.1", + "spring.cloud.alicloud.acm.server-port=8080", + "spring.cloud.alicloud.acm.timeout=1000", + "spring.cloud.alicloud.acm.group=test-group" }, webEnvironment = NONE) +public class AcmGroupConfigurationTest { + + static { + + try { + Method method = PowerMockito.method(ConfigService.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 ("com.test:application.properties".equals(args[0]) + && "test-group".equals(args[1])) { + return "com.test.value=com.test"; + } + if ("com.test.hello:application.properties".equals(args[0]) + && "test-group".equals(args[1])) { + return "com.test.hello.value=com.test.hello"; + } + return ""; + } + }); + + } + catch (Exception ignore) { + ignore.printStackTrace(); + + } + } + + @Autowired + private Environment environment; + + @Test + public void contextLoads() throws Exception { + + Assert.assertEquals(environment.getProperty("com.test.value"), "com.test"); + Assert.assertEquals(environment.getProperty("com.test.hello.value"), + "com.test.hello"); + + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class, + AcmAutoConfiguration.class, AcmContextBootstrapConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/endpoint/AcmEndpointTests.java b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/endpoint/AcmEndpointTests.java new file mode 100644 index 00000000..dcef7f48 --- /dev/null +++ b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/endpoint/AcmEndpointTests.java @@ -0,0 +1,152 @@ +/* + * 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 org.springframework.cloud.alicloud.acm.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 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.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.actuate.health.HealthIndicator; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.acm.AcmAutoConfiguration; +import org.springframework.cloud.alicloud.acm.AcmPropertySourceRepository; +import org.springframework.cloud.alicloud.acm.bootstrap.AcmPropertySourceLocator; +import org.springframework.cloud.alicloud.acm.refresh.AcmRefreshHistory; +import org.springframework.cloud.alicloud.context.acm.AcmContextBootstrapConfiguration; +import org.springframework.cloud.alicloud.context.acm.AcmIntegrationProperties; +import org.springframework.cloud.alicloud.context.acm.AcmProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; + +import com.alibaba.edas.acm.ConfigService; + +/** + * @author xiaojing + */ + +@RunWith(PowerMockRunner.class) +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ ConfigService.class }) +@SpringBootTest(classes = AcmEndpointTests.TestConfig.class, properties = { + "spring.application.name=test-name", + "spring.cloud.alicloud.acm.server-list=127.0.0.1", + "spring.cloud.alicloud.acm.server-port=8848", + "spring.cloud.alicloud.acm.file-extension=properties" }, webEnvironment = NONE) +public class AcmEndpointTests { + + static { + + try { + + Method method = PowerMockito.method(ConfigService.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 ("test-name.properties".equals(args[0]) + && "DEFAULT_GROUP".equals(args[1])) { + return "user.name=hello\nuser.age=12"; + } + return ""; + } + }); + + } + catch (Exception ignore) { + ignore.printStackTrace(); + + } + } + + @Autowired + private AcmProperties properties; + + @Autowired + private AcmRefreshHistory refreshHistory; + + @Autowired + private AcmPropertySourceRepository propertySourceRepository; + + @Autowired + private AcmPropertySourceRepository acmPropertySourceRepository; + + @Test + public void contextLoads() throws Exception { + + checkoutEndpoint(); + checkoutAcmHealthIndicator(); + + } + + private void checkoutAcmHealthIndicator() { + try { + Builder builder = new Builder(); + + AcmHealthIndicator healthIndicator = new AcmHealthIndicator(properties, + acmPropertySourceRepository); + healthIndicator.doHealthCheck(builder); + + Builder builder1 = new Builder(); + List dataIds = new ArrayList<>(); + dataIds.add("test-name.properties"); + builder1.up().withDetail("dataIds", dataIds); + + Assert.assertTrue(builder.build().equals(builder1.build())); + + } + catch (Exception ignoreE) { + + } + + } + + private void checkoutEndpoint() throws Exception { + AcmEndpoint acmEndpoint = new AcmEndpoint(properties, refreshHistory, + propertySourceRepository); + Map map = acmEndpoint.invoke(); + assertEquals(map.get("config"), properties); + assertEquals(((Map) map.get("runtime")).get("refreshHistory"), + refreshHistory.getRecords()); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class, + AcmAutoConfiguration.class, AcmContextBootstrapConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/acm/AcmIntegrationProperties.java b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/acm/AcmIntegrationProperties.java index 8491ef12..55c073b9 100644 --- a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/acm/AcmIntegrationProperties.java +++ b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/acm/AcmIntegrationProperties.java @@ -88,6 +88,10 @@ public class AcmIntegrationProperties { this.activeProfiles = activeProfiles; } + public String[] getActiveProfiles() { + return activeProfiles; + } + public void setAcmProperties(AcmProperties acmProperties) { this.acmProperties = acmProperties; } From db0fa6547b1d96c6ef0f1af30afd47fdc66b9257 Mon Sep 17 00:00:00 2001 From: flystar32 Date: Thu, 28 Feb 2019 15:39:20 +0800 Subject: [PATCH 18/18] add more ACM test case --- .../bootstrap/AcmPropertySourceLocator.java | 2 + .../alicloud/acm/AcmConfigurationTests.java | 6 +- .../alicloud/acm/AcmFileExtensionTest.java | 98 +++++++++++++++++++ .../acm/AcmGroupConfigurationTest.java | 5 +- .../acm/endpoint/AcmEndpointTests.java | 4 - 5 files changed, 108 insertions(+), 7 deletions(-) create mode 100644 spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmFileExtensionTest.java diff --git a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySourceLocator.java b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySourceLocator.java index cb5ebdfb..62ded421 100644 --- a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySourceLocator.java +++ b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySourceLocator.java @@ -42,6 +42,8 @@ public class AcmPropertySourceLocator implements PropertySourceLocator { CompositePropertySource compositePropertySource = new CompositePropertySource( DIAMOND_PROPERTY_SOURCE_NAME); + acmIntegrationProperties.setActiveProfiles(environment.getActiveProfiles()); + for (String dataId : acmIntegrationProperties.getGroupConfigurationDataIds()) { loadDiamondDataIfPresent(compositePropertySource, dataId, acmIntegrationProperties.getAcmProperties().getGroup(), true); diff --git a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmConfigurationTests.java b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmConfigurationTests.java index ea6a4bdb..9d09fd7a 100644 --- a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmConfigurationTests.java +++ b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmConfigurationTests.java @@ -126,6 +126,7 @@ public class AcmConfigurationTests { checkoutAcmProfiles(); checkoutAcmRefreshEnabled(); checkoutDataLoad(); + checkoutProfileDataLoad(); } private void checkoutAcmServerAddr() { @@ -178,10 +179,13 @@ public class AcmConfigurationTests { } private void checkoutDataLoad() { - Assert.assertEquals(environment.getProperty("user.name"), "dev"); Assert.assertEquals(environment.getProperty("user.age"), "12"); } + private void checkoutProfileDataLoad() { + Assert.assertEquals(environment.getProperty("user.name"), "dev"); + } + @Configuration @EnableAutoConfiguration @ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class, diff --git a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmFileExtensionTest.java b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmFileExtensionTest.java new file mode 100644 index 00000000..b463cf8f --- /dev/null +++ b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmFileExtensionTest.java @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2019 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 org.springframework.cloud.alicloud.acm; + +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + +import org.junit.Assert; +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.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.cloud.alicloud.acm.endpoint.AcmEndpointAutoConfiguration; +import org.springframework.cloud.alicloud.context.acm.AcmContextBootstrapConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; + +import com.alibaba.edas.acm.ConfigService; + +/** + * @author xiaojing + */ + +@RunWith(PowerMockRunner.class) +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ ConfigService.class }) +@SpringBootTest(classes = AcmFileExtensionTest.TestConfig.class, properties = { + "spring.application.name=test-name", + "spring.cloud.alicloud.acm.server-list=127.0.0.1", + "spring.cloud.alicloud.acm.server-port=8080", + "spring.cloud.alicloud.acm.file-extension=yaml" }, webEnvironment = NONE) +public class AcmFileExtensionTest { + + static { + + try { + Method method = PowerMockito.method(ConfigService.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 ("test-name.yaml".equals(args[0]) + && "DEFAULT_GROUP".equals(args[1])) { + return "user:\n name: hello\n age: 12"; + } + return ""; + } + }); + + } + catch (Exception ignore) { + ignore.printStackTrace(); + + } + } + + @Autowired + private Environment environment; + + @Test + public void contextLoads() throws Exception { + + Assert.assertEquals(environment.getProperty("user.name"), "hello"); + Assert.assertEquals(environment.getProperty("user.age"), "12"); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class, + AcmAutoConfiguration.class, AcmContextBootstrapConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmGroupConfigurationTest.java b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmGroupConfigurationTest.java index 2e8076ab..030b26d0 100644 --- a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmGroupConfigurationTest.java +++ b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmGroupConfigurationTest.java @@ -67,11 +67,11 @@ public class AcmGroupConfigurationTest { throws Throwable { if ("com.test:application.properties".equals(args[0]) && "test-group".equals(args[1])) { - return "com.test.value=com.test"; + return "com.test.value=com.test\ntest.priority=1"; } if ("com.test.hello:application.properties".equals(args[0]) && "test-group".equals(args[1])) { - return "com.test.hello.value=com.test.hello"; + return "com.test.hello.value=com.test.hello\ntest.priority=2"; } return ""; } @@ -91,6 +91,7 @@ public class AcmGroupConfigurationTest { public void contextLoads() throws Exception { Assert.assertEquals(environment.getProperty("com.test.value"), "com.test"); + Assert.assertEquals(environment.getProperty("test.priority"), "2"); Assert.assertEquals(environment.getProperty("com.test.hello.value"), "com.test.hello"); diff --git a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/endpoint/AcmEndpointTests.java b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/endpoint/AcmEndpointTests.java index dcef7f48..d05ddb5f 100644 --- a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/endpoint/AcmEndpointTests.java +++ b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/endpoint/AcmEndpointTests.java @@ -35,19 +35,15 @@ 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.actuate.health.HealthIndicator; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.alicloud.acm.AcmAutoConfiguration; import org.springframework.cloud.alicloud.acm.AcmPropertySourceRepository; -import org.springframework.cloud.alicloud.acm.bootstrap.AcmPropertySourceLocator; import org.springframework.cloud.alicloud.acm.refresh.AcmRefreshHistory; import org.springframework.cloud.alicloud.context.acm.AcmContextBootstrapConfiguration; -import org.springframework.cloud.alicloud.context.acm.AcmIntegrationProperties; import org.springframework.cloud.alicloud.context.acm.AcmProperties; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; import com.alibaba.edas.acm.ConfigService;