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

Merge remote-tracking branch 'upstream/1.x' into binder-dev-1.x

This commit is contained in:
fangjian0423 2019-02-28 15:41:45 +08:00
commit 348f699eb8
82 changed files with 2353 additions and 559 deletions

View File

@ -16,9 +16,9 @@
<description>Spring Cloud Alibaba Dependencies</description>
<properties>
<sentinel.version>1.4.1</sentinel.version>
<sentinel.version>1.4.2</sentinel.version>
<oss.version>3.1.0</oss.version>
<nacos.version>0.8.1</nacos.version>
<nacos.version>0.8.2</nacos.version>
<fescar.version>0.1.3</fescar.version>
<acm.version>1.0.8</acm.version>
<ans.version>1.0.1</ans.version>

View File

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

View File

@ -29,11 +29,6 @@
<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>

View File

@ -0,0 +1,35 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.cloud.examples;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author xiaolongzuo
*/
@RestController
public class HelloController {
@RequestMapping("/")
@ResponseBody
public String hello() {
return "OK";
}
}

View File

@ -16,25 +16,25 @@
package org.springframework.cloud.alibaba.cloud.examples;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.edas.schedulerx.ProcessResult;
import com.alibaba.edas.schedulerx.ScxSimpleJobContext;
import com.alibaba.edas.schedulerx.ScxSimpleJobProcessor;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author xiaolongzuo
*/
public class SimpleTask implements ScxSimpleJobProcessor {
@Autowired
private TestService testService;
@Autowired
private TestService testService;
@Override
public ProcessResult process(ScxSimpleJobContext context) {
System.out.println("-----------Hello world---------------");
testService.test();
ProcessResult processResult = new ProcessResult(true);
return processResult;
}
@Override
public ProcessResult process(ScxSimpleJobContext context) {
testService.test();
ProcessResult processResult = new ProcessResult(true);
return processResult;
}
}

View File

@ -0,0 +1,39 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.cloud.examples;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author xiaolongzuo
*/
@RestController
public class TestController {
static AtomicInteger atomicInteger = new AtomicInteger(0);
@RequestMapping("/test")
@ResponseBody
public String test() {
return String.valueOf(atomicInteger.get());
}
}

View File

@ -24,7 +24,7 @@ import org.springframework.stereotype.Service;
@Service
public class TestService {
public void test() {
System.out.println("---------IOC Success--------");
}
public void test() {
TestController.atomicInteger.incrementAndGet();
}
}

View File

@ -17,6 +17,7 @@
package org.springframework.cloud.alibaba.nacos;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -27,15 +28,17 @@ import org.springframework.context.annotation.Configuration;
@Configuration
public class NacosConfigBootstrapConfiguration {
@Bean
public NacosPropertySourceLocator nacosPropertySourceLocator() {
return new NacosPropertySourceLocator();
}
@Bean
@ConditionalOnMissingBean
public NacosConfigProperties nacosConfigProperties() {
return new NacosConfigProperties();
}
@Bean
@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public NacosPropertySourceLocator nacosPropertySourceLocator(
NacosConfigProperties nacosConfigProperties) {
return new NacosPropertySourceLocator(nacosConfigProperties);
}
}

View File

@ -44,9 +44,14 @@ public class NacosConfigProperties {
public static final String PREFIX = "spring.cloud.nacos.config";
private static final Logger LOGGER = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(NacosConfigProperties.class);
/**
* whether to enable nacos config.
*/
private boolean enabled = true;
/**
* nacos config server address
*/
@ -137,11 +142,15 @@ public class NacosConfigProperties {
this.activeProfiles = environment.getActiveProfiles();
}
public void setActiveProfiles(String[] activeProfiles) {
this.activeProfiles = activeProfiles;
// todo sts support
public boolean isEnabled() {
return enabled;
}
// todo sts support
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getServerAddr() {
return serverAddr;
@ -243,10 +252,6 @@ public class NacosConfigProperties {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getActiveProfiles() {
return activeProfiles;
}
@ -275,6 +280,14 @@ public class NacosConfigProperties {
this.extConfig = extConfig;
}
public void setName(String name) {
this.name = name;
}
public void setActiveProfiles(String[] activeProfiles) {
this.activeProfiles = activeProfiles;
}
public static class Config {
/**
* the data id of extended configuration
@ -316,16 +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() {
@ -348,7 +362,7 @@ public class NacosConfigProperties {
return configService;
}
catch (Exception e) {
LOGGER.error("create config service error!properties={},e=,", this, e);
log.error("create config service error!properties={},e=,", this, e);
return null;
}
}

View File

@ -33,7 +33,7 @@ import java.util.*;
* @author pbting
*/
public class NacosPropertySourceBuilder {
private static final Logger LOGGER = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(NacosPropertySourceBuilder.class);
private static final Properties EMPTY_PROPERTIES = new Properties();
@ -68,9 +68,6 @@ public class NacosPropertySourceBuilder {
NacosPropertySource build(String dataId, String group, String fileExtension,
boolean isRefreshable) {
Properties p = loadNacosData(dataId, group, fileExtension);
if (p == null) {
p = EMPTY_PROPERTIES;
}
NacosPropertySource nacosPropertySource = new NacosPropertySource(group, dataId,
propertiesToMap(p), new Date(), isRefreshable);
NacosPropertySourceRepository.collectNacosPropertySources(nacosPropertySource);
@ -82,7 +79,7 @@ public class NacosPropertySourceBuilder {
try {
data = configService.getConfig(dataId, group, timeout);
if (!StringUtils.isEmpty(data)) {
LOGGER.info(String.format("Loading nacos data, dataId: '%s', group: '%s'",
log.info(String.format("Loading nacos data, dataId: '%s', group: '%s'",
dataId, group));
if (fileExtension.equalsIgnoreCase("properties")) {
@ -101,21 +98,20 @@ public class NacosPropertySourceBuilder {
}
}
catch (NacosException e) {
LOGGER.error("get data from Nacos error,dataId:{}, ", dataId, e);
log.error("get data from Nacos error,dataId:{}, ", dataId, e);
}
catch (Exception e) {
LOGGER.error("parse data from Nacos error,dataId:{},data:{},", dataId, data,
e);
log.error("parse data from Nacos error,dataId:{},data:{},", dataId, data, e);
}
return null;
return EMPTY_PROPERTIES;
}
@SuppressWarnings("unchecked")
private Map<String, Object> propertiesToMap(Properties properties) {
Map<String, Object> result = new HashMap<>(16);
Enumeration<String> tmpKeys = (Enumeration<String>) properties.propertyNames();
while (tmpKeys.hasMoreElements()) {
String key = tmpKeys.nextElement();
Enumeration<String> keys = (Enumeration<String>) properties.propertyNames();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
Object value = properties.getProperty(key);
if (value != null) {
result.put(key, ((String) value).trim());
@ -126,4 +122,5 @@ public class NacosPropertySourceBuilder {
}
return result;
}
}

View File

@ -19,7 +19,6 @@ package org.springframework.cloud.alibaba.nacos.client;
import com.alibaba.nacos.api.config.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosConfigProperties;
import org.springframework.cloud.alibaba.nacos.NacosPropertySourceRepository;
import org.springframework.cloud.alibaba.nacos.refresh.NacosContextRefresher;
@ -40,7 +39,7 @@ import java.util.List;
@Order(0)
public class NacosPropertySourceLocator implements PropertySourceLocator {
private static final Logger LOGGER = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(NacosPropertySourceLocator.class);
private static final String NACOS_PROPERTY_SOURCE_NAME = "NACOS";
private static final String SEP1 = "-";
@ -49,22 +48,21 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
private static final List<String> SUPPORT_FILE_EXTENSION = Arrays.asList("properties",
"yaml", "yml");
@Autowired
private NacosPropertySourceBuilder nacosPropertySourceBuilder;
private NacosConfigProperties nacosConfigProperties;
public NacosPropertySourceLocator() {
public NacosPropertySourceLocator(NacosConfigProperties nacosConfigProperties) {
this.nacosConfigProperties = nacosConfigProperties;
}
private NacosPropertySourceBuilder nacosPropertySourceBuilder;
@Override
public PropertySource<?> locate(Environment env) {
ConfigService configService = nacosConfigProperties.configServiceInstance();
if (null == configService) {
LOGGER.warn(
"no instance of config service found, can't load config from nacos");
log.warn("no instance of config service found, can't load config from nacos");
return null;
}
long timeout = nacosConfigProperties.getTimeout();
@ -167,8 +165,7 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
private void loadNacosDataIfPresent(final CompositePropertySource composite,
final String dataId, final String group, String fileExtension,
boolean isRefreshable) {
if (NacosContextRefresher.loadCount.get() != 0) {
if (NacosContextRefresher.getRefreshCount() != 0) {
NacosPropertySource ps;
if (!isRefreshable) {
ps = NacosPropertySourceRepository.getNacosPropertySource(dataId);
@ -184,18 +181,22 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
fileExtension, isRefreshable);
composite.addFirstPropertySource(ps);
}
}
private static void checkDataIdFileExtension(String[] sharedDataIdArry) {
private static void checkDataIdFileExtension(String[] dataIdArray) {
StringBuilder stringBuilder = new StringBuilder();
outline: 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) {
continue outline;
if (dataIdArray[i].indexOf(fileExtension) > 0) {
isLegal = true;
break;
}
}
stringBuilder.append(sharedDataIdArry[i] + ",");
// add tips
if (!isLegal) {
stringBuilder.append(dataIdArray[i] + ",");
}
}
if (stringBuilder.length() > 0) {

View File

@ -19,6 +19,7 @@ package org.springframework.cloud.alibaba.nacos.refresh;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
@ -51,10 +52,10 @@ import java.util.concurrent.atomic.AtomicLong;
public class NacosContextRefresher
implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {
private final static Logger LOGGER = LoggerFactory
private final static Logger log = LoggerFactory
.getLogger(NacosContextRefresher.class);
public static final AtomicLong loadCount = new AtomicLong(0);
private static final AtomicLong REFRESH_COUNT = new AtomicLong(0);
private final NacosRefreshProperties refreshProperties;
@ -110,7 +111,7 @@ public class NacosContextRefresher
listener = new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
loadCount.incrementAndGet();
refreshCountIncrement();
String md5 = "";
if (!StringUtils.isEmpty(configInfo)) {
try {
@ -120,16 +121,15 @@ public class NacosContextRefresher
}
catch (NoSuchAlgorithmException
| UnsupportedEncodingException e) {
LOGGER.warn("[Nacos] unable to get md5 for dataId: " + dataId,
log.warn("[Nacos] unable to get md5 for dataId: " + dataId,
e);
}
}
refreshHistory.add(dataId, md5);
applicationContext.publishEvent(
new RefreshEvent(this, null, "Refresh Nacos config"));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Refresh Nacos config group{},dataId{}", group,
dataId);
if (log.isDebugEnabled()) {
log.debug("Refresh Nacos config group{},dataId{}", group, dataId);
}
}
@ -149,4 +149,11 @@ public class NacosContextRefresher
}
}
public static long getRefreshCount() {
return REFRESH_COUNT.get();
}
public static void refreshCountIncrement() {
REFRESH_COUNT.incrementAndGet();
}
}

View File

@ -16,16 +16,23 @@
package org.springframework.cloud.alibaba.nacos;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.registry.NacosAutoServiceRegistration;
import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration;
import org.springframework.cloud.alibaba.nacos.registry.NacosServiceRegistry;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -38,19 +45,28 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnNacosDiscoveryEnabled
@ConditionalOnClass(name = "org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent")
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
@AutoConfigureBefore({ AutoServiceRegistrationAutoConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class })
@AutoConfigureBefore(NacosDiscoveryClientAutoConfiguration.class)
@AutoConfigureAfter(AutoServiceRegistrationConfiguration.class)
public class NacosDiscoveryAutoConfiguration {
@Bean
public NacosServiceRegistry nacosServiceRegistry() {
return new NacosServiceRegistry();
@ConditionalOnMissingBean
public NacosDiscoveryProperties nacosProperties() {
return new NacosDiscoveryProperties();
}
@Bean
public NacosServiceRegistry nacosServiceRegistry(
NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosServiceRegistry(nacosDiscoveryProperties);
}
@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
public NacosRegistration nacosRegistration() {
return new NacosRegistration();
public NacosRegistration nacosRegistration(
NacosDiscoveryProperties nacosDiscoveryProperties,
ApplicationContext context) {
return new NacosRegistration(nacosDiscoveryProperties, context);
}
@Bean
@ -62,4 +78,31 @@ public class NacosDiscoveryAutoConfiguration {
return new NacosAutoServiceRegistration(registry,
autoServiceRegistrationProperties, registration);
}
@Bean
@ConditionalOnBean(NacosAutoServiceRegistration.class) // NacosAutoServiceRegistration
// should be present
@ConditionalOnNotWebApplication // Not Web Application
public ApplicationRunner applicationRunner(
final NacosAutoServiceRegistration nacosAutoServiceRegistration) {
return new ApplicationRunner() {
@Override
public void run(ApplicationArguments args) throws Exception {
if (!nacosAutoServiceRegistration.isRunning()) { // If it's not running,
// let
// it start.
// FIXME: Please make sure "spring.cloud.nacos.discovery.port" must be
// configured on an available port,
// or the startup or Nacos health check will be failed.
nacosAutoServiceRegistration.start();
// NacosAutoServiceRegistration will be stopped after its destroy()
// method
// is invoked.
// @PreDestroy destroy() -> stop()
}
}
};
}
}

View File

@ -27,7 +27,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.net.Inet4Address;
import java.net.InetAddress;
@ -40,7 +39,7 @@ import static com.alibaba.nacos.api.PropertyKeyConst.*;
/**
* @author dungu.zpf
* @author xiaojing
* @author pbting
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
@ConfigurationProperties("spring.cloud.nacos.discovery")
@ -65,6 +64,11 @@ public class NacosDiscoveryProperties {
*/
private String namespace;
/**
* watch delay,duration to pull new service from nacos server.
*/
private long watchDelay = 5000;
/**
* nacos naming log file name
*/
@ -145,7 +149,14 @@ public class NacosDiscoveryProperties {
@PostConstruct
public void init() throws SocketException {
if (secure) {
metadata.put("secure", "true");
}
serverAddr = Objects.toString(serverAddr, "");
if (serverAddr.lastIndexOf("/") != -1) {
serverAddr.substring(0, serverAddr.length() - 1);
}
endpoint = Objects.toString(endpoint, "");
namespace = Objects.toString(namespace, "");
logName = Objects.toString(logName, "");
@ -158,7 +169,7 @@ public class NacosDiscoveryProperties {
else {
NetworkInterface netInterface = NetworkInterface
.getByName(networkInterface);
if (null == networkInterface) {
if (null == netInterface) {
throw new IllegalArgumentException(
"no such interface " + networkInterface);
}
@ -316,16 +327,25 @@ public class NacosDiscoveryProperties {
this.namingLoadCacheAtStart = namingLoadCacheAtStart;
}
public long getWatchDelay() {
return watchDelay;
}
public void setWatchDelay(long watchDelay) {
this.watchDelay = watchDelay;
}
@Override
public String toString() {
return "NacosDiscoveryProperties{" + "serverAddr='" + serverAddr + '\''
+ ", endpoint='" + endpoint + '\'' + ", namespace='" + namespace + '\''
+ ", logName='" + logName + '\'' + ", service='" + service + '\''
+ ", weight=" + weight + ", clusterName='" + clusterName + '\''
+ ", metadata=" + metadata + ", registerEnabled=" + registerEnabled
+ ", ip='" + ip + '\'' + ", networkInterface='" + networkInterface + '\''
+ ", port=" + port + ", secure=" + secure + ", accessKey='" + accessKey
+ ", namingLoadCacheAtStart=" + namingLoadCacheAtStart + '\''
+ ", watchDelay=" + watchDelay + ", logName='" + logName + '\''
+ ", service='" + service + '\'' + ", weight=" + weight
+ ", clusterName='" + clusterName + '\'' + ", namingLoadCacheAtStart='"
+ namingLoadCacheAtStart + '\'' + ", metadata=" + metadata
+ ", registerEnabled=" + registerEnabled + ", ip='" + ip + '\''
+ ", networkInterface='" + networkInterface + '\'' + ", port=" + port
+ ", secure=" + secure + ", accessKey='" + accessKey + '\''
+ ", secretKey='" + secretKey + '\'' + '}';
}
@ -353,7 +373,7 @@ public class NacosDiscoveryProperties {
}
if (StringUtils.isEmpty(this.getClusterName())) {
this.setClusterName(env.resolvePlaceholders(
"${spring.cloud.nacos.discovery.clusterName-name:}"));
"${spring.cloud.nacos.discovery.cluster-name:}"));
}
if (StringUtils.isEmpty(this.getEndpoint())) {
this.setEndpoint(
@ -379,12 +399,12 @@ public class NacosDiscoveryProperties {
try {
namingService = NacosFactory.createNamingService(properties);
return namingService;
}
catch (Exception e) {
LOGGER.error("create naming service error!properties={},e=,", this, e);
return null;
}
return namingService;
}
}

View File

@ -14,13 +14,14 @@
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos;
package org.springframework.cloud.alibaba.nacos.discovery;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.NacosServiceInstance;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
@ -30,7 +31,6 @@ import java.util.*;
/**
* @author xiaojing
* @author renhaojun
* @author pbting
*/
public class NacosDiscoveryClient implements DiscoveryClient {
@ -38,9 +38,12 @@ public class NacosDiscoveryClient implements DiscoveryClient {
.getLogger(NacosDiscoveryClient.class);
public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client";
@Autowired
private NacosDiscoveryProperties discoveryProperties;
public NacosDiscoveryClient(NacosDiscoveryProperties discoveryProperties) {
this.discoveryProperties = discoveryProperties;
}
@Override
public String description() {
return DESCRIPTION;
@ -75,19 +78,24 @@ public class NacosDiscoveryClient implements DiscoveryClient {
nacosServiceInstance.setHost(instance.getIp());
nacosServiceInstance.setPort(instance.getPort());
nacosServiceInstance.setServiceId(serviceId);
Map<String, String> metadata = new HashMap<String, String>();
Map<String, String> metadata = new HashMap<>();
metadata.put("instanceId", instance.getInstanceId());
metadata.put("weight", instance.getWeight() + "");
metadata.put("healthy", instance.isHealthy() + "");
metadata.put("cluster", instance.getClusterName() + "");
metadata.putAll(instance.getMetadata());
nacosServiceInstance.setMetadata(metadata);
if (metadata.containsKey("secure")) {
boolean secure = Boolean.parseBoolean(metadata.get("secure"));
nacosServiceInstance.setSecure(secure);
}
return nacosServiceInstance;
}
private static List<ServiceInstance> hostToServiceInstanceList(
List<Instance> instances, String serviceId) {
List<ServiceInstance> result = new ArrayList<ServiceInstance>(instances.size());
List<ServiceInstance> result = new ArrayList<>(instances.size());
for (Instance instance : instances) {
result.add(hostToServiceInstance(instance, serviceId));
}

View File

@ -14,11 +14,16 @@
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos;
package org.springframework.cloud.alibaba.nacos.discovery;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.alibaba.nacos.ConditionalOnNacosDiscoveryEnabled;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.client.CommonsClientAutoConfiguration;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -26,20 +31,21 @@ import org.springframework.context.annotation.Configuration;
* @author xiaojing
*/
@Configuration
@ConditionalOnMissingBean(DiscoveryClient.class)
@ConditionalOnNacosDiscoveryEnabled
@EnableConfigurationProperties
@AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class,
CommonsClientAutoConfiguration.class })
public class NacosDiscoveryClientAutoConfiguration {
@Bean
public DiscoveryClient nacosDiscoveryClient() {
return new NacosDiscoveryClient();
public DiscoveryClient nacosDiscoveryClient(
NacosDiscoveryProperties discoveryProperties) {
return new NacosDiscoveryClient(discoveryProperties);
}
@Bean
@ConditionalOnMissingBean
public NacosDiscoveryProperties nacosProperties() {
return new NacosDiscoveryProperties();
public NacosWatch nacosWatch(NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosWatch(nacosDiscoveryProperties);
}
}

View File

@ -0,0 +1,183 @@
/*
* Copyright (C) 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos.discovery;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.pojo.ListView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.client.discovery.event.HeartbeatEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.SmartLifecycle;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* @author xiaojing
*/
public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycle {
private static final Logger log = LoggerFactory.getLogger(NacosWatch.class);
private final NacosDiscoveryProperties properties;
private final TaskScheduler taskScheduler;
private final AtomicLong nacosWatchIndex = new AtomicLong(0);
private final AtomicBoolean running = new AtomicBoolean(false);
private ApplicationEventPublisher publisher;
private ScheduledFuture<?> watchFuture;
private Set<String> cacheServices = new HashSet<>();
private HashMap<String, EventListener> subscribeListeners = new HashMap<>();
public NacosWatch(NacosDiscoveryProperties properties) {
this(properties, getTaskScheduler());
}
public NacosWatch(NacosDiscoveryProperties properties, TaskScheduler taskScheduler) {
this.properties = properties;
this.taskScheduler = taskScheduler;
}
private static ThreadPoolTaskScheduler getTaskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
return taskScheduler;
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void stop(Runnable callback) {
this.stop();
callback.run();
}
@Override
public void start() {
if (this.running.compareAndSet(false, true)) {
this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
NacosWatch.this.nacosServicesWatch();
}
}, this.properties.getWatchDelay());
}
}
@Override
public void stop() {
if (this.running.compareAndSet(true, false) && this.watchFuture != null) {
this.watchFuture.cancel(true);
}
}
@Override
public boolean isRunning() {
return false;
}
@Override
public int getPhase() {
return 0;
}
public void nacosServicesWatch() {
try {
boolean changed = false;
NamingService namingService = properties.namingServiceInstance();
ListView<String> listView = properties.namingServiceInstance()
.getServicesOfServer(1, Integer.MAX_VALUE);
List<String> serviceList = listView.getData();
// if there are new services found, publish event
Set<String> currentServices = new HashSet<>(serviceList);
currentServices.removeAll(cacheServices);
if (currentServices.size() > 0) {
changed = true;
}
// if some services disappear, publish event
if (cacheServices.removeAll(new HashSet<>(serviceList))
&& cacheServices.size() > 0) {
changed = true;
for (String serviceName : cacheServices) {
namingService.unsubscribe(serviceName,
subscribeListeners.get(serviceName));
subscribeListeners.remove(serviceName);
}
}
cacheServices = new HashSet<>(serviceList);
// subscribe services's node change, publish event if nodes changed
for (String serviceName : cacheServices) {
if (!subscribeListeners.containsKey(serviceName)) {
EventListener eventListener = new EventListener() {
@Override
public void onEvent(Event event) {
NacosWatch.this.publisher.publishEvent(new HeartbeatEvent(
NacosWatch.this, nacosWatchIndex.getAndIncrement()));
}
};
subscribeListeners.put(serviceName, eventListener);
namingService.subscribe(serviceName, eventListener);
}
}
if (changed) {
this.publisher.publishEvent(
new HeartbeatEvent(this, nacosWatchIndex.getAndIncrement()));
}
}
catch (Exception e) {
log.error("Error watching Nacos Service change", e);
}
}
}

View File

@ -26,7 +26,6 @@ import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
@ -39,11 +38,11 @@ public class NacosDiscoveryEndpoint extends AbstractEndpoint<Map<String, Object>
private static final Logger LOGGER = LoggerFactory
.getLogger(NacosDiscoveryEndpoint.class);
@Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties;
public NacosDiscoveryEndpoint() {
public NacosDiscoveryEndpoint(NacosDiscoveryProperties nacosDiscoveryProperties) {
super("nacos_discovery", false);
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
}
/**

View File

@ -18,7 +18,7 @@ package org.springframework.cloud.alibaba.nacos.endpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -31,8 +31,9 @@ public class NacosDiscoveryEndpointAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public NacosDiscoveryEndpoint nacosDiscoveryEndpoint() {
return new NacosDiscoveryEndpoint();
public NacosDiscoveryEndpoint nacosDiscoveryEndpoint(
NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosDiscoveryEndpoint(nacosDiscoveryProperties);
}
}

View File

@ -18,26 +18,25 @@ package org.springframework.cloud.alibaba.nacos.registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* @author xiaojing
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
public class NacosAutoServiceRegistration
extends AbstractAutoServiceRegistration<NacosRegistration> {
extends AbstractAutoServiceRegistration<Registration> {
private static final Logger LOGGER = LoggerFactory
.getLogger(NacosAutoServiceRegistration.class);
@Autowired
private NacosRegistration registration;
public NacosAutoServiceRegistration(
ServiceRegistry<NacosRegistration> serviceRegistry,
public NacosAutoServiceRegistration(ServiceRegistry<Registration> serviceRegistry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
NacosRegistration registration) {
super(serviceRegistry, autoServiceRegistrationProperties);

View File

@ -17,7 +17,6 @@
package org.springframework.cloud.alibaba.nacos.registry;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.ManagementServerPortUtils;
@ -38,16 +37,20 @@ import com.alibaba.nacos.api.naming.NamingService;
*/
public class NacosRegistration implements Registration, ServiceInstance {
private static final String MANAGEMENT_PORT = "management.port";
private static final String MANAGEMENT_CONTEXT_PATH = "management.context-path";
private static final String MANAGEMENT_ADDRESS = "management.address";
public static final String MANAGEMENT_PORT = "management.port";
public static final String MANAGEMENT_CONTEXT_PATH = "management.context-path";
public static final String MANAGEMENT_ADDRESS = "management.address";
@Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties;
@Autowired
private ApplicationContext context;
public NacosRegistration(NacosDiscoveryProperties nacosDiscoveryProperties,
ApplicationContext context) {
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
this.context = context;
}
@PostConstruct
public void init() {
@ -121,11 +124,6 @@ public class NacosRegistration implements Registration, ServiceInstance {
return nacosDiscoveryProperties.namingServiceInstance();
}
public void setNacosDiscoveryProperties(
NacosDiscoveryProperties nacosDiscoveryProperties) {
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
}
@Override
public String toString() {
return "NacosRegistration{" + "nacosDiscoveryProperties="

View File

@ -20,37 +20,43 @@ import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.util.StringUtils;
/**
* @author xiaojing
* @author pbting
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
public class NacosServiceRegistry implements ServiceRegistry<NacosRegistration> {
public class NacosServiceRegistry implements ServiceRegistry<Registration> {
private static Logger logger = LoggerFactory.getLogger(NacosServiceRegistry.class);
@Override
public void register(NacosRegistration registration) {
private final NacosDiscoveryProperties nacosDiscoveryProperties;
private final NamingService namingService;
public NacosServiceRegistry(NacosDiscoveryProperties nacosDiscoveryProperties) {
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
this.namingService = nacosDiscoveryProperties.namingServiceInstance();
}
@Override
public void register(Registration registration) {
if (!registration.isRegisterEnabled()) {
logger.info("Nacos Registration is disabled...");
return;
}
if (StringUtils.isEmpty(registration.getServiceId())) {
logger.info("No service to register for nacos client...");
return;
}
NamingService namingService = registration.getNacosNamingService();
String serviceId = registration.getServiceId();
Instance instance = new Instance();
instance.setIp(registration.getHost());
instance.setPort(registration.getPort());
instance.setWeight(registration.getRegisterWeight());
instance.setClusterName(registration.getCluster());
instance.setWeight(nacosDiscoveryProperties.getWeight());
instance.setClusterName(nacosDiscoveryProperties.getClusterName());
instance.setMetadata(registration.getMetadata());
try {
@ -65,7 +71,7 @@ public class NacosServiceRegistry implements ServiceRegistry<NacosRegistration>
}
@Override
public void deregister(NacosRegistration registration) {
public void deregister(Registration registration) {
logger.info("De-registering from Nacos Server now...");
@ -74,12 +80,12 @@ public class NacosServiceRegistry implements ServiceRegistry<NacosRegistration>
return;
}
NamingService namingService = registration.getNacosNamingService();
NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
String serviceId = registration.getServiceId();
try {
namingService.deregisterInstance(serviceId, registration.getHost(),
registration.getPort(), registration.getCluster());
registration.getPort(), nacosDiscoveryProperties.getClusterName());
}
catch (Exception e) {
logger.error("ERR_NACOS_DEREGISTER, de-register failed...{},",
@ -95,12 +101,12 @@ public class NacosServiceRegistry implements ServiceRegistry<NacosRegistration>
}
@Override
public void setStatus(NacosRegistration registration, String status) {
public void setStatus(Registration registration, String status) {
// nacos doesn't support set status of a particular registration.
}
@Override
public <T> T getStatus(NacosRegistration registration) {
public <T> T getStatus(Registration registration) {
// nacos doesn't support query status of a particular registration.
return null;
}

View File

@ -19,6 +19,7 @@ package org.springframework.cloud.alibaba.nacos.ribbon;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ServerList;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -32,8 +33,8 @@ public class NacosRibbonClientConfiguration {
@Bean
@ConditionalOnMissingBean
public ServerList<?> ribbonServerList(IClientConfig config) {
NacosServerList serverList = new NacosServerList();
public ServerList<?> ribbonServerList(IClientConfig config, NacosDiscoveryProperties nacosDiscoveryProperties) {
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
serverList.initWithNiwsConfig(config);
return serverList;
}

View File

@ -16,32 +16,26 @@
package org.springframework.cloud.alibaba.nacos.ribbon;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractServerList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.nacos.api.naming.pojo.Instance;
/**
* @author xiaojing
* @author renhaojun
*/
public class NacosServerList extends AbstractServerList<NacosServer> {
@Autowired
private NacosDiscoveryProperties discoveryProperties;
private String serviceId;
public NacosServerList() {
}
public NacosServerList(String serviceId) {
this.serviceId = serviceId;
public NacosServerList(NacosDiscoveryProperties discoveryProperties) {
this.discoveryProperties = discoveryProperties;
}
@Override
@ -68,7 +62,10 @@ public class NacosServerList extends AbstractServerList<NacosServer> {
}
private List<NacosServer> instancesToServerList(List<Instance> instances) {
List<NacosServer> result = new ArrayList<>(instances.size());
List<NacosServer> result = new ArrayList<>();
if (null == instances) {
return result;
}
for (Instance instance : instances) {
result.add(new NacosServer(instance));
}

View File

@ -1,5 +1,4 @@
{
"properties": [
{"properties": [
{
"name": "spring.cloud.nacos.discovery.service",
"type": "java.lang.String",
@ -12,5 +11,4 @@
"defaultValue": "false",
"description": "naming load from local cache at application start ."
}
]
}
]}

View File

@ -1,6 +1,5 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration,\
org.springframework.cloud.alibaba.nacos.ribbon.RibbonNacosAutoConfiguration,\
org.springframework.cloud.alibaba.nacos.endpoint.NacosDiscoveryEndpointAutoConfiguration
org.springframework.cloud.client.discovery.EnableDiscoveryClient=\
org.springframework.cloud.alibaba.nacos.NacosDiscoveryClientAutoConfiguration
org.springframework.cloud.alibaba.nacos.endpoint.NacosDiscoveryEndpointAutoConfiguration,\
org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration

View File

@ -19,9 +19,9 @@ package org.springframework.cloud.alibaba.nacos;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.commons.util.InetUtils;
@ -44,7 +44,7 @@ public class NacosDiscoveryAutoConfigurationTests {
this.context = new SpringApplicationBuilder(NacosDiscoveryTestConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class).web(false).run(
"--spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080",
"--spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848",
"--spring.cloud.nacos.discovery.port=18080",
"--spring.cloud.nacos.discovery.service=myapp");
}
@ -55,7 +55,7 @@ public class NacosDiscoveryAutoConfigurationTests {
NacosDiscoveryProperties properties = context
.getBean(NacosDiscoveryProperties.class);
assertThat(properties.getPort()).isEqualTo(18080);
assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8080");
assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848");
assertThat(properties.getService()).isEqualTo("myapp");
}

View File

@ -0,0 +1,127 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import org.junit.Test;
import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClient;
import org.springframework.cloud.client.ServiceInstance;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.cloud.alibaba.nacos.test.NacosMockTest.serviceInstance;
/**
* @author xiaojing
*/
public class NacosDiscoveryClientTests {
private String host = "123.123.123.123";
private int port = 8888;
private String serviceName = "test-service";
@Test
public void testGetServers() throws Exception {
ArrayList<Instance> instances = new ArrayList<>();
HashMap<String, String> map = new HashMap<>();
map.put("test-key", "test-value");
map.put("secure", "true");
instances.add(serviceInstance(serviceName, false, host, port, map));
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class);
NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
when(namingService.selectInstances(eq(serviceName), eq(true)))
.thenReturn(instances);
NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient(
nacosDiscoveryProperties);
List<ServiceInstance> serviceInstances = discoveryClient
.getInstances(serviceName);
assertThat(serviceInstances.size()).isEqualTo(1);
ServiceInstance serviceInstance = serviceInstances.get(0);
assertThat(serviceInstance.getServiceId()).isEqualTo(serviceName);
assertThat(serviceInstance.getHost()).isEqualTo(host);
assertThat(serviceInstance.getPort()).isEqualTo(port);
assertThat(serviceInstance.isSecure()).isEqualTo(true);
assertThat(serviceInstance.getUri().toString())
.isEqualTo(getUri(serviceInstance));
assertThat(serviceInstance.getMetadata().get("test-key")).isEqualTo("test-value");
}
@Test
public void testGetAllService() throws Exception {
ListView<String> nacosServices = new ListView<>();
nacosServices.setData(new LinkedList<String>());
nacosServices.getData().add(serviceName + "1");
nacosServices.getData().add(serviceName + "2");
nacosServices.getData().add(serviceName + "3");
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class);
NamingService namingService = mock(NamingService.class);
NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient(
nacosDiscoveryProperties);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE)))
.thenReturn(nacosServices);
List<String> services = discoveryClient.getServices();
assertThat(services.size()).isEqualTo(3);
assertThat(services.contains(serviceName + "1"));
assertThat(services.contains(serviceName + "2"));
assertThat(services.contains(serviceName + "3"));
}
private String getUri(ServiceInstance instance) {
if (instance.isSecure()) {
return "https://" + host + ":" + port;
}
return "http://" + host + ":" + port;
}
}

View File

@ -0,0 +1,147 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos.registry;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosAutoServiceRegistrationIpNetworkInterfaceTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848" }, webEnvironment = RANDOM_PORT)
public class NacosAutoServiceRegistrationIpNetworkInterfaceTests {
@Autowired
private NacosRegistration registration;
@Autowired
private NacosAutoServiceRegistration nacosAutoServiceRegistration;
@Autowired
private NacosDiscoveryProperties properties;
@Autowired
private InetUtils inetUtils;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosRegistration was not created", registration);
assertNotNull("NacosDiscoveryProperties was not created", properties);
assertNotNull("NacosAutoServiceRegistration was not created",
nacosAutoServiceRegistration);
checkoutNacosDiscoveryServiceIP();
}
private void checkoutNacosDiscoveryServiceIP() {
assertEquals("NacosDiscoveryProperties service IP was wrong",
getIPFromNetworkInterface(TestConfig.netWorkInterfaceName),
registration.getHost());
}
private String getIPFromNetworkInterface(String networkInterface) {
if (!TestConfig.hasValidNetworkInterface) {
return inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
}
try {
NetworkInterface netInterface = NetworkInterface.getByName(networkInterface);
Enumeration<InetAddress> inetAddress = netInterface.getInetAddresses();
while (inetAddress.hasMoreElements()) {
InetAddress currentAddress = inetAddress.nextElement();
if (currentAddress instanceof Inet4Address
&& !currentAddress.isLoopbackAddress()) {
return currentAddress.getHostAddress();
}
}
return networkInterface;
}
catch (Exception e) {
return networkInterface;
}
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class })
public static class TestConfig {
static boolean hasValidNetworkInterface = false;
static String netWorkInterfaceName;
static {
try {
Enumeration<NetworkInterface> enumeration = NetworkInterface
.getNetworkInterfaces();
while (enumeration.hasMoreElements() && !hasValidNetworkInterface) {
NetworkInterface networkInterface = enumeration.nextElement();
Enumeration<InetAddress> inetAddress = networkInterface
.getInetAddresses();
while (inetAddress.hasMoreElements()) {
InetAddress currentAddress = inetAddress.nextElement();
if (currentAddress instanceof Inet4Address
&& !currentAddress.isLoopbackAddress()) {
hasValidNetworkInterface = true;
netWorkInterfaceName = networkInterface.getName();
System.setProperty(
"spring.cloud.nacos.discovery.network-interface",
networkInterface.getName());
break;
}
}
}
}
catch (Exception e) {
}
}
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosAutoServiceRegistrationIpTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.discovery.ip=123.123.123.123" }, webEnvironment = RANDOM_PORT)
public class NacosAutoServiceRegistrationIpTests {
@Autowired
private NacosRegistration registration;
@Autowired
private NacosAutoServiceRegistration nacosAutoServiceRegistration;
@Autowired
private NacosDiscoveryProperties properties;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosRegistration was not created", registration);
assertNotNull("NacosDiscoveryProperties was not created", properties);
assertNotNull("NacosAutoServiceRegistration was not created",
nacosAutoServiceRegistration);
checkoutNacosDiscoveryServiceIP();
}
private void checkoutNacosDiscoveryServiceIP() {
assertEquals("NacosDiscoveryProperties service IP was wrong", "123.123.123.123",
registration.getHost());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@ -0,0 +1,88 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.cloud.alibaba.nacos.registry.NacosRegistration.MANAGEMENT_PORT;
import static org.springframework.cloud.alibaba.nacos.registry.NacosRegistration.MANAGEMENT_CONTEXT_PATH;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosAutoServiceRegistrationManagementPortTests.TestConfig.class, properties = {
"spring.application.name=myTestService1", "management.port=8888",
"management.context-path=/test-context-path",
"spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.discovery.port=8888" }, webEnvironment = RANDOM_PORT)
public class NacosAutoServiceRegistrationManagementPortTests {
@Autowired
private NacosRegistration registration;
@Autowired
private NacosAutoServiceRegistration nacosAutoServiceRegistration;
@Autowired
private NacosDiscoveryProperties properties;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosRegistration was not created", registration);
assertNotNull("NacosDiscoveryProperties was not created", properties);
assertNotNull("NacosAutoServiceRegistration was not created",
nacosAutoServiceRegistration);
checkoutNacosDiscoveryManagementData();
}
private void checkoutNacosDiscoveryManagementData() {
assertEquals("NacosDiscoveryProperties management port was wrong", "8888",
properties.getMetadata().get(MANAGEMENT_PORT));
assertEquals("NacosDiscoveryProperties management context path was wrong",
"/test-context-path",
properties.getMetadata().get(MANAGEMENT_CONTEXT_PATH));
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosAutoServiceRegistrationPortTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.discovery.port=8888" }, webEnvironment = RANDOM_PORT)
public class NacosAutoServiceRegistrationPortTests {
@Autowired
private NacosRegistration registration;
@Autowired
private NacosAutoServiceRegistration nacosAutoServiceRegistration;
@Autowired
private NacosDiscoveryProperties properties;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosRegistration was not created", registration);
assertNotNull("NacosDiscoveryProperties was not created", properties);
assertNotNull("NacosAutoServiceRegistration was not created",
nacosAutoServiceRegistration);
checkoutNacosDiscoveryServicePort();
}
private void checkoutNacosDiscoveryServicePort() {
assertEquals("NacosDiscoveryProperties service Port was wrong", 8888,
registration.getPort());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@ -0,0 +1,199 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos.registry;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.endpoint.NacosDiscoveryEndpoint;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosAutoServiceRegistrationTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.discovery.endpoint=test-endpoint",
"spring.cloud.nacos.discovery.namespace=test-namespace",
"spring.cloud.nacos.discovery.log-name=test-logName",
"spring.cloud.nacos.discovery.weight=2",
"spring.cloud.nacos.discovery.clusterName=test-cluster",
"spring.cloud.nacos.discovery.namingLoadCacheAtStart=true",
"spring.cloud.nacos.discovery.secure=true",
"spring.cloud.nacos.discovery.accessKey=test-accessKey",
"spring.cloud.nacos.discovery.secretKey=test-secretKey" }, webEnvironment = RANDOM_PORT)
public class NacosAutoServiceRegistrationTests {
@Autowired
private NacosRegistration registration;
@Autowired
private NacosAutoServiceRegistration nacosAutoServiceRegistration;
@LocalServerPort
private int port;
@Autowired
private NacosDiscoveryProperties properties;
@Autowired
private InetUtils inetUtils;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosRegistration was not created", registration);
assertNotNull("NacosDiscoveryProperties was not created", properties);
assertNotNull("NacosAutoServiceRegistration was not created",
nacosAutoServiceRegistration);
checkoutNacosDiscoveryServerAddr();
checkoutNacosDiscoveryEndpoint();
checkoutNacosDiscoveryNamespace();
checkoutNacosDiscoveryLogName();
checkoutNacosDiscoveryWeight();
checkoutNacosDiscoveryClusterName();
checkoutNacosDiscoveryCache();
checkoutNacosDiscoverySecure();
checkoutNacosDiscoveryAccessKey();
checkoutNacosDiscoverySecrectKey();
checkoutNacosDiscoveryServiceName();
checkoutNacosDiscoveryServiceIP();
checkoutNacosDiscoveryServicePort();
checkAutoRegister();
checkoutEndpoint();
}
private void checkAutoRegister() {
assertTrue("Nacos Auto Registration was not start",
nacosAutoServiceRegistration.isRunning());
}
private void checkoutNacosDiscoveryServerAddr() {
assertEquals("NacosDiscoveryProperties server address was wrong",
"127.0.0.1:8848", properties.getServerAddr());
}
private void checkoutNacosDiscoveryEndpoint() {
assertEquals("NacosDiscoveryProperties endpoint was wrong", "test-endpoint",
properties.getEndpoint());
}
private void checkoutNacosDiscoveryNamespace() {
assertEquals("NacosDiscoveryProperties namespace was wrong", "test-namespace",
properties.getNamespace());
}
private void checkoutNacosDiscoveryLogName() {
assertEquals("NacosDiscoveryProperties logName was wrong", "test-logName",
properties.getLogName());
}
private void checkoutNacosDiscoveryWeight() {
assertEquals(2, properties.getWeight(), 0.00000001);
}
private void checkoutNacosDiscoveryClusterName() {
assertEquals("NacosDiscoveryProperties cluster was wrong", "test-cluster",
properties.getClusterName());
}
private void checkoutNacosDiscoveryCache() {
assertEquals("NacosDiscoveryProperties naming load cache was wrong", "true",
properties.getNamingLoadCacheAtStart());
}
private void checkoutNacosDiscoverySecure() {
assertEquals("NacosDiscoveryProperties is secure was wrong", true,
properties.isSecure());
assertEquals("NacosDiscoveryProperties is secure was wrong", "true",
properties.getMetadata().get("secure"));
}
private void checkoutNacosDiscoveryAccessKey() {
assertEquals("NacosDiscoveryProperties is access key was wrong", "test-accessKey",
properties.getAccessKey());
}
private void checkoutNacosDiscoverySecrectKey() {
assertEquals("NacosDiscoveryProperties is secret key was wrong", "test-secretKey",
properties.getSecretKey());
}
private void checkoutNacosDiscoveryServiceName() {
assertEquals("NacosDiscoveryProperties service name was wrong", "myTestService1",
properties.getService());
}
private void checkoutNacosDiscoveryServiceIP() {
assertEquals("NacosDiscoveryProperties service IP was wrong",
inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(),
registration.getHost());
}
private void checkoutNacosDiscoveryServicePort() {
assertEquals("NacosDiscoveryProperties service Port was wrong", port,
registration.getPort());
}
private void checkoutEndpoint() throws Exception {
NacosDiscoveryEndpoint nacosDiscoveryEndpoint = new NacosDiscoveryEndpoint(
properties);
Map<String, Object> map = nacosDiscoveryEndpoint.invoke();
assertEquals(map.get("NacosDiscoveryProperties"), properties);
assertEquals(map.get("subscribe").toString(),
properties.namingServiceInstance().getSubscribeServices().toString());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@ -1,82 +0,0 @@
package org.springframework.cloud.alibaba.nacos.ribbon;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.client.config.IClientConfig;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author xiaojing
*/
public class NacosRibbonClientConfigurationTests {
private ConfigurableApplicationContext context;
@Before
public void setUp() throws Exception {
this.context = new SpringApplicationBuilder(NacosRibbonTestConfiguration.class,
NacosDiscoveryAutoConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
NacosRibbonClientConfiguration.class, RibbonNacosAutoConfiguration.class)
.web(false).run("--server.port=18080",
"--spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080",
"--spring.cloud.nacos.discovery.port=18080",
"--spring.cloud.nacos.discovery.service=myapp");
}
@Test
public void testProperties() {
NacosServerList serverList = context.getBean(NacosServerList.class);
assertThat(serverList.getServiceId()).isEqualTo("myapp");
}
@Configuration
@AutoConfigureBefore(value = { NacosDiscoveryAutoConfiguration.class })
static class NacosRibbonTestConfiguration {
@Bean
@ConditionalOnMissingBean
AutoServiceRegistrationProperties autoServiceRegistrationProperties() {
return new AutoServiceRegistrationProperties();
}
@Bean
IClientConfig iClientConfig() {
DefaultClientConfigImpl config = new DefaultClientConfigImpl();
config.setClientName("myapp");
return config;
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
InetUtils inetUtils() {
return new InetUtils(new InetUtilsProperties());
}
}
}

View File

@ -0,0 +1,175 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos.ribbon;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import org.junit.Test;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.cloud.alibaba.nacos.test.NacosMockTest.serviceInstance;
/**
* @author xiaojing
*/
public class NacosServerListTests {
@Test
@SuppressWarnings("unchecked")
public void testEmptyInstancesReturnsEmptyList() throws Exception {
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class);
NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
when(namingService.selectInstances(anyString(), eq(true))).thenReturn(null);
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
List<NacosServer> servers = serverList.getInitialListOfServers();
assertThat(servers).isEmpty();
}
@Test
@SuppressWarnings("unchecked")
public void testGetServers() throws Exception {
ArrayList<Instance> instances = new ArrayList<>();
instances.add(serviceInstance("test-service", false,
Collections.<String, String> emptyMap()));
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class);
NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
when(namingService.selectInstances(eq("test-service"), eq(true)))
.thenReturn(instances);
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
serverList.initWithNiwsConfig(clientConfig);
List<NacosServer> servers = serverList.getInitialListOfServers();
assertThat(servers).hasSize(1);
servers = serverList.getUpdatedListOfServers();
assertThat(servers).hasSize(1);
}
@Test
@SuppressWarnings("unchecked")
public void testGetServersWithInstanceStatus() throws Exception {
ArrayList<Instance> instances = new ArrayList<>();
HashMap<String, String> map1 = new HashMap<>();
map1.put("instanceNum", "1");
HashMap<String, String> map2 = new HashMap<>();
map2.put("instanceNum", "2");
instances.add(serviceInstance("test-service", false, map1));
instances.add(serviceInstance("test-service", true, map2));
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class);
NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
List<Instance> returnInstances = new LinkedList<>();
for (Instance instance : instances) {
if (instance.isHealthy()) {
returnInstances.add(instance);
}
}
when(namingService.selectInstances(eq("test-service"), eq(true)))
.thenReturn(returnInstances);
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
serverList.initWithNiwsConfig(clientConfig);
List<NacosServer> servers = serverList.getInitialListOfServers();
assertThat(servers).hasSize(1);
NacosServer nacosServer = servers.get(0);
assertThat(nacosServer.getMetaInfo().getInstanceId())
.isEqualTo(instances.get(1).getInstanceId());
assertThat(nacosServer.getMetadata()).isEqualTo(map2);
assertThat(nacosServer.getInstance().isHealthy()).isEqualTo(true);
assertThat(nacosServer.getInstance().getServiceName()).isEqualTo("test-service");
assertThat(nacosServer.getInstance().getMetadata().get("instanceNum"))
.isEqualTo("2");
}
@Test
public void testUpdateServers() throws Exception {
ArrayList<Instance> instances = new ArrayList<>();
HashMap<String, String> map = new HashMap<>();
map.put("instanceNum", "1");
instances.add(serviceInstance("test-service", true, map));
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class);
NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
List<Instance> returnInstances = new LinkedList<>();
for (Instance instance : instances) {
if (instance.isHealthy()) {
returnInstances.add(instance);
}
}
when(namingService.selectInstances(eq("test-service"), eq(true)))
.thenReturn(returnInstances);
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
serverList.initWithNiwsConfig(clientConfig);
List<NacosServer> servers = serverList.getUpdatedListOfServers();
assertThat(servers).hasSize(1);
assertThat(servers.get(0).getInstance().isHealthy()).isEqualTo(true);
assertThat(servers.get(0).getInstance().getMetadata().get("instanceNum"))
.isEqualTo("1");
}
}

View File

@ -0,0 +1,36 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos.test;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author xiaojing
*/
@Configuration
public class CommonTestConfig {
@Bean
@LoadBalanced
RestTemplate loadBalancedRestTemplate() {
return new RestTemplate();
}
}

View File

@ -0,0 +1,49 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos.test;
import java.util.Map;
import java.util.UUID;
import com.alibaba.nacos.api.naming.pojo.Instance;
/**
* @author xiaojing
*/
public class NacosMockTest {
public static Instance serviceInstance(String serviceName, boolean isHealthy,
Map<String, String> metadata) {
Instance instance = new Instance();
instance.setInstanceId(UUID.randomUUID().toString());
instance.setServiceName(serviceName);
instance.setHealthy(isHealthy);
instance.setMetadata(metadata);
return instance;
}
public static Instance serviceInstance(String serviceName, boolean isHealthy,
String host, int port, Map<String, String> metadata) {
Instance instance = new Instance();
instance.setIp(host);
instance.setPort(port);
instance.setServiceName(serviceName);
instance.setHealthy(isHealthy);
instance.setMetadata(metadata);
return instance;
}
}

View File

@ -86,7 +86,6 @@
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
<optional>true</optional>
</dependency>

View File

@ -16,7 +16,6 @@
package org.springframework.cloud.alibaba.sentinel.datasource.config;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.springframework.cloud.alibaba.sentinel.datasource.RuleType;
@ -37,7 +36,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
*/
public class AbstractDataSourceProperties {
@NotEmpty
@NotNull
private String dataType = "json";
@NotNull
private RuleType ruleType;

View File

@ -16,7 +16,7 @@
package org.springframework.cloud.alibaba.sentinel.datasource.config;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.ApolloDataSourceFactoryBean;
@ -28,9 +28,9 @@ import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.ApolloD
*/
public class ApolloDataSourceProperties extends AbstractDataSourceProperties {
@NotEmpty
@NotNull
private String namespaceName;
@NotEmpty
@NotNull
private String flowRulesKey;
private String defaultFlowRuleValue;

View File

@ -4,6 +4,8 @@ import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.springframework.util.ObjectUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
@ -19,12 +21,16 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
*/
public class DataSourcePropertiesConfiguration {
@Valid
private FileDataSourceProperties file;
@Valid
private NacosDataSourceProperties nacos;
@Valid
private ZookeeperDataSourceProperties zk;
@Valid
private ApolloDataSourceProperties apollo;
public DataSourcePropertiesConfiguration() {

View File

@ -18,7 +18,7 @@ package org.springframework.cloud.alibaba.sentinel.datasource.config;
import java.io.IOException;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.FileRefreshableDataSourceFactoryBean;
import org.springframework.util.ResourceUtils;
@ -32,7 +32,7 @@ import org.springframework.util.StringUtils;
*/
public class FileDataSourceProperties extends AbstractDataSourceProperties {
@NotEmpty
@NotNull
private String file;
private String charset = "utf-8";
private long recommendRefreshMs = 3000L;

View File

@ -16,7 +16,7 @@
package org.springframework.cloud.alibaba.sentinel.datasource.config;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.NacosDataSourceFactoryBean;
import org.springframework.util.StringUtils;
@ -31,10 +31,10 @@ public class NacosDataSourceProperties extends AbstractDataSourceProperties {
private String serverAddr;
@NotEmpty
@NotNull
private String groupId = "DEFAULT_GROUP";
@NotEmpty
@NotNull
private String dataId;
private String endpoint;

View File

@ -16,7 +16,7 @@
package org.springframework.cloud.alibaba.sentinel.datasource.config;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.ZookeeperDataSourceFactoryBean;
@ -32,7 +32,7 @@ public class ZookeeperDataSourceProperties extends AbstractDataSourceProperties
super(ZookeeperDataSourceFactoryBean.class.getName());
}
@NotEmpty
@NotNull
private String serverAddr;
private String path;

View File

@ -53,7 +53,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class SentinelConverter<T extends AbstractRule>
implements Converter<String, List<AbstractRule>> {
private static final Logger logger = LoggerFactory.getLogger(SentinelConverter.class);
private static final Logger log = LoggerFactory.getLogger(SentinelConverter.class);
private final ObjectMapper objectMapper;
@ -68,7 +68,7 @@ public abstract class SentinelConverter<T extends AbstractRule>
public List<AbstractRule> convert(String source) {
List<AbstractRule> ruleList = new ArrayList<>();
if (StringUtils.isEmpty(source)) {
logger.warn("converter can not convert rules because source is empty");
log.warn("converter can not convert rules because source is empty");
return ruleList;
}
try {

View File

@ -20,6 +20,8 @@ import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.validation.Valid;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.alibaba.sentinel.datasource.config.DataSourcePropertiesConfiguration;
import org.springframework.core.Ordered;
@ -55,6 +57,7 @@ public class SentinelProperties {
/**
* Configurations about datasource, like 'nacos', 'apollo', 'file', 'zookeeper'.
*/
@Valid
private Map<String, DataSourcePropertiesConfiguration> datasource = new TreeMap<>(
String.CASE_INSENSITIVE_ORDER);

View File

@ -42,7 +42,7 @@ import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
@EnableConfigurationProperties(SentinelProperties.class)
public class SentinelWebAutoConfiguration {
private static final Logger logger = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(SentinelWebAutoConfiguration.class);
@Autowired
@ -65,7 +65,7 @@ public class SentinelWebAutoConfiguration {
Filter filter = new CommonFilter();
registration.setFilter(filter);
registration.setOrder(filterConfig.getOrder());
logger.info("[Sentinel Starter] register Sentinel with urlPatterns: {}.",
log.info("[Sentinel Starter] register Sentinel with urlPatterns: {}.",
filterConfig.getUrlPatterns());
return registration;

View File

@ -53,7 +53,7 @@ import com.alibaba.csp.sentinel.slots.block.BlockException;
*/
public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProcessor {
private static final Logger logger = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(SentinelBeanPostProcessor.class);
private final ApplicationContext applicationContext;
@ -100,14 +100,14 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
return;
}
if (blockClass != void.class && StringUtils.isEmpty(blockMethod)) {
logger.error(
log.error(
"{} class attribute exists but {} method attribute is not exists in bean[{}]",
type, type, beanName);
throw new IllegalArgumentException(type + " class attribute exists but "
+ type + " method attribute is not exists in bean[" + beanName + "]");
}
else if (blockClass == void.class && !StringUtils.isEmpty(blockMethod)) {
logger.error(
log.error(
"{} method attribute exists but {} class attribute is not exists in bean[{}]",
type, type, beanName);
throw new IllegalArgumentException(type + " method attribute exists but "
@ -123,7 +123,7 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
String argsStr = Arrays.toString(argList.toArray());
Method foundMethod = ClassUtils.getStaticMethod(blockClass, blockMethod, args);
if (foundMethod == null) {
logger.error(
log.error(
"{} static method can not be found in bean[{}]. The right method signature is {}#{}{}, please check your class name, method name and arguments",
type, beanName, blockClass.getName(), blockMethod, argsStr);
throw new IllegalArgumentException(type
@ -134,7 +134,7 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
}
if (!ClientHttpResponse.class.isAssignableFrom(foundMethod.getReturnType())) {
logger.error(
log.error(
"{} method return value in bean[{}] is not ClientHttpResponse: {}#{}{}",
type, beanName, blockClass.getName(), blockMethod, argsStr);
throw new IllegalArgumentException(type + " method return value in bean["

View File

@ -52,7 +52,7 @@ import com.alibaba.csp.sentinel.slots.block.AbstractRule;
*/
public class SentinelDataSourceHandler implements SmartInitializingSingleton {
private static final Logger logger = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(SentinelDataSourceHandler.class);
private List<String> dataTypeList = Arrays.asList("json", "xml");
@ -78,7 +78,7 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
try {
List<String> validFields = dataSourceProperties.getValidField();
if (validFields.size() != 1) {
logger.error("[Sentinel Starter] DataSource " + dataSourceName
log.error("[Sentinel Starter] DataSource " + dataSourceName
+ " multi datasource active and won't loaded: "
+ dataSourceProperties.getValidField());
return;
@ -90,7 +90,7 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
+ validFields.get(0) + "-datasource");
}
catch (Exception e) {
logger.error("[Sentinel Starter] DataSource " + dataSourceName
log.error("[Sentinel Starter] DataSource " + dataSourceName
+ " build error: " + e.getMessage(), e);
}
}
@ -109,8 +109,8 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
}
}
catch (IllegalAccessException e) {
logger.error("[Sentinel Starter] DataSource " + dataSourceName
+ " field: " + field.getName() + " invoke error");
log.error("[Sentinel Starter] DataSource " + dataSourceName + " field: "
+ field.getName() + " invoke error");
throw new RuntimeException("[Sentinel Starter] DataSource "
+ dataSourceName + " field: " + field.getName() + " invoke error",
e);
@ -157,7 +157,7 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
builder.addPropertyReference("converter", customConvertBeanName);
}
catch (ClassNotFoundException e) {
logger.error("[Sentinel Starter] DataSource " + dataSourceName
log.error("[Sentinel Starter] DataSource " + dataSourceName
+ " handle "
+ dataSourceProperties.getClass().getSimpleName()
+ " error, class name: "
@ -217,14 +217,14 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
ruleConfig = dataSource.loadConfig();
}
catch (Exception e) {
logger.error("[Sentinel Starter] DataSource " + dataSourceName
log.error("[Sentinel Starter] DataSource " + dataSourceName
+ " loadConfig error: " + e.getMessage(), e);
return;
}
if (ruleConfig instanceof List) {
List convertedRuleList = (List) ruleConfig;
if (CollectionUtils.isEmpty(convertedRuleList)) {
logger.warn("[Sentinel Starter] DataSource {} rule list is empty.",
log.warn("[Sentinel Starter] DataSource {} rule list is empty.",
dataSourceName);
return;
}
@ -235,23 +235,23 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
}
}
if (matchCount == 0) {
logger.error("[Sentinel Starter] DataSource {} none rules are {} type.",
log.error("[Sentinel Starter] DataSource {} none rules are {} type.",
dataSourceName, ruleClass.getSimpleName());
throw new IllegalArgumentException("[Sentinel Starter] DataSource "
+ dataSourceName + " none rules are " + ruleClass.getSimpleName()
+ " type.");
}
else if (matchCount != convertedRuleList.size()) {
logger.warn("[Sentinel Starter] DataSource {} all rules are not {} type.",
log.warn("[Sentinel Starter] DataSource {} all rules are not {} type.",
dataSourceName, ruleClass.getSimpleName());
}
else {
logger.info("[Sentinel Starter] DataSource {} load {} {}", dataSourceName,
log.info("[Sentinel Starter] DataSource {} load {} {}", dataSourceName,
convertedRuleList.size(), ruleClass.getSimpleName());
}
}
else {
logger.error("[Sentinel Starter] DataSource " + dataSourceName
log.error("[Sentinel Starter] DataSource " + dataSourceName
+ " rule class is not List<" + ruleClass.getSimpleName()
+ ">. Class: " + ruleConfig.getClass());
throw new IllegalArgumentException("[Sentinel Starter] DataSource "

View File

@ -21,8 +21,6 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.alibaba.sentinel.annotation.SentinelRestTemplate;
import org.springframework.cloud.alibaba.sentinel.rest.SentinelClientHttpResponse;
import org.springframework.http.HttpRequest;
@ -44,9 +42,6 @@ import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
*/
public class SentinelProtectInterceptor implements ClientHttpRequestInterceptor {
private static final Logger logger = LoggerFactory
.getLogger(SentinelProtectInterceptor.class);
private final SentinelRestTemplate sentinelRestTemplate;
public SentinelProtectInterceptor(SentinelRestTemplate sentinelRestTemplate) {

View File

@ -11,6 +11,7 @@
</parent>
<artifactId>spring-cloud-alicloud-acm</artifactId>
<name>Spring Cloud Alibaba Cloud ACM</name>
<dependencies>
@ -43,6 +44,7 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
@ -65,6 +67,19 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.7.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.7.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -27,29 +27,29 @@ import java.util.Map;
*/
public class AcmPropertySource extends MapPropertySource {
private final String dataId;
private final String dataId;
private final Date timestamp;
private final Date timestamp;
private final boolean groupLevel;
private final boolean groupLevel;
AcmPropertySource(String dataId, Map<String, Object> source, Date timestamp,
boolean groupLevel) {
super(dataId, source);
this.dataId = dataId;
this.timestamp = timestamp;
this.groupLevel = groupLevel;
}
AcmPropertySource(String dataId, Map<String, Object> source, Date timestamp,
boolean groupLevel) {
super(dataId, source);
this.dataId = dataId;
this.timestamp = timestamp;
this.groupLevel = groupLevel;
}
public String getDataId() {
return dataId;
}
public String getDataId() {
return dataId;
}
public Date getTimestamp() {
return timestamp;
}
public Date getTimestamp() {
return timestamp;
}
public boolean isGroupLevel() {
return groupLevel;
}
public boolean isGroupLevel() {
return groupLevel;
}
}

View File

@ -33,64 +33,68 @@ import java.util.*;
*/
class AcmPropertySourceBuilder {
private Logger logger = LoggerFactory.getLogger(AcmPropertySourceBuilder.class);
private Logger log = LoggerFactory.getLogger(AcmPropertySourceBuilder.class);
/**
* 传入 ACM DataId groupID获取到解析后的 AcmProperty 对象
*
* @param dataId
* @param diamondGroup
* @param groupLevel
* @return
*/
AcmPropertySource build(String dataId, String diamondGroup, boolean groupLevel) {
Properties properties = loadDiamondData(dataId, diamondGroup);
if (properties == null) {
return null;
}
return new AcmPropertySource(dataId, toMap(properties), new Date(), groupLevel);
}
/**
* 传入 ACM DataId groupID获取到解析后的 AcmProperty 对象
*
* @param dataId
* @param diamondGroup
* @param groupLevel
* @return
*/
AcmPropertySource build(String dataId, String diamondGroup, boolean groupLevel) {
Properties properties = loadDiamondData(dataId, diamondGroup);
if (properties == null) {
return null;
}
return new AcmPropertySource(dataId, toMap(properties), new Date(), groupLevel);
}
private Properties loadDiamondData(String dataId, String diamondGroup) {
try {
String data = ConfigService.getConfig(dataId, diamondGroup, 3000L);
if (StringUtils.isEmpty(data)) {
return null;
}
if (dataId.endsWith(".properties")) {
Properties properties = new Properties();
logger.info(String.format("Loading acm data, dataId: '%s', group: '%s'",
dataId, diamondGroup));
properties.load(new StringReader(data));
return properties;
} else if (dataId.endsWith(".yaml") || dataId.endsWith(".yml")) {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(new ByteArrayResource(data.getBytes()));
return yamlFactory.getObject();
}
} catch (Exception e) {
if (e instanceof ConfigException) {
logger.error("DIAMOND-100500:" + dataId + ", " + e.toString(), e);
} else {
logger.error("DIAMOND-100500:" + dataId, e);
}
}
return null;
}
private Properties loadDiamondData(String dataId, String diamondGroup) {
try {
String data = ConfigService.getConfig(dataId, diamondGroup, 3000L);
if (StringUtils.isEmpty(data)) {
return null;
}
if (dataId.endsWith(".properties")) {
Properties properties = new Properties();
log.info(String.format("Loading acm data, dataId: '%s', group: '%s'",
dataId, diamondGroup));
properties.load(new StringReader(data));
return properties;
}
else if (dataId.endsWith(".yaml") || dataId.endsWith(".yml")) {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(new ByteArrayResource(data.getBytes()));
return yamlFactory.getObject();
}
}
catch (Exception e) {
if (e instanceof ConfigException) {
log.error("DIAMOND-100500:" + dataId + ", " + e.toString(), e);
}
else {
log.error("DIAMOND-100500:" + dataId, e);
}
}
return null;
}
@SuppressWarnings("unchecked")
private Map<String, Object> toMap(Properties properties) {
Map<String, Object> result = new HashMap<>();
Enumeration<String> keys = (Enumeration<String>)properties.propertyNames();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
Object value = properties.getProperty(key);
if (value != null) {
result.put(key, ((String)value).trim());
} else {
result.put(key, null);
}
}
return result;
}
@SuppressWarnings("unchecked")
private Map<String, Object> toMap(Properties properties) {
Map<String, Object> result = new HashMap<>();
Enumeration<String> keys = (Enumeration<String>) properties.propertyNames();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
Object value = properties.getProperty(key);
if (value != null) {
result.put(key, ((String) value).trim());
}
else {
result.put(key, null);
}
}
return result;
}
}

View File

@ -42,6 +42,8 @@ public class AcmPropertySourceLocator implements PropertySourceLocator {
CompositePropertySource compositePropertySource = new CompositePropertySource(
DIAMOND_PROPERTY_SOURCE_NAME);
acmIntegrationProperties.setActiveProfiles(environment.getActiveProfiles());
for (String dataId : acmIntegrationProperties.getGroupConfigurationDataIds()) {
loadDiamondDataIfPresent(compositePropertySource, dataId,
acmIntegrationProperties.getAcmProperties().getGroup(), true);

View File

@ -1,40 +0,0 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alicloud.acm.diagnostics.analyzer;
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer;
import org.springframework.boot.diagnostics.FailureAnalysis;
/**
* A {@code FailureAnalyzer} that performs analysis of failures caused by a
* {@code DiamondConnectionFailureException}.
*
* @author juven.xuxb, 07/11/2016.
*/
public class DiamondConnectionFailureAnalyzer
extends AbstractFailureAnalyzer<DiamondConnectionFailureException> {
@Override
protected FailureAnalysis analyze(Throwable rootFailure,
DiamondConnectionFailureException cause) {
return new FailureAnalysis(
"Application failed to connect to Diamond, unable to access http://"
+ cause.getDomain() + ":" + cause.getPort()
+ "/diamond-server/diamond",
"config the right endpoint", cause);
}
}

View File

@ -1,52 +0,0 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alicloud.acm.diagnostics.analyzer;
/**
* A {@code DiamondConnectionFailureException} is thrown when the application fails to
* connect to Diamond Server.
*
* @author juven.xuxb, 07/11/2016.
*/
public class DiamondConnectionFailureException extends RuntimeException {
private final String domain;
private final String port;
public DiamondConnectionFailureException(String domain, String port, String message) {
super(message);
this.domain = domain;
this.port = port;
}
public DiamondConnectionFailureException(String domain, String port, String message,
Throwable cause) {
super(message, cause);
this.domain = domain;
this.port = port;
}
String getDomain() {
return domain;
}
String getPort() {
return port;
}
}

View File

@ -33,39 +33,40 @@ import java.util.List;
*/
public class AcmHealthIndicator extends AbstractHealthIndicator {
private final AcmProperties acmProperties;
private final AcmProperties acmProperties;
private final AcmPropertySourceRepository acmPropertySourceRepository;
private final AcmPropertySourceRepository acmPropertySourceRepository;
private final List<String> dataIds;
private final List<String> dataIds;
public AcmHealthIndicator(AcmProperties acmProperties,
AcmPropertySourceRepository acmPropertySourceRepository) {
this.acmProperties = acmProperties;
this.acmPropertySourceRepository = acmPropertySourceRepository;
public AcmHealthIndicator(AcmProperties acmProperties,
AcmPropertySourceRepository acmPropertySourceRepository) {
this.acmProperties = acmProperties;
this.acmPropertySourceRepository = acmPropertySourceRepository;
this.dataIds = new ArrayList<>();
for (AcmPropertySource acmPropertySource : this.acmPropertySourceRepository
.getAll()) {
this.dataIds.add(acmPropertySource.getDataId());
}
}
this.dataIds = new ArrayList<>();
for (AcmPropertySource acmPropertySource : this.acmPropertySourceRepository
.getAll()) {
this.dataIds.add(acmPropertySource.getDataId());
}
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
for (String dataId : dataIds) {
try {
String config = ConfigService.getConfig(dataId, acmProperties.getGroup(),
acmProperties.getTimeout());
if (StringUtils.isEmpty(config)) {
builder.down().withDetail(String.format("dataId: '%s', group: '%s'",
dataId, acmProperties.getGroup()), "config is empty");
}
} catch (Exception e) {
builder.down().withDetail(String.format("dataId: '%s', group: '%s'",
dataId, acmProperties.getGroup()), e.getMessage());
}
}
builder.up().withDetail("dataIds", dataIds);
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
for (String dataId : dataIds) {
try {
String config = ConfigService.getConfig(dataId, acmProperties.getGroup(),
acmProperties.getTimeout());
if (StringUtils.isEmpty(config)) {
builder.down().withDetail(String.format("dataId: '%s', group: '%s'",
dataId, acmProperties.getGroup()), "config is empty");
}
}
catch (Exception e) {
builder.down().withDetail(String.format("dataId: '%s', group: '%s'",
dataId, acmProperties.getGroup()), e.getMessage());
}
}
builder.up().withDetail("dataIds", dataIds);
}
}

View File

@ -28,7 +28,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.alicloud.acm.AcmPropertySourceRepository;
import org.springframework.cloud.alicloud.acm.bootstrap.AcmPropertySource;
import org.springframework.cloud.alicloud.context.acm.AcmIntegrationProperties;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.endpoint.event.RefreshEvent;
@ -50,7 +49,7 @@ import com.alibaba.edas.acm.listener.ConfigChangeListener;
public class AcmContextRefresher
implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {
private Logger logger = LoggerFactory.getLogger(AcmContextRefresher.class);
private Logger log = LoggerFactory.getLogger(AcmContextRefresher.class);
private final ContextRefresher contextRefresher;
@ -103,7 +102,7 @@ public class AcmContextRefresher
}
catch (NoSuchAlgorithmException
| UnsupportedEncodingException e) {
logger.warn("unable to get md5 for dataId: " + dataId, e);
log.warn("unable to get md5 for dataId: " + dataId, e);
}
}
refreshHistory.add(dataId, md5);

View File

@ -4,6 +4,3 @@ org.springframework.cloud.alicloud.acm.bootstrap.AcmPropertySourceLocator
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.alicloud.acm.AcmAutoConfiguration,\
org.springframework.cloud.alicloud.acm.endpoint.AcmEndpointAutoConfiguration
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.cloud.alicloud.acm.diagnostics.analyzer.DiamondConnectionFailureAnalyzer

View File

@ -0,0 +1,195 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alicloud.acm;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import com.alibaba.edas.acm.ConfigService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.api.support.MethodProxy;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alicloud.acm.bootstrap.AcmPropertySourceLocator;
import org.springframework.cloud.alicloud.acm.endpoint.AcmEndpointAutoConfiguration;
import org.springframework.cloud.alicloud.context.acm.AcmContextBootstrapConfiguration;
import org.springframework.cloud.alicloud.context.acm.AcmIntegrationProperties;
import org.springframework.cloud.alicloud.context.acm.AcmProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ ConfigService.class })
@SpringBootTest(classes = AcmConfigurationTests.TestConfig.class, properties = {
"spring.application.name=test-name", "spring.profiles.active=dev,test",
"spring.cloud.alicloud.acm.server-list=127.0.0.1",
"spring.cloud.alicloud.acm.server-port=8848",
"spring.cloud.alicloud.acm.endpoint=test-endpoint",
"spring.cloud.alicloud.acm.namespace=test-namespace",
"spring.cloud.alicloud.acm.timeout=1000",
"spring.cloud.alicloud.acm.group=test-group",
"spring.cloud.alicloud.acm.refresh-enabled=false",
"spring.cloud.alicloud.acm.file-extension=properties" }, webEnvironment = NONE)
public class AcmConfigurationTests {
static {
try {
Method method = PowerMockito.method(ConfigService.class, "getConfig",
String.class, String.class, long.class);
MethodProxy.proxy(method, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if ("test-name.properties".equals(args[0])
&& "test-group".equals(args[1])) {
return "user.name=hello\nuser.age=12";
}
if ("test-name-dev.properties".equals(args[0])
&& "test-group".equals(args[1])) {
return "user.name=dev";
}
return "";
}
});
}
catch (Exception ignore) {
ignore.printStackTrace();
}
}
@Autowired
private Environment environment;
@Autowired
private AcmPropertySourceLocator locator;
@Autowired
private AcmIntegrationProperties integrationProperties;
@Autowired
private AcmProperties properties;
@Test
public void contextLoads() throws Exception {
assertNotNull("AcmPropertySourceLocator was not created", locator);
assertNotNull("AcmProperties was not created", properties);
assertNotNull("AcmIntegrationProperties was not created", integrationProperties);
checkoutAcmServerAddr();
checkoutAcmServerPort();
checkoutAcmEndpoint();
checkoutAcmNamespace();
checkoutAcmGroup();
checkoutAcmFileExtension();
checkoutAcmTimeout();
checkoutAcmProfiles();
checkoutAcmRefreshEnabled();
checkoutDataLoad();
checkoutProfileDataLoad();
}
private void checkoutAcmServerAddr() {
assertEquals("AcmProperties server address is wrong", "127.0.0.1",
properties.getServerList());
}
private void checkoutAcmServerPort() {
assertEquals("AcmProperties server port is wrong", "8848",
properties.getServerPort());
}
private void checkoutAcmEndpoint() {
assertEquals("AcmProperties endpoint is wrong", "test-endpoint",
properties.getEndpoint());
}
private void checkoutAcmNamespace() {
assertEquals("AcmProperties namespace is wrong", "test-namespace",
properties.getNamespace());
}
private void checkoutAcmGroup() {
assertEquals("AcmProperties' group is wrong", "test-group",
properties.getGroup());
}
private void checkoutAcmFileExtension() {
assertEquals("AcmProperties' file extension is wrong", "properties",
properties.getFileExtension());
}
private void checkoutAcmTimeout() {
assertEquals("AcmProperties' timeout is wrong", 1000, properties.getTimeout());
}
private void checkoutAcmRefreshEnabled() {
assertEquals("AcmProperties' refresh enabled is wrong", false,
properties.isRefreshEnabled());
}
private void checkoutAcmProfiles() {
assertArrayEquals("AcmProperties' profiles is wrong",
new String[] { "dev", "test" },
integrationProperties.getActiveProfiles());
}
private void checkoutDataLoad() {
Assert.assertEquals(environment.getProperty("user.age"), "12");
}
private void checkoutProfileDataLoad() {
Assert.assertEquals(environment.getProperty("user.name"), "dev");
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class,
AcmAutoConfiguration.class, AcmContextBootstrapConfiguration.class })
public static class TestConfig {
}
}

View File

@ -0,0 +1,98 @@
/*
* Copyright (C) 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alicloud.acm;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.api.support.MethodProxy;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alicloud.acm.endpoint.AcmEndpointAutoConfiguration;
import org.springframework.cloud.alicloud.context.acm.AcmContextBootstrapConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import com.alibaba.edas.acm.ConfigService;
/**
* @author xiaojing
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ ConfigService.class })
@SpringBootTest(classes = AcmFileExtensionTest.TestConfig.class, properties = {
"spring.application.name=test-name",
"spring.cloud.alicloud.acm.server-list=127.0.0.1",
"spring.cloud.alicloud.acm.server-port=8080",
"spring.cloud.alicloud.acm.file-extension=yaml" }, webEnvironment = NONE)
public class AcmFileExtensionTest {
static {
try {
Method method = PowerMockito.method(ConfigService.class, "getConfig",
String.class, String.class, long.class);
MethodProxy.proxy(method, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if ("test-name.yaml".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "user:\n name: hello\n age: 12";
}
return "";
}
});
}
catch (Exception ignore) {
ignore.printStackTrace();
}
}
@Autowired
private Environment environment;
@Test
public void contextLoads() throws Exception {
Assert.assertEquals(environment.getProperty("user.name"), "hello");
Assert.assertEquals(environment.getProperty("user.age"), "12");
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class,
AcmAutoConfiguration.class, AcmContextBootstrapConfiguration.class })
public static class TestConfig {
}
}

View File

@ -0,0 +1,106 @@
/*
* Copyright (C) 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alicloud.acm;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import com.alibaba.edas.acm.ConfigService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.api.support.MethodProxy;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alicloud.acm.endpoint.AcmEndpointAutoConfiguration;
import org.springframework.cloud.alicloud.context.acm.AcmContextBootstrapConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
/**
* @author xiaojing
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ ConfigService.class })
@SpringBootTest(classes = AcmGroupConfigurationTest.TestConfig.class, properties = {
"spring.application.name=test-name", "spring.application.group=com.test.hello",
"spring.cloud.alicloud.acm.server-list=127.0.0.1",
"spring.cloud.alicloud.acm.server-port=8080",
"spring.cloud.alicloud.acm.timeout=1000",
"spring.cloud.alicloud.acm.group=test-group" }, webEnvironment = NONE)
public class AcmGroupConfigurationTest {
static {
try {
Method method = PowerMockito.method(ConfigService.class, "getConfig",
String.class, String.class, long.class);
MethodProxy.proxy(method, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if ("com.test:application.properties".equals(args[0])
&& "test-group".equals(args[1])) {
return "com.test.value=com.test\ntest.priority=1";
}
if ("com.test.hello:application.properties".equals(args[0])
&& "test-group".equals(args[1])) {
return "com.test.hello.value=com.test.hello\ntest.priority=2";
}
return "";
}
});
}
catch (Exception ignore) {
ignore.printStackTrace();
}
}
@Autowired
private Environment environment;
@Test
public void contextLoads() throws Exception {
Assert.assertEquals(environment.getProperty("com.test.value"), "com.test");
Assert.assertEquals(environment.getProperty("test.priority"), "2");
Assert.assertEquals(environment.getProperty("com.test.hello.value"),
"com.test.hello");
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class,
AcmAutoConfiguration.class, AcmContextBootstrapConfiguration.class })
public static class TestConfig {
}
}

View File

@ -0,0 +1,148 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alicloud.acm.endpoint;
import static org.junit.Assert.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.api.support.MethodProxy;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health.Builder;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alicloud.acm.AcmAutoConfiguration;
import org.springframework.cloud.alicloud.acm.AcmPropertySourceRepository;
import org.springframework.cloud.alicloud.acm.refresh.AcmRefreshHistory;
import org.springframework.cloud.alicloud.context.acm.AcmContextBootstrapConfiguration;
import org.springframework.cloud.alicloud.context.acm.AcmProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.alibaba.edas.acm.ConfigService;
/**
* @author xiaojing
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ ConfigService.class })
@SpringBootTest(classes = AcmEndpointTests.TestConfig.class, properties = {
"spring.application.name=test-name",
"spring.cloud.alicloud.acm.server-list=127.0.0.1",
"spring.cloud.alicloud.acm.server-port=8848",
"spring.cloud.alicloud.acm.file-extension=properties" }, webEnvironment = NONE)
public class AcmEndpointTests {
static {
try {
Method method = PowerMockito.method(ConfigService.class, "getConfig",
String.class, String.class, long.class);
MethodProxy.proxy(method, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if ("test-name.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "user.name=hello\nuser.age=12";
}
return "";
}
});
}
catch (Exception ignore) {
ignore.printStackTrace();
}
}
@Autowired
private AcmProperties properties;
@Autowired
private AcmRefreshHistory refreshHistory;
@Autowired
private AcmPropertySourceRepository propertySourceRepository;
@Autowired
private AcmPropertySourceRepository acmPropertySourceRepository;
@Test
public void contextLoads() throws Exception {
checkoutEndpoint();
checkoutAcmHealthIndicator();
}
private void checkoutAcmHealthIndicator() {
try {
Builder builder = new Builder();
AcmHealthIndicator healthIndicator = new AcmHealthIndicator(properties,
acmPropertySourceRepository);
healthIndicator.doHealthCheck(builder);
Builder builder1 = new Builder();
List<String> dataIds = new ArrayList<>();
dataIds.add("test-name.properties");
builder1.up().withDetail("dataIds", dataIds);
Assert.assertTrue(builder.build().equals(builder1.build()));
}
catch (Exception ignoreE) {
}
}
private void checkoutEndpoint() throws Exception {
AcmEndpoint acmEndpoint = new AcmEndpoint(properties, refreshHistory,
propertySourceRepository);
Map<String, Object> map = acmEndpoint.invoke();
assertEquals(map.get("config"), properties);
assertEquals(((Map) map.get("runtime")).get("refreshHistory"),
refreshHistory.getRecords());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class,
AcmAutoConfiguration.class, AcmContextBootstrapConfiguration.class })
public static class TestConfig {
}
}

View File

@ -16,6 +16,7 @@
package org.springframework.cloud.alicloud.ans;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@ -26,7 +27,7 @@ import org.springframework.cloud.alicloud.ans.registry.AnsAutoServiceRegistratio
import org.springframework.cloud.alicloud.ans.registry.AnsRegistration;
import org.springframework.cloud.alicloud.ans.registry.AnsServiceRegistry;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@ -42,8 +43,8 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnClass(name = "org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent")
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
@ConditionalOnAnsEnabled
@AutoConfigureBefore({ AutoServiceRegistrationAutoConfiguration.class,
AnsDiscoveryClientAutoConfiguration.class })
@AutoConfigureBefore(AnsDiscoveryClientAutoConfiguration.class)
@AutoConfigureAfter(AutoServiceRegistrationConfiguration.class)
public class AnsAutoConfiguration {
@Bean

View File

@ -18,8 +18,8 @@ package org.springframework.cloud.alicloud.ans.endpoint;
import com.alibaba.ans.core.NamingService;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
@ -34,7 +34,7 @@ import java.util.Set;
*/
public class AnsEndpoint extends AbstractEndpoint<Map<String, Object>> {
private static final Log log = LogFactory.getLog(AnsEndpoint.class);
private static final Logger log = LoggerFactory.getLogger(AnsEndpoint.class);
private AnsProperties ansProperties;

View File

@ -1,7 +1,7 @@
package org.springframework.cloud.alicloud.ans.migrate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import java.util.Map;
@ -13,7 +13,7 @@ import java.util.concurrent.ConcurrentMap;
public class MigrateEndpoint
extends AbstractEndpoint<Map<String, ConcurrentMap<String, ServerWrapper>>> {
private static final Log log = LogFactory.getLog(MigrateEndpoint.class);
private static final Logger log = LoggerFactory.getLogger(MigrateEndpoint.class);
public MigrateEndpoint() {
super("migrate");

View File

@ -1,7 +1,7 @@
package org.springframework.cloud.alicloud.ans.migrate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
@ -10,7 +10,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
*/
public class MigrateOnConditionClass extends MigrateOnCondition {
protected static final Log log = LogFactory.getLog(MigrateOnConditionClass.class);
private static final Logger log = LoggerFactory
.getLogger(MigrateOnConditionClass.class);
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

View File

@ -1,7 +1,7 @@
package org.springframework.cloud.alicloud.ans.migrate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
@ -9,8 +9,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
* @author pbting
*/
public class MigrateOnConditionMissingClass extends MigrateOnConditionClass {
protected static final Log log = LogFactory
.getLog(MigrateOnConditionMissingClass.class);
private static final Logger log = LoggerFactory
.getLogger(MigrateOnConditionMissingClass.class);
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

View File

@ -7,8 +7,8 @@ import com.netflix.loadbalancer.ServerList;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.ProxyFactory;
import java.util.*;
@ -20,7 +20,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
*/
final class MigrateProxyManager {
private final static Log log = LogFactory.getLog(MigrateProxyManager.class);
private static final Logger log = LoggerFactory.getLogger(MigrateProxyManager.class);
private final static AtomicBoolean IS_PROXY = new AtomicBoolean(true);

View File

@ -7,8 +7,8 @@ import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.context.named.NamedContextFactory;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.context.ApplicationListener;
@ -22,7 +22,8 @@ import com.netflix.loadbalancer.ILoadBalancer;
*/
@Component
public class MigrateRefreshEventListener implements ApplicationListener<RefreshEvent> {
private final static Log log = LogFactory.getLog(MigrateRefreshEventListener.class);
private static final Logger log = LoggerFactory
.getLogger(MigrateRefreshEventListener.class);
private final static int CHECK_INTERVAL = 1;

View File

@ -1,7 +1,7 @@
package org.springframework.cloud.alicloud.ans.migrate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.config.BeanPostProcessor;
@ -16,7 +16,7 @@ import com.netflix.loadbalancer.ServerList;
public class MigrateRibbonBeanPostProcessor
implements BeanPostProcessor, BeanClassLoaderAware {
protected static final Log log = LogFactory.getLog(MigrateOnCondition.class);
private static final Logger log = LoggerFactory.getLogger(MigrateOnCondition.class);
private ClassLoader classLoader;
private IClientConfig clientConfig;

View File

@ -2,8 +2,8 @@ package org.springframework.cloud.alicloud.ans.migrate;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.alicloud.ans.registry.AnsRegistration;
import org.springframework.cloud.alicloud.ans.registry.AnsServiceRegistry;
@ -19,7 +19,8 @@ import org.springframework.stereotype.Component;
@Component
public class MigrateServiceRegistry {
private static final Log log = LogFactory.getLog(MigrateServiceRegistry.class);
private static final Logger log = LoggerFactory
.getLogger(MigrateServiceRegistry.class);
private AtomicBoolean running = new AtomicBoolean(false);

View File

@ -4,8 +4,8 @@ import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.Server;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.alicloud.ans.ribbon.AnsServer;
import org.springframework.cloud.alicloud.ans.ribbon.AnsServerList;
@ -21,7 +21,8 @@ import java.util.concurrent.atomic.AtomicLong;
*/
class ServerListInvocationHandler implements MethodInterceptor {
private final static Log log = LogFactory.getLog(ServerListInvocationHandler.class);
private static final Logger log = LoggerFactory
.getLogger(ServerListInvocationHandler.class);
private final static ConcurrentMap<String, AnsServerList> SERVER_LIST_CONCURRENT_MAP = new ConcurrentHashMap<>();

View File

@ -16,8 +16,8 @@
package org.springframework.cloud.alicloud.ans.registry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
@ -35,7 +35,8 @@ import org.springframework.util.StringUtils;
public class AnsAutoServiceRegistration
extends AbstractAutoServiceRegistration<AnsRegistration> {
private static final Log log = LogFactory.getLog(AnsAutoServiceRegistration.class);
private static final Logger log = LoggerFactory
.getLogger(AnsAutoServiceRegistration.class);
private AnsRegistration registration;
@ -115,11 +116,11 @@ public class AnsAutoServiceRegistration
@Override
protected int getConfiguredPort() {
return registration.getPort();
return this.getPort().get();
}
@Override
protected void setConfiguredPort(int port) {
this.registration.setPort(port);
this.getPort().set(port);
}
}

View File

@ -19,8 +19,8 @@ package org.springframework.cloud.alicloud.ans.registry;
import com.alibaba.ans.core.NamingService;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.ipms.NodeReactor;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import java.util.ArrayList;
@ -32,7 +32,7 @@ import java.util.Map;
*/
public class AnsServiceRegistry implements ServiceRegistry<AnsRegistration> {
private static Log log = LogFactory.getLog(AnsServiceRegistry.class);
private static final Logger log = LoggerFactory.getLogger(AnsServiceRegistry.class);
private static final String SEPARATOR = ",";

View File

@ -88,6 +88,10 @@ public class AcmIntegrationProperties {
this.activeProfiles = activeProfiles;
}
public String[] getActiveProfiles() {
return activeProfiles;
}
public void setAcmProperties(AcmProperties acmProperties) {
this.acmProperties = acmProperties;
}

View File

@ -15,14 +15,15 @@
*/
package org.springframework.cloud.alicloud.context.nacos;
import com.alibaba.cloud.context.edas.EdasChangeOrderConfiguration;
import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.cloud.alicloud.context.listener.AbstractOnceApplicationListener;
import java.util.Properties;
import com.alibaba.cloud.context.edas.EdasChangeOrderConfiguration;
import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory;
/**
* @author pbting
@ -52,7 +53,7 @@ public class NacosDiscoveryParameterInitListener
}
// initialize nacos configuration
Properties properties = System.getProperties();
properties.setProperty("spring.cloud.nacos.discovery.server-mode", "EDAS");
// step 1: set some properties for spring cloud alibaba nacos discovery
properties.setProperty("spring.cloud.nacos.discovery.server-addr", "");
properties.setProperty("spring.cloud.nacos.discovery.endpoint",
@ -65,7 +66,7 @@ public class NacosDiscoveryParameterInitListener
edasChangeOrderConfiguration.getDauthSecretKey());
// step 2: set these properties for nacos client
properties.setProperty("webContext", "/vipserver");
properties.setProperty("serverPort", "80");
properties.setProperty("nacos.naming.web.context", "/vipserver");
properties.setProperty("nacos.naming.exposed.port", "80");
}
}

View File

@ -31,13 +31,33 @@ import com.aliyun.oss.ClientBuilderConfiguration;
@ConfigurationProperties("spring.cloud.alicloud.oss")
public class OssProperties {
/**
* Authorization Mode, please see <a href=
* "https://help.aliyun.com/document_detail/32010.html?spm=a2c4g.11186623.6.659.29f145dc3KOwTh">oss
* docs</a>.
*/
@Value("${spring.cloud.alicloud.oss.authorization-mode:AK_SK}")
private AliCloudAuthorizationMode authorizationMode;
/**
* Endpoint, please see <a href=
* "https://help.aliyun.com/document_detail/32010.html?spm=a2c4g.11186623.6.659.29f145dc3KOwTh">oss
* docs</a>.
*/
private String endpoint;
/**
* Sts token, please see <a href=
* "https://help.aliyun.com/document_detail/32010.html?spm=a2c4g.11186623.6.659.29f145dc3KOwTh">oss
* docs</a>.
*/
private StsToken sts;
/**
* Client Configuration, please see <a href=
* "https://help.aliyun.com/document_detail/32010.html?spm=a2c4g.11186623.6.659.29f145dc3KOwTh">oss
* docs</a>.
*/
private ClientBuilderConfiguration config;
public AliCloudAuthorizationMode getAuthorizationMode() {

View File

@ -26,8 +26,18 @@ import com.alibaba.cloud.context.scx.ScxConfiguration;
@ConfigurationProperties("spring.cloud.alicloud.scx")
public class ScxProperties implements ScxConfiguration {
/**
* Group id, please see <a href=
* "https://help.aliyun.com/document_detail/35359.html?spm=a2c4g.11186623.6.721.69ca5763p9IJly">scx
* docs</a>.
*/
private String groupId;
/**
* Domain name, please see <a href=
* "https://help.aliyun.com/document_detail/35359.html?spm=a2c4g.11186623.6.721.69ca5763p9IJly">scx
* docs</a>.
*/
private String domainName;
@Override

View File

@ -48,7 +48,9 @@ public class StatisticsTaskStarter implements InitializingBean {
private static final String NACOS_CONFIG_SERVER_MODE_KEY = "spring.cloud.nacos.config.server-mode";
private static final String NACOS_CONFIG_SERVER_MODE_VALUE = "EDAS";
private static final String NACOS_DISCOVERY_SERVER_MODE_KEY = "spring.cloud.nacos.discovery.server-mode";
private static final String NACOS_SERVER_MODE_VALUE = "EDAS";
@Autowired(required = false)
private AliCloudEdasSdk aliCloudEdasSdk;
@ -106,10 +108,14 @@ public class StatisticsTaskStarter implements InitializingBean {
if (acmContextBootstrapConfiguration != null && acmEnableEdas) {
components.add("SC-ACM");
}
if (NACOS_CONFIG_SERVER_MODE_VALUE
if (NACOS_SERVER_MODE_VALUE
.equals(System.getProperty(NACOS_CONFIG_SERVER_MODE_KEY))) {
components.add("SC-NACOS-CONFIG");
}
if (NACOS_SERVER_MODE_VALUE
.equals(System.getProperty(NACOS_DISCOVERY_SERVER_MODE_KEY))) {
components.add("SC-NACOS-DISCOVERY");
}
return components;
}

View File

@ -0,0 +1,23 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos;
/**
* @author xiaolongzuo
*/
public class NacosDiscoveryAutoConfiguration {
}

View File

@ -16,15 +16,16 @@
package org.springframework.cloud.alicloud.context.nacos;
import com.alibaba.cloud.context.ans.AliCloudAnsInitializer;
import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.springframework.cloud.alicloud.context.BaseAliCloudSpringApplication;
import org.springframework.cloud.alicloud.utils.ChangeOrderUtils;
import static org.assertj.core.api.Assertions.assertThat;
import com.alibaba.cloud.context.ans.AliCloudAnsInitializer;
import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory;
/**
* @author xiaolongzuo
@ -37,24 +38,25 @@ public class NacosDiscoveryParameterInitListenerTests
@BeforeClass
public static void setUp() {
ChangeOrderUtils.mockChangeOrder();
System.getProperties().setProperty("webContext", "/vipserver");
System.getProperties().setProperty("serverPort", "80");
}
@Test
public void testNacosParameterInitListener() {
assertThat(System.getProperty("spring.cloud.nacos.config.server-addr"))
assertThat(System.getProperty("spring.cloud.nacos.discovery.server-mode"))
.isEqualTo("EDAS");
assertThat(System.getProperty("spring.cloud.nacos.discovery.server-addr"))
.isEqualTo("");
assertThat(System.getProperty("spring.cloud.nacos.config.endpoint"))
assertThat(System.getProperty("spring.cloud.nacos.discovery.endpoint"))
.isEqualTo("testDomain");
assertThat(System.getProperty("spring.cloud.nacos.config.namespace"))
assertThat(System.getProperty("spring.cloud.nacos.discovery.namespace"))
.isEqualTo("testTenantId");
assertThat(System.getProperty("spring.cloud.nacos.config.access-key"))
assertThat(System.getProperty("spring.cloud.nacos.discovery.access-key"))
.isEqualTo("testAK");
assertThat(System.getProperty("spring.cloud.nacos.config.secret-key"))
assertThat(System.getProperty("spring.cloud.nacos.discovery.secret-key"))
.isEqualTo("testSK");
assertThat(System.getProperties().getProperty("webContext"))
assertThat(System.getProperties().getProperty("nacos.naming.web.context"))
.isEqualTo("/vipserver");
assertThat(System.getProperties().getProperty("serverPort")).isEqualTo("80");
assertThat(System.getProperties().getProperty("nacos.naming.exposed.port"))
.isEqualTo("80");
}
}