diff --git a/spring-cloud-alibaba-dependencies/pom.xml b/spring-cloud-alibaba-dependencies/pom.xml index 291417429..2eda46bbf 100644 --- a/spring-cloud-alibaba-dependencies/pom.xml +++ b/spring-cloud-alibaba-dependencies/pom.xml @@ -20,7 +20,7 @@ 1.4.1 3.1.0 0.1.3 - 0.8.0 + 0.8.1 0.8.0 1.0.8 1.0.1 diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/bootstrap.properties b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/bootstrap.properties index 6adb653ca..831d8ff78 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/bootstrap.properties +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/bootstrap.properties @@ -1,2 +1,4 @@ -spring.application.name=nacos-config-example -spring.cloud.nacos.config.server-addr=127.0.0.1:8848 \ No newline at end of file +spring.application.name=sca-nacos-config +spring.cloud.nacos.config.server-addr=127.0.0.1:8848 +spring.cloud.nacos.config.shared-data-ids=base-common.properties,common.properties +spring.cloud.nacos.config.refreshable-dataids=common.properties \ No newline at end of file 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 6a3af32b3..d0ac8e07a 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 @@ -45,6 +45,10 @@ spring-cloud-starter-alibaba-sentinel + + org.springframework.cloud + spring-cloud-alicloud-context + 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 60fd7050f..df0e78025 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,7 +29,10 @@ org.springframework.boot spring-boot-starter-actuator - + + org.springframework.cloud + spring-cloud-alicloud-context + diff --git a/spring-cloud-alibaba-nacos-config/pom.xml b/spring-cloud-alibaba-nacos-config/pom.xml index 05a7f5bd8..8096c7139 100644 --- a/spring-cloud-alibaba-nacos-config/pom.xml +++ b/spring-cloud-alibaba-nacos-config/pom.xml @@ -65,6 +65,11 @@ true + + org.springframework.boot + spring-boot-starter-web + test + org.springframework.boot spring-boot-starter-test @@ -75,6 +80,19 @@ spring-cloud-test-support test + + + org.powermock + powermock-module-junit4 + 2.0.0 + test + + + org.powermock + powermock-api-mockito2 + 2.0.0 + test + 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 7fedcc169..94933a4d2 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; @@ -34,6 +35,7 @@ public class NacosConfigBootstrapConfiguration { } @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 4fefa8633..c0e454926 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,8 +18,8 @@ package org.springframework.cloud.alibaba.nacos; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.config.ConfigService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.core.env.Environment; @@ -30,14 +30,7 @@ import java.util.List; import java.util.Objects; import java.util.Properties; -import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; -import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; -import static com.alibaba.nacos.api.PropertyKeyConst.CONTEXT_PATH; -import static com.alibaba.nacos.api.PropertyKeyConst.ENCODE; -import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; -import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; -import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; -import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; +import static com.alibaba.nacos.api.PropertyKeyConst.*; /** * nacos properties @@ -49,9 +42,15 @@ import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; @ConfigurationProperties(NacosConfigProperties.PREFIX) public class NacosConfigProperties { - static final String PREFIX = "spring.cloud.nacos.config"; + public static final String PREFIX = "spring.cloud.nacos.config"; - private static final Log log = LogFactory.getLog(NacosConfigProperties.class); + private static final Logger log = LoggerFactory + .getLogger(NacosConfigProperties.class); + + /** + * whether to enable nacos config. + */ + private boolean enabled = true; /** * nacos config server address @@ -145,6 +144,14 @@ public class NacosConfigProperties { // todo sts support + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + public String getServerAddr() { return serverAddr; } @@ -322,16 +329,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() { @@ -354,11 +362,8 @@ public class NacosConfigProperties { return configService; } catch (Exception e) { - log.error( - "create config service error!properties=" + this.toString() + ",e=,", - 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/NacosPropertySourceRepository.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosPropertySourceRepository.java index f29ab80a2..0a0cc00cd 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosPropertySourceRepository.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosPropertySourceRepository.java @@ -24,6 +24,7 @@ import java.util.concurrent.ConcurrentHashMap; /** * @author xiaojing + * @author pbting */ public class NacosPropertySourceRepository { @@ -45,6 +46,7 @@ public class NacosPropertySourceRepository { } public static NacosPropertySource getNacosPropertySource(String dataId) { + return nacosPropertySourceRepository.get(dataId); } } 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 c820d8b0e..d53690074 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 @@ -18,26 +18,23 @@ package org.springframework.cloud.alibaba.nacos.client; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.cloud.alibaba.nacos.NacosPropertySourceRepository; import org.springframework.core.io.ByteArrayResource; import org.springframework.util.StringUtils; import java.io.StringReader; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; +import java.util.*; /** * @author xiaojing * @author pbting */ public class NacosPropertySourceBuilder { - private static final Log log = LogFactory.getLog(NacosPropertySourceBuilder.class); + private static final Logger log = LoggerFactory + .getLogger(NacosPropertySourceBuilder.class); private static final Properties EMPTY_PROPERTIES = new Properties(); private ConfigService configService; @@ -101,11 +98,10 @@ public class NacosPropertySourceBuilder { } } catch (NacosException e) { - log.error("get data from Nacos error,dataId:" + dataId + ", ", e); + log.error("get data from Nacos error,dataId:{}, ", dataId, e); } catch (Exception e) { - log.error("parse data from Nacos error,dataId:" + dataId + ",data:" + data - + ",", e); + log.error("parse data from Nacos error,dataId:{},data:{},", dataId, data, e); } return EMPTY_PROPERTIES; } 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 5ffb7ac31..7a665d2bb 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 @@ -17,8 +17,8 @@ package org.springframework.cloud.alibaba.nacos.client; import com.alibaba.nacos.api.config.ConfigService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.cloud.alibaba.nacos.NacosConfigProperties; import org.springframework.cloud.alibaba.nacos.NacosPropertySourceRepository; import org.springframework.cloud.alibaba.nacos.refresh.NacosContextRefresher; @@ -39,7 +39,8 @@ import java.util.List; @Order(0) public class NacosPropertySourceLocator implements PropertySourceLocator { - private static final Log log = LogFactory.getLog(NacosPropertySourceLocator.class); + private static final Logger log = LoggerFactory + .getLogger(NacosPropertySourceLocator.class); private static final String NACOS_PROPERTY_SOURCE_NAME = "NACOS"; private static final String SEP1 = "-"; private static final String DOT = "."; @@ -182,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-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 fcc6d9df1..40341d41c 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,8 +19,9 @@ 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.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.alibaba.nacos.NacosPropertySourceRepository; import org.springframework.cloud.alibaba.nacos.client.NacosPropertySource; @@ -51,7 +52,8 @@ import java.util.concurrent.atomic.AtomicLong; public class NacosContextRefresher implements ApplicationListener, ApplicationContextAware { - private final static Log log = LogFactory.getLog(NacosContextRefresher.class); + private final static Logger log = LoggerFactory + .getLogger(NacosContextRefresher.class); private static final AtomicLong REFRESH_COUNT = new AtomicLong(0); diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/EndpointTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/EndpointTests.java new file mode 100644 index 000000000..5ef53f032 --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/EndpointTests.java @@ -0,0 +1,43 @@ +/* + * 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; + +import org.junit.Test; +import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigEndpoint; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author pbting + * @date 2019-01-17 2:25 PM + */ +public class EndpointTests extends NacosPowerMockitBaseTests { + + @Test + public void nacosConfigEndpoint() { + + NacosConfigEndpoint nacosConfigEndpoint = super.context + .getBean(NacosConfigEndpoint.class); + assertThat(nacosConfigEndpoint != null).isEqualTo(true); + } + + @Test + public void endpointInvoke() { + NacosConfigEndpoint nacosConfigEndpoint = this.context + .getBean(NacosConfigEndpoint.class); + assertThat(nacosConfigEndpoint.invoke() != null).isEqualTo(true); + } +} \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigAutoConfigurationTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigAutoConfigurationTests.java index 4ecb4ddfb..32d63fd61 100644 --- a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigAutoConfigurationTests.java +++ b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigAutoConfigurationTests.java @@ -16,59 +16,52 @@ package org.springframework.cloud.alibaba.nacos; -import org.junit.After; -import org.junit.Before; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceLocator; import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshProperties; -import org.springframework.cloud.context.refresh.ContextRefresher; -import org.springframework.cloud.context.scope.refresh.RefreshScope; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -import static org.assertj.core.api.Assertions.assertThat; +import org.springframework.core.env.CompositePropertySource; +import org.springframework.core.env.PropertySource; /** * @author xiaojing + * @author pbting */ -public class NacosConfigAutoConfigurationTests { - - private ConfigurableApplicationContext context; - - @Before - public void setUp() throws Exception { - this.context = new SpringApplicationBuilder( - NacosConfigBootstrapConfiguration.class, - NacosConfigAutoConfiguration.class, TestConfiguration.class) - .web(WebApplicationType.NONE) - .run("--spring.cloud.nacos.config.name=myapp", - "--spring.cloud.config.enabled=true", - "--spring.cloud.nacos.config.server-addr=127.0.0.1:8848", - "--spring.cloud.nacos.config.prefix=test"); - } - - @After - public void tearDown() throws Exception { - if (this.context != null) { - this.context.close(); - } - } - +public class NacosConfigAutoConfigurationTests extends NacosPowerMockitBaseTests { @Test public void testNacosConfigProperties() { - NacosConfigProperties nacosConfigProperties = this.context.getParent() + NacosConfigProperties nacosConfigProperties = context.getParent() .getBean(NacosConfigProperties.class); assertThat(nacosConfigProperties.getFileExtension()).isEqualTo("properties"); - assertThat(nacosConfigProperties.getPrefix()).isEqualTo("test"); - assertThat(nacosConfigProperties.getName()).isEqualTo("myapp"); + assertThat(nacosConfigProperties.getPrefix() == null).isEqualTo(true); + assertThat(nacosConfigProperties.getNamespace() == null).isEqualTo(true); + assertThat(nacosConfigProperties.getName()).isEqualTo("sca-nacos-config"); + assertThat(nacosConfigProperties.getServerAddr()).isEqualTo("127.0.0.1:8848"); + assertThat(nacosConfigProperties.getEncode()).isEqualTo("utf-8"); + assertThat(nacosConfigProperties.getActiveProfiles()) + .isEqualTo(new String[] { "develop" }); + assertThat(nacosConfigProperties.getSharedDataids()) + .isEqualTo("base-common.properties,common.properties"); + assertThat(nacosConfigProperties.getRefreshableDataids()) + .isEqualTo("common.properties"); + assertThat(nacosConfigProperties.getExtConfig().size()).isEqualTo(3); + assertThat(nacosConfigProperties.getExtConfig().get(0).getDataId()) + .isEqualTo("ext00.yaml"); + assertThat(nacosConfigProperties.getExtConfig().get(1).getGroup()) + .isEqualTo("EXT01_GROUP"); + assertThat(nacosConfigProperties.getExtConfig().get(1).isRefresh()) + .isEqualTo(true); + } + @Test + public void nacosPropertySourceLocator() { + NacosPropertySourceLocator nacosPropertySourceLocator = this.context + .getBean(NacosPropertySourceLocator.class); + PropertySource propertySource = nacosPropertySourceLocator + .locate(this.context.getEnvironment()); + assertThat(propertySource instanceof CompositePropertySource).isEqualTo(true); } @Test @@ -80,18 +73,4 @@ public class NacosConfigAutoConfigurationTests { } - @Configuration - @AutoConfigureBefore(NacosConfigAutoConfiguration.class) - static class TestConfiguration { - - @Autowired - ConfigurableApplicationContext context; - - @Bean - ContextRefresher contextRefresher() { - return new ContextRefresher(context, new RefreshScope()); - } - - } - } diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigBootstrapConfigurationTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigBootstrapConfigurationTests.java deleted file mode 100644 index 3d273f2ab..000000000 --- a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigBootstrapConfigurationTests.java +++ /dev/null @@ -1,82 +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.alibaba.nacos; - -import java.lang.reflect.Field; - -import com.alibaba.nacos.api.config.ConfigService; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceLocator; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.Environment; -import org.springframework.util.ReflectionUtils; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author xiaojing - */ -public class NacosConfigBootstrapConfigurationTests { - - private ConfigurableApplicationContext context; - - @Before - public void setUp() throws Exception { - this.context = new SpringApplicationBuilder( - NacosConfigBootstrapConfiguration.class).web(WebApplicationType.NONE).run( - "--spring.cloud.nacos.config.name=myapp", - "--spring.cloud.config.enabled=true", - "--spring.cloud.nacos.config.server-addr=127.0.0.1:8848", - "--spring.cloud.nacos.config.prefix=test"); - } - - @After - public void tearDown() throws Exception { - if (this.context != null) { - this.context.close(); - } - } - - @Test - public void testNacosPropertySourceLocator() { - - NacosPropertySourceLocator locator = this.context - .getBean(NacosPropertySourceLocator.class); - Environment environment = this.context.getEnvironment(); - try { - locator.locate(environment); - } - catch (Exception e) { - - } - - Field nacosConfigPropertiesField = ReflectionUtils - .findField(NacosPropertySourceLocator.class, "nacosConfigProperties"); - nacosConfigPropertiesField.setAccessible(true); - - NacosConfigProperties configService = (NacosConfigProperties) ReflectionUtils - .getField(nacosConfigPropertiesField, locator); - - assertThat(configService).isNotNull(); - } - -} diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigHealthIndicatorTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigHealthIndicatorTests.java new file mode 100644 index 000000000..1fd434b5a --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigHealthIndicatorTests.java @@ -0,0 +1,67 @@ +/* + * 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; + +import org.junit.Test; +import org.springframework.boot.actuate.health.Health; +import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigHealthIndicator; +import org.springframework.util.ReflectionUtils; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author pbting + * @date 2019-01-17 2:58 PM + */ +public class NacosConfigHealthIndicatorTests extends NacosPowerMockitBaseTests { + + @Test + public void nacosConfigHealthIndicatorInstance() { + NacosConfigHealthIndicator nacosConfigHealthIndicator = this.context + .getBean(NacosConfigHealthIndicator.class); + + assertThat(nacosConfigHealthIndicator != null).isEqualTo(true); + } + + @Test + public void testHealthCheck() { + + NacosConfigHealthIndicator nacosConfigHealthIndicator = this.context + .getBean(NacosConfigHealthIndicator.class); + + Health.Builder builder = Health.up(); + + Method method = ReflectionUtils.findMethod(NacosConfigHealthIndicator.class, + "doHealthCheck", Health.Builder.class); + ReflectionUtils.makeAccessible(method); + assertThat(method != null).isEqualTo(true); + + try { + method.invoke(nacosConfigHealthIndicator, builder); + assertThat(builder != null).isEqualTo(true); + } + catch (IllegalAccessException e) { + e.printStackTrace(); + } + catch (InvocationTargetException e) { + e.printStackTrace(); + } + + } +} \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosPowerMockitBaseTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosPowerMockitBaseTests.java new file mode 100644 index 000000000..a54f19186 --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosPowerMockitBaseTests.java @@ -0,0 +1,171 @@ +/* + * 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; + +import com.alibaba.nacos.api.config.ConfigService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.api.support.MethodProxy; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alibaba.nacos.client.NacosPropertySource; +import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceBuilder; +import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigEndpointAutoConfiguration; +import org.springframework.cloud.context.refresh.ContextRefresher; +import org.springframework.cloud.context.scope.refresh.RefreshScope; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.util.ReflectionUtils; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.*; + +/** + * @author pbting + * @date 2019-01-17 8:54 PM + */ +@RunWith(PowerMockRunner.class) +@PowerMockRunnerDelegate(SpringRunner.class) +@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*" }) +@PrepareForTest({ NacosPropertySourceBuilder.class }) +@SpringBootTest(classes = { NacosConfigBootstrapConfiguration.class, + NacosConfigEndpointAutoConfiguration.class, NacosConfigAutoConfiguration.class, + NacosPowerMockitBaseTests.TestConfiguration.class }, properties = { + "spring.application.name=sca-nacos-config", + "spring.cloud.nacos.config.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.config.name=sca-nacos-config", + // "spring.cloud.nacos.config.refresh.enabled=false", + "spring.cloud.nacos.config.encode=utf-8", + "spring.cloud.nacos.config.shared-data-ids=base-common.properties,common.properties", + "spring.cloud.nacos.config.refreshable-dataids=common.properties", + "spring.cloud.nacos.config.ext-config[0].data-id=ext00.yaml", + "spring.cloud.nacos.config.ext-config[1].data-id=ext01.yml", + "spring.cloud.nacos.config.ext-config[1].group=EXT01_GROUP", + "spring.cloud.nacos.config.ext-config[1].refresh=true", + "spring.cloud.nacos.config.ext-config[2].data-id=ext02.yaml", + "spring.profiles.active=develop", "server.port=19090" }) +public class NacosPowerMockitBaseTests { + + private final static List DATAIDS = Arrays.asList("common.properties", + "base-common.properties", "ext00.yaml", "ext01.yml", "ext02.yaml", + "sca-nacos-config.properties", "sca-nacos-config-develop.properties"); + + private final static HashMap VALUES = new HashMap<>(); + + @Autowired + protected ApplicationContext context; + + static { + initDataIds(); + try { + final Constructor constructor = ReflectionUtils.accessibleConstructor( + NacosPropertySource.class, String.class, String.class, Map.class, + Date.class, boolean.class); + Method method = PowerMockito.method(NacosPropertySourceBuilder.class, "build", + String.class, String.class, String.class, boolean.class); + MethodProxy.proxy(method, new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + Properties properties = VALUES.get(args[0].toString()); + if (properties == null) { + properties = new Properties(); + properties.put("user.name", args[0].toString()); + } + Object instance = constructor.newInstance(args[1].toString(), + args[0].toString(), properties, new Date(), args[3]); + return instance; + } + }); + } + catch (NoSuchMethodException e) { + e.printStackTrace(); + } + } + + private static void initDataIds() { + DATAIDS.forEach(dataId -> { + String realpath = "/" + dataId; + ClassPathResource classPathResource = new ClassPathResource(realpath); + if (realpath.endsWith("properties")) { + Properties properties = new Properties(); + try { + properties.load(classPathResource.getInputStream()); + VALUES.put(dataId, properties); + } + catch (IOException e) { + e.printStackTrace(); + } + } + + if (realpath.endsWith("yaml") || realpath.endsWith("yml")) { + YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); + yamlFactory.setResources(classPathResource); + try { + VALUES.put(dataId, yamlFactory.getObject()); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + + public NacosPropertySourceBuilder nacosPropertySourceBuilderInstance() { + NacosConfigProperties nacosConfigProperties = this.context + .getBean(NacosConfigProperties.class); + + ConfigService configService = nacosConfigProperties.configServiceInstance(); + long timeout = nacosConfigProperties.getTimeout(); + NacosPropertySourceBuilder nacosPropertySourceBuilder = new NacosPropertySourceBuilder( + configService, timeout); + return nacosPropertySourceBuilder; + } + + @Configuration + @AutoConfigureBefore(NacosConfigAutoConfiguration.class) + static class TestConfiguration { + + @Autowired + ConfigurableApplicationContext context; + + @Bean + ContextRefresher contextRefresher() { + RefreshScope refreshScope = new RefreshScope(); + refreshScope.setApplicationContext(context); + return new ContextRefresher(context, refreshScope); + } + } + + @Test + public void testAppContext() { + System.err.println(this.context); + } +} \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosPropertySourceBuilderTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosPropertySourceBuilderTests.java new file mode 100644 index 000000000..40248d25a --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosPropertySourceBuilderTests.java @@ -0,0 +1,190 @@ +/* + * 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; + +import org.junit.Test; +import org.powermock.api.support.MethodProxy; +import org.springframework.cloud.alibaba.nacos.client.NacosPropertySource; +import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceBuilder; +import org.springframework.util.ReflectionUtils; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author pbting + * @date 2019-01-17 11:49 AM + */ +public class NacosPropertySourceBuilderTests extends NacosPowerMockitBaseTests { + + @Test + public void nacosPropertySourceBuilder() { + + assertThat(nacosPropertySourceBuilderInstance() != null).isEqualTo(true); + } + + @Test + public void getConfigByProperties() { + try { + final HashMap value = new HashMap<>(); + value.put("dev.mode", "local-mock"); + + final Constructor constructor = ReflectionUtils.accessibleConstructor( + NacosPropertySource.class, String.class, String.class, Map.class, + Date.class, boolean.class); + + NacosPropertySourceBuilder nacosPropertySourceBuilder = nacosPropertySourceBuilderInstance(); + + Method method = ReflectionUtils.findMethod(NacosPropertySourceBuilder.class, + "build", String.class, String.class, String.class, boolean.class); + ReflectionUtils.makeAccessible(method); + assertThat(method != null).isEqualTo(true); + MethodProxy.proxy(method, new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + Object instance = constructor.newInstance(args[1].toString(), + args[0].toString(), value, new Date(), args[3]); + return instance; + } + }); + + Object result = method.invoke(nacosPropertySourceBuilder, + "mock-nacos-config.properties", "DEFAULT_GROUP", "properties", true); + assertThat(result != null).isEqualTo(true); + assertThat(result instanceof NacosPropertySource).isEqualTo(true); + NacosPropertySource nacosPropertySource = (NacosPropertySource) result; + assertThat(nacosPropertySource.getProperty("dev.mode")) + .isEqualTo("local-mock"); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void getConfigByYaml() { + + try { + // + final HashMap value = new HashMap<>(); + value.put("mock-ext-config", "mock-ext-config-value"); + + final Constructor constructor = ReflectionUtils.accessibleConstructor( + NacosPropertySource.class, String.class, String.class, Map.class, + Date.class, boolean.class); + + Method method = ReflectionUtils.findMethod(NacosPropertySourceBuilder.class, + "build", String.class, String.class, String.class, boolean.class); + ReflectionUtils.makeAccessible(method); + assertThat(method != null).isEqualTo(true); + + MethodProxy.proxy(method, new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + Object instance = constructor.newInstance(args[1].toString(), + args[0].toString(), value, new Date(), args[3]); + return instance; + } + }); + + NacosPropertySourceBuilder nacosPropertySourceBuilder = nacosPropertySourceBuilderInstance(); + Object result = method.invoke(nacosPropertySourceBuilder, "ext-config.yaml", + "DEFAULT_GROUP", "yaml", true); + assertThat(result != null).isEqualTo(true); + assertThat(result instanceof NacosPropertySource).isEqualTo(true); + NacosPropertySource nacosPropertySource = (NacosPropertySource) result; + assertThat(nacosPropertySource.getProperty("mock-ext-config")) + .isEqualTo("mock-ext-config-value"); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void getConfigByYml() { + try { + // + final HashMap value = new HashMap<>(); + value.put("mock-ext-config-yml", "mock-ext-config-yml-value"); + + final Constructor constructor = ReflectionUtils.accessibleConstructor( + NacosPropertySource.class, String.class, String.class, Map.class, + Date.class, boolean.class); + + Method method = ReflectionUtils.findMethod(NacosPropertySourceBuilder.class, + "build", String.class, String.class, String.class, boolean.class); + ReflectionUtils.makeAccessible(method); + assertThat(method != null).isEqualTo(true); + + MethodProxy.proxy(method, new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + Object instance = constructor.newInstance(args[1].toString(), + args[0].toString(), value, new Date(), args[3]); + return instance; + } + }); + + NacosPropertySourceBuilder nacosPropertySourceBuilder = nacosPropertySourceBuilderInstance(); + Object result = method.invoke(nacosPropertySourceBuilder, "ext-config.yml", + "DEFAULT_GROUP", "yml", true); + assertThat(result != null).isEqualTo(true); + assertThat(result instanceof NacosPropertySource).isEqualTo(true); + NacosPropertySource nacosPropertySource = (NacosPropertySource) result; + assertThat(nacosPropertySource.getProperty("mock-ext-config-yml")) + .isEqualTo("mock-ext-config-yml-value"); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void getEmpty() { + NacosPropertySourceBuilder nacosPropertySourceBuilder = nacosPropertySourceBuilderInstance(); + + Method method = ReflectionUtils.findMethod(NacosPropertySourceBuilder.class, + "build", String.class, String.class, String.class, boolean.class); + ReflectionUtils.makeAccessible(method); + assertThat(method != null).isEqualTo(true); + + try { + Object result = method.invoke(nacosPropertySourceBuilder, "nacos-empty.yml", + "DEFAULT_GROUP", "yml", true); + assertThat(result != null).isEqualTo(true); + assertThat(result instanceof NacosPropertySource).isEqualTo(true); + NacosPropertySource nacosPropertySource = (NacosPropertySource) result; + assertThat(nacosPropertySource.getProperty("address")).isEqualTo(null); + } + catch (IllegalAccessException e) { + e.printStackTrace(); + } + catch (InvocationTargetException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosSharedAndExtConfigTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosSharedAndExtConfigTests.java new file mode 100644 index 000000000..90fe3ca4e --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosSharedAndExtConfigTests.java @@ -0,0 +1,91 @@ +/* + * 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; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author pbting + * @date 2019-01-17 11:46 AM + */ +public class NacosSharedAndExtConfigTests extends NacosPowerMockitBaseTests { + private final static Logger log = LoggerFactory + .getLogger(NacosSharedAndExtConfigTests.class); + + @Test + public void testSharedConfigPriority() { + String userName = this.context.getEnvironment().getProperty("user.address"); + assertThat(userName).isEqualTo("zhejiang-ningbo"); + } + + @Test + public void testSharedConfigRefresh() { + + while (true) { + // ContextRefresher contextRefresher = this.context + // .getBean(ContextRefresher.class); + // contextRefresher.refresh(); + String userName = this.context.getEnvironment().getProperty("user.address"); + try { + assertThat(userName).isEqualTo("zhejiang-ningbo"); + TimeUnit.SECONDS.sleep(1); + log.info("user name is {}", userName); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + // 真实测试时将这里 注释掉 + break; + } + } + + @Test + public void testExtConfigPriority() { + String extKey = this.context.getEnvironment().getProperty("ext.key"); + assertThat(extKey).isEqualTo("ext.value02"); + } + + @Test + public void testExtOtherGroup() { + String userExt = this.context.getEnvironment().getProperty("user.ext"); + assertThat(userExt).isEqualTo("EXT01_GROUP-value"); + } + + @Test + public void testExtRefresh() { + while (true) { + // ContextRefresher contextRefresher = this.context + // .getBean(ContextRefresher.class); + // contextRefresher.refresh(); + String userExt = this.context.getEnvironment().getProperty("user.ext"); + try { + assertThat(userExt).isEqualTo("EXT01_GROUP-value"); + TimeUnit.SECONDS.sleep(1); + log.info("user name is {}", userExt); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + break; + } + } +} \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/base-common.properties b/spring-cloud-alibaba-nacos-config/src/test/resources/base-common.properties new file mode 100644 index 000000000..71137acf8 --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/resources/base-common.properties @@ -0,0 +1,2 @@ +user.name=base-common-value +user.address=zhejiang-hangzhou \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/common.properties b/spring-cloud-alibaba-nacos-config/src/test/resources/common.properties new file mode 100644 index 000000000..d8f617767 --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/resources/common.properties @@ -0,0 +1,2 @@ +user.name=common-value +user.address=zhejiang-ningbo \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/ext00.yaml b/spring-cloud-alibaba-nacos-config/src/test/resources/ext00.yaml new file mode 100644 index 000000000..4d70f6749 --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/resources/ext00.yaml @@ -0,0 +1,4 @@ +user: + name: ext-00-value +ext: + key: ext.value00 \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/ext01.yml b/spring-cloud-alibaba-nacos-config/src/test/resources/ext01.yml new file mode 100644 index 000000000..c689c09ee --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/resources/ext01.yml @@ -0,0 +1,5 @@ +user: + name: ext-01-value + ext: EXT01_GROUP-value +ext: + key: ext.value01 diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/ext02.yaml b/spring-cloud-alibaba-nacos-config/src/test/resources/ext02.yaml new file mode 100644 index 000000000..9cc477408 --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/resources/ext02.yaml @@ -0,0 +1,5 @@ +user: + name: ext-02-value +ext: + key: ext.value02 +app-local-common: update app local shared cguration for Nacos \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/sca-nacos-config-develop.properties b/spring-cloud-alibaba-nacos-config/src/test/resources/sca-nacos-config-develop.properties new file mode 100644 index 000000000..21a6ef58f --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/resources/sca-nacos-config-develop.properties @@ -0,0 +1 @@ +user.name=sca-nacos-config-value-develop \ No newline at end of file diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/sca-nacos-config.properties b/spring-cloud-alibaba-nacos-config/src/test/resources/sca-nacos-config.properties new file mode 100644 index 000000000..db268f2ca --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/resources/sca-nacos-config.properties @@ -0,0 +1,2 @@ +user.name=sca-nacos-config-value +dev.mode=local \ No newline at end of file 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 index 88291f5c5..872c22a1c 100644 --- 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 @@ -42,7 +42,7 @@ import org.springframework.test.context.junit4.SpringRunner; @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) + "spring.cloud.nacos.discovery.ip=123.123.123.123" }, webEnvironment = RANDOM_PORT) public class NacosAutoServiceRegistrationIpTests { @Autowired diff --git a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosParameterInitListener.java b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosConfigParameterInitListener.java similarity index 87% rename from spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosParameterInitListener.java rename to spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosConfigParameterInitListener.java index 91e9dd200..9f1cd1f9b 100644 --- a/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosParameterInitListener.java +++ b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosConfigParameterInitListener.java @@ -11,10 +11,10 @@ import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; /** * @author pbting */ -public class NacosParameterInitListener +public class NacosConfigParameterInitListener extends AbstractOnceApplicationListener { private static final Logger log = LoggerFactory - .getLogger(NacosParameterInitListener.class); + .getLogger(NacosConfigParameterInitListener.class); @Override protected String conditionalOnClass() { @@ -30,12 +30,15 @@ public class NacosParameterInitListener EdasChangeOrderConfiguration edasChangeOrderConfiguration = EdasChangeOrderConfigurationFactory .getEdasChangeOrderConfiguration(); + if (log.isDebugEnabled()) { + log.debug("Initialize Nacos Config Parameter ,is managed {}.", + edasChangeOrderConfiguration.isEdasManaged()); + } + if (!edasChangeOrderConfiguration.isEdasManaged()) { return; } - log.info("Initialize Nacos Parameter from edas change order,is edas managed {}.", - edasChangeOrderConfiguration.isEdasManaged()); System.getProperties().setProperty("spring.cloud.nacos.config.server-mode", "EDAS"); // initialize nacos configuration 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 new file mode 100644 index 000000000..757f2b50e --- /dev/null +++ b/spring-cloud-alicloud-context/src/main/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListener.java @@ -0,0 +1,72 @@ +/* + * 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.context.nacos; + +import com.alibaba.cloud.context.edas.EdasChangeOrderConfiguration; +import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; +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; + +/** + * @author pbting + * @date 2019-02-14 11:12 AM + */ +public class NacosDiscoveryParameterInitListener + extends AbstractOnceApplicationListener { + private static final Logger log = LoggerFactory + .getLogger(NacosDiscoveryParameterInitListener.class); + + @Override + protected String conditionalOnClass() { + return "org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration"; + } + + @Override + protected void handleEvent(ApplicationEnvironmentPreparedEvent event) { + EdasChangeOrderConfiguration edasChangeOrderConfiguration = EdasChangeOrderConfigurationFactory + .getEdasChangeOrderConfiguration(); + + if (log.isDebugEnabled()) { + log.debug("Initialize Nacos Discovery Parameter ,is managed {}.", + edasChangeOrderConfiguration.isEdasManaged()); + } + + if (!edasChangeOrderConfiguration.isEdasManaged()) { + return; + } + // initialize nacos configuration + Properties properties = System.getProperties(); + + // 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", + edasChangeOrderConfiguration.getAddressServerDomain()); + properties.setProperty("spring.cloud.nacos.discovery.namespace", + edasChangeOrderConfiguration.getTenantId()); + properties.setProperty("spring.cloud.nacos.discovery.access-key", + edasChangeOrderConfiguration.getDauthAccessKey()); + properties.setProperty("spring.cloud.nacos.discovery.secret-key", + edasChangeOrderConfiguration.getDauthSecretKey()); + + // step 2: set these properties for nacos client + properties.setProperty("webContext", "/vipserver"); + properties.setProperty("serverPort", "80"); + } +} \ No newline at end of file diff --git a/spring-cloud-alicloud-context/src/main/resources/META-INF/spring.factories b/spring-cloud-alicloud-context/src/main/resources/META-INF/spring.factories index f99f05028..b39c6499b 100644 --- a/spring-cloud-alicloud-context/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-alicloud-context/src/main/resources/META-INF/spring.factories @@ -10,5 +10,6 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.cloud.alicloud.context.sms.SmsContextAutoConfiguration org.springframework.context.ApplicationListener=\ org.springframework.cloud.alicloud.context.ans.AnsContextApplicationListener,\ - org.springframework.cloud.alicloud.context.nacos.NacosParameterInitListener,\ + org.springframework.cloud.alicloud.context.nacos.NacosConfigParameterInitListener,\ + org.springframework.cloud.alicloud.context.nacos.NacosDiscoveryParameterInitListener,\ org.springframework.cloud.alicloud.context.sentinel.SentinelAliCloudListener \ No newline at end of file diff --git a/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosParameterInitListenerTests.java b/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosConfigParameterInitListenerTests.java similarity index 92% rename from spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosParameterInitListenerTests.java rename to spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosConfigParameterInitListenerTests.java index fe0451fde..c8a11a627 100644 --- a/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosParameterInitListenerTests.java +++ b/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosConfigParameterInitListenerTests.java @@ -16,23 +16,22 @@ package org.springframework.cloud.alicloud.context.nacos; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - +import com.alibaba.cloud.context.ans.AliCloudAnsInitializer; +import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; 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 com.alibaba.cloud.context.ans.AliCloudAnsInitializer; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author xiaolongzuo */ @PrepareForTest({ EdasChangeOrderConfigurationFactory.class, - NacosParameterInitListener.class, AliCloudAnsInitializer.class }) -public class NacosParameterInitListenerTests extends BaseAliCloudSpringApplication { + NacosConfigParameterInitListener.class, AliCloudAnsInitializer.class }) +public class NacosConfigParameterInitListenerTests extends BaseAliCloudSpringApplication { @BeforeClass public static void setUp() { 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 new file mode 100644 index 000000000..393980015 --- /dev/null +++ b/spring-cloud-alicloud-context/src/test/java/org/springframework/cloud/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java @@ -0,0 +1,58 @@ +/* + * 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.context.nacos; + +import com.alibaba.cloud.context.ans.AliCloudAnsInitializer; +import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; +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.AssertionsForClassTypes.assertThat; + +/** + * @author xiaolongzuo + */ +@PrepareForTest({EdasChangeOrderConfigurationFactory.class, + NacosConfigParameterInitListener.class, AliCloudAnsInitializer.class}) +public class NacosDiscoveryParameterInitListenerTests extends BaseAliCloudSpringApplication { + + @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")) + .isEqualTo(""); + assertThat(System.getProperty("spring.cloud.nacos.config.endpoint")) + .isEqualTo("testDomain"); + assertThat(System.getProperty("spring.cloud.nacos.config.namespace")) + .isEqualTo("testTenantId"); + assertThat(System.getProperty("spring.cloud.nacos.config.access-key")) + .isEqualTo("testAK"); + assertThat(System.getProperty("spring.cloud.nacos.config.secret-key")) + .isEqualTo("testSK"); + assertThat(System.getProperties().getProperty("webContext")).isEqualTo("/vipserver"); + assertThat(System.getProperties().getProperty("serverPort")).isEqualTo("80"); + } +}