Merge remote-tracking branch 'upstream/master'

pull/364/head
fangjian0423 6 years ago
commit 94a3bc2cc2

@ -20,7 +20,7 @@
<sentinel.version>1.4.1</sentinel.version>
<oss.version>3.1.0</oss.version>
<fescar.version>0.1.3</fescar.version>
<nacos.client.version>0.8.0</nacos.client.version>
<nacos.client.version>0.8.1</nacos.client.version>
<nacos.config.version>0.8.0</nacos.config.version>
<acm.version>1.0.8</acm.version>
<ans.version>1.0.1</ans.version>

@ -1,2 +1,4 @@
spring.application.name=nacos-config-example
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
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

@ -45,6 +45,10 @@
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alicloud-context</artifactId>
</dependency>
</dependencies>
<build>

@ -29,7 +29,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alicloud-context</artifactId>
</dependency>
</dependencies>
<build>

@ -65,6 +65,11 @@
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
@ -75,6 +80,19 @@
<artifactId>spring-cloud-test-support</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock.modules.test.powermockito/powermock-modules-test-powermockito -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
</dependencies>

@ -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);

@ -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;
}
}
}

@ -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);
}
}

@ -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;
}

@ -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] + ",");
}
}

@ -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<ApplicationReadyEvent>, 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);

@ -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);
}
}

@ -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());
}
}
}

@ -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();
}
}

@ -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();
}
}
}

@ -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<String> 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<String, Properties> 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);
}
}

@ -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<String, String> 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<String, String> 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<String, String> 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();
}
}
}

@ -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;
}
}
}

@ -0,0 +1,2 @@
user.name=base-common-value
user.address=zhejiang-hangzhou

@ -0,0 +1,2 @@
user.name=common-value
user.address=zhejiang-ningbo

@ -0,0 +1,4 @@
user:
name: ext-00-value
ext:
key: ext.value00

@ -0,0 +1,5 @@
user:
name: ext-01-value
ext: EXT01_GROUP-value
ext:
key: ext.value01

@ -0,0 +1,5 @@
user:
name: ext-02-value
ext:
key: ext.value02
app-local-common: update app local shared cguration for Nacos

@ -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

@ -11,10 +11,10 @@ import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory;
/**
* @author pbting
*/
public class NacosParameterInitListener
public class NacosConfigParameterInitListener
extends AbstractOnceApplicationListener<ApplicationEnvironmentPreparedEvent> {
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

@ -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<ApplicationEnvironmentPreparedEvent> {
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");
}
}

@ -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

@ -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() {

@ -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");
}
}
Loading…
Cancel
Save