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

add test case and nacos watch

This commit is contained in:
flystar32 2019-02-20 19:02:17 +08:00
parent fe13a96fe4
commit a03ce9fea8
27 changed files with 1338 additions and 178 deletions

View File

@ -18,7 +18,6 @@ package org.springframework.cloud.alibaba.nacos;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

View File

@ -183,19 +183,19 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
}
}
private static void checkDataIdFileExtension(String[] sharedDataIdArry) {
private static void checkDataIdFileExtension(String[] dataIdArray) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < sharedDataIdArry.length; i++) {
for (int i = 0; i < dataIdArray.length; i++) {
boolean isLegal = false;
for (String fileExtension : SUPPORT_FILE_EXTENSION) {
if (sharedDataIdArry[i].indexOf(fileExtension) > 0) {
if (dataIdArray[i].indexOf(fileExtension) > 0) {
isLegal = true;
break;
}
}
// add tips
if (!isLegal) {
stringBuilder.append(sharedDataIdArry[i] + ",");
stringBuilder.append(dataIdArray[i] + ",");
}
}

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