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

update NacosAutoServiceRegistration, update pom.xml, and format code

This commit is contained in:
flystar32 2018-09-18 14:58:50 +08:00
parent 50ffcef735
commit 879e689390
8 changed files with 113 additions and 101 deletions

View File

@ -34,7 +34,6 @@
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency> </dependency>
<!--spring boot-->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId> <artifactId>spring-boot-actuator</artifactId>
@ -62,13 +61,12 @@
<scope>provided</scope> <scope>provided</scope>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
<scope>provided</scope> <scope>test</scope>
<optional>true</optional>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>

View File

@ -63,8 +63,10 @@ public class NacosDiscoveryAutoConfiguration {
@Bean @Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class) @ConditionalOnBean(AutoServiceRegistrationProperties.class)
public NacosAutoServiceRegistration nacosAutoServiceRegistration( public NacosAutoServiceRegistration nacosAutoServiceRegistration(
NacosServiceRegistry registry, AutoServiceRegistrationProperties properties, NacosServiceRegistry registry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
NacosRegistration registration) { NacosRegistration registration) {
return new NacosAutoServiceRegistration(registry, properties, registration); return new NacosAutoServiceRegistration(registry,
autoServiceRegistrationProperties, registration);
} }
} }

View File

@ -35,7 +35,8 @@ import com.alibaba.nacos.api.naming.pojo.ListView;
*/ */
public class NacosDiscoveryClient implements DiscoveryClient { public class NacosDiscoveryClient implements DiscoveryClient {
private static final Logger LOGGER = LoggerFactory.getLogger(NacosDiscoveryClient.class); private static final Logger LOGGER = LoggerFactory
.getLogger(NacosDiscoveryClient.class);
public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client"; public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client";
@Autowired @Autowired
@ -85,7 +86,7 @@ public class NacosDiscoveryClient implements DiscoveryClient {
public List<ServiceInstance> getInstances(String serviceId) { public List<ServiceInstance> getInstances(String serviceId) {
try { try {
NamingService namingService = nacosRegistration.getNacosNamingService(); NamingService namingService = nacosRegistration.getNacosNamingService();
List<Instance> instances = namingService.selectInstances(serviceId,true); List<Instance> instances = namingService.selectInstances(serviceId, true);
return hostToServiceInstanceList(instances, serviceId); return hostToServiceInstanceList(instances, serviceId);
} }
catch (Exception e) { catch (Exception e) {
@ -94,25 +95,26 @@ public class NacosDiscoveryClient implements DiscoveryClient {
} }
} }
private static ServiceInstance hostToServiceInstance(Instance instance, String serviceId) { private static ServiceInstance hostToServiceInstance(Instance instance,
String serviceId) {
NacosServiceInstance nacosServiceInstance = new NacosServiceInstance(); NacosServiceInstance nacosServiceInstance = new NacosServiceInstance();
nacosServiceInstance.setHost(instance.getIp()); nacosServiceInstance.setHost(instance.getIp());
nacosServiceInstance.setPort(instance.getPort()); nacosServiceInstance.setPort(instance.getPort());
nacosServiceInstance.setServiceId(serviceId); nacosServiceInstance.setServiceId(serviceId);
Map<String, String> metadata = new HashMap<String, String>(); Map<String, String> metadata = new HashMap<String, String>();
metadata.put("instanceId", instance.getInstanceId()); metadata.put("instanceId", instance.getInstanceId());
metadata.put("weight", instance.getWeight()+""); metadata.put("weight", instance.getWeight() + "");
metadata.put("healthy", instance.isHealthy()+""); metadata.put("healthy", instance.isHealthy() + "");
metadata.put("cluster", instance.getCluster()+""); metadata.put("cluster", instance.getCluster() + "");
metadata.putAll(instance.getMetadata()); metadata.putAll(instance.getMetadata());
nacosServiceInstance.setMetadata(metadata); nacosServiceInstance.setMetadata(metadata);
return nacosServiceInstance; return nacosServiceInstance;
} }
private static List<ServiceInstance> hostToServiceInstanceList(List<Instance> instances, private static List<ServiceInstance> hostToServiceInstanceList(
String serviceId) { List<Instance> instances, String serviceId) {
List<ServiceInstance> result = new ArrayList<ServiceInstance>(instances.size()); List<ServiceInstance> result = new ArrayList<ServiceInstance>(instances.size());
for (Instance instance: instances) { for (Instance instance : instances) {
result.add(hostToServiceInstance(instance, serviceId)); result.add(hostToServiceInstance(instance, serviceId));
} }
return result; return result;
@ -123,9 +125,11 @@ public class NacosDiscoveryClient implements DiscoveryClient {
try { try {
NamingService namingService = nacosRegistration.getNacosNamingService(); NamingService namingService = nacosRegistration.getNacosNamingService();
ListView<String> services = namingService.getServicesOfServer(1, Integer.MAX_VALUE); ListView<String> services = namingService.getServicesOfServer(1,
Integer.MAX_VALUE);
return services.getData(); return services.getData();
}catch( Exception e){ }
catch (Exception e) {
LOGGER.error("get service name from nacos server fail,", e); LOGGER.error("get service name from nacos server fail,", e);
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -16,7 +16,6 @@
package org.springframework.cloud.alibaba.nacos; package org.springframework.cloud.alibaba.nacos;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
@ -49,7 +48,8 @@ public class NacosDiscoveryProperties {
private String serverAddr; private String serverAddr;
/** /**
* the domain name of a service, through which the server address can be dynamically obtained. * the domain name of a service, through which the server address can be dynamically
* obtained.
*/ */
private String endpoint; private String endpoint;
@ -91,8 +91,8 @@ public class NacosDiscoveryProperties {
private boolean registerEnabled = true; private boolean registerEnabled = true;
/** /**
* The ip address your want to register for your service instance, needn't to set it if * The ip address your want to register for your service instance, needn't to set it
* the auto detect ip works well * if the auto detect ip works well.
*/ */
private String ip; private String ip;
@ -123,7 +123,6 @@ public class NacosDiscoveryProperties {
private String secretKey; private String secretKey;
@Autowired @Autowired
@JsonIgnore
private InetUtils inetUtils; private InetUtils inetUtils;
@PostConstruct @PostConstruct
@ -190,10 +189,6 @@ public class NacosDiscoveryProperties {
this.logName = logName; this.logName = logName;
} }
public InetUtils getInetUtils() {
return inetUtils;
}
public void setInetUtils(InetUtils inetUtils) { public void setInetUtils(InetUtils inetUtils) {
this.inetUtils = inetUtils; this.inetUtils = inetUtils;
} }
@ -296,47 +291,45 @@ public class NacosDiscoveryProperties {
@Override @Override
public String toString() { public String toString() {
return "NacosDiscoveryProperties{" + return "NacosDiscoveryProperties{" + "serverAddr='" + serverAddr + '\''
"serverAddr='" + serverAddr + '\'' + + ", endpoint='" + endpoint + '\'' + ", namespace='" + namespace + '\''
", endpoint='" + endpoint + '\'' + + ", logName='" + logName + '\'' + ", service='" + service + '\''
", namespace='" + namespace + '\'' + + ", weight=" + weight + ", clusterName='" + clusterName + '\''
", logName='" + logName + '\'' + + ", metadata=" + metadata + ", registerEnabled=" + registerEnabled
", service='" + service + '\'' + + ", ip='" + ip + '\'' + ", networkInterface='" + networkInterface + '\''
", weight=" + weight + + ", port=" + port + ", secure=" + secure + ", accessKey='" + accessKey
", clusterName='" + clusterName + '\'' + + '\'' + ", secretKey='" + secretKey + '\'' + '}';
", metadata=" + metadata +
", registerEnabled=" + registerEnabled +
", ip='" + ip + '\'' +
", networkInterface='" + networkInterface + '\'' +
", port=" + port +
", secure=" + secure +
", accessKey='" + accessKey + '\'' +
", secretKey='" + secretKey + '\'' +
'}';
} }
public void overrideFromEnv(Environment env){ public void overrideFromEnv(Environment env) {
if(StringUtils.isEmpty(this.getServerAddr())) { if (StringUtils.isEmpty(this.getServerAddr())) {
this.setServerAddr(env.resolvePlaceholders("${spring.cloud.nacos.discovery.server-addr:}")); this.setServerAddr(env
.resolvePlaceholders("${spring.cloud.nacos.discovery.server-addr:}"));
} }
if(StringUtils.isEmpty(this.getNamespace())) { if (StringUtils.isEmpty(this.getNamespace())) {
this.setNamespace(env.resolvePlaceholders("${spring.cloud.nacos.discovery.namespace:}")); this.setNamespace(env
.resolvePlaceholders("${spring.cloud.nacos.discovery.namespace:}"));
} }
if(StringUtils.isEmpty(this.getAccessKey())) { if (StringUtils.isEmpty(this.getAccessKey())) {
this.setAccessKey(env.resolvePlaceholders("${spring.cloud.nacos.discovery.access-key:}")); this.setAccessKey(env
.resolvePlaceholders("${spring.cloud.nacos.discovery.access-key:}"));
} }
if(StringUtils.isEmpty(this.getSecretKey())) { if (StringUtils.isEmpty(this.getSecretKey())) {
this.setSecretKey(env.resolvePlaceholders("${spring.cloud.nacos.discovery.secret-key:}")); this.setSecretKey(env
.resolvePlaceholders("${spring.cloud.nacos.discovery.secret-key:}"));
} }
if(StringUtils.isEmpty(this.getLogName())) { if (StringUtils.isEmpty(this.getLogName())) {
this.setLogName(env.resolvePlaceholders("${spring.cloud.nacos.discovery.log-name:}")); this.setLogName(
env.resolvePlaceholders("${spring.cloud.nacos.discovery.log-name:}"));
} }
if(StringUtils.isEmpty(this.getClusterName())) { if (StringUtils.isEmpty(this.getClusterName())) {
this.setClusterName(env.resolvePlaceholders("${spring.cloud.nacos.discovery.clusterName-name:}")); this.setClusterName(env.resolvePlaceholders(
"${spring.cloud.nacos.discovery.clusterName-name:}"));
} }
if(StringUtils.isEmpty(this.getEndpoint())) { if (StringUtils.isEmpty(this.getEndpoint())) {
this.setEndpoint(env.resolvePlaceholders("${spring.cloud.nacos.discovery.endpoint:}")); this.setEndpoint(
env.resolvePlaceholders("${spring.cloud.nacos.discovery.endpoint:}"));
} }
} }

View File

@ -30,7 +30,6 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnClass(name = "org.springframework.boot.actuate.endpoint.AbstractEndpoint") @ConditionalOnClass(name = "org.springframework.boot.actuate.endpoint.AbstractEndpoint")
public class NacosDiscoveryEndpointAutoConfiguration { public class NacosDiscoveryEndpointAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public NacosDiscoveryEndpoint nacosDiscoveryEndpoint() { public NacosDiscoveryEndpoint nacosDiscoveryEndpoint() {

View File

@ -19,12 +19,11 @@ package org.springframework.cloud.alibaba.nacos.registry;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration; import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry; import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.context.ApplicationContext; import org.springframework.util.Assert;
import org.springframework.context.event.EventListener; import org.springframework.util.StringUtils;
/** /**
* @author xiaojing * @author xiaojing
@ -37,20 +36,26 @@ public class NacosAutoServiceRegistration
@Autowired @Autowired
private NacosRegistration registration; private NacosRegistration registration;
@Autowired
private ApplicationContext context;
public NacosAutoServiceRegistration( public NacosAutoServiceRegistration(
ServiceRegistry<NacosRegistration> serviceRegistry, ServiceRegistry<NacosRegistration> serviceRegistry,
AutoServiceRegistrationProperties properties, AutoServiceRegistrationProperties autoServiceRegistrationProperties,
NacosRegistration registration) { NacosRegistration registration) {
super(serviceRegistry, properties); super(serviceRegistry, autoServiceRegistrationProperties);
this.registration = registration; this.registration = registration;
} }
@Deprecated
public void setPort(int port) {
getPort().set(port);
}
@Override @Override
protected NacosRegistration getRegistration() { protected NacosRegistration getRegistration() {
return registration; if (this.registration.getPort() < 0 && this.getPort().get() > 0) {
this.registration.setPort(this.getPort().get());
}
Assert.isTrue(this.registration.getPort() > 0, "service.port has not been set");
return this.registration;
} }
@Override @Override
@ -58,6 +63,27 @@ public class NacosAutoServiceRegistration
return null; return null;
} }
@Override
protected void register() {
if (!this.registration.getNacosDiscoveryProperties().isRegisterEnabled()) {
LOGGER.debug("Registration disabled.");
return;
}
if (this.registration.getPort() < 0) {
this.registration.setPort(getPort().get());
}
super.register();
}
@Override
protected void registerManagement() {
if (!this.registration.getNacosDiscoveryProperties().isRegisterEnabled()) {
return;
}
super.registerManagement();
}
@Override @Override
protected int getConfiguredPort() { protected int getConfiguredPort() {
return this.getPort().get(); return this.getPort().get();
@ -70,34 +96,19 @@ public class NacosAutoServiceRegistration
@Override @Override
protected Object getConfiguration() { protected Object getConfiguration() {
return null; return this.registration.getNacosDiscoveryProperties();
} }
@Override @Override
protected boolean isEnabled() { protected boolean isEnabled() {
return true; return this.registration.getNacosDiscoveryProperties().isRegisterEnabled();
}
/**
* Register the local service with the {@link ServiceRegistry}
*/
@Override
protected void register() {
this.registration.setPort(this.getPort().get());
this.getServiceRegistry().register(getRegistration());
} }
@Override @Override
@EventListener(EmbeddedServletContainerInitializedEvent.class) @SuppressWarnings("deprecation")
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) { protected String getAppName() {
if (context.equals(event.getApplicationContext())) { String appName = registration.getNacosDiscoveryProperties().getService();
int localPort = event.getEmbeddedServletContainer().getPort(); return StringUtils.isEmpty(appName) ? super.getAppName() : appName;
if (this.getPort().get() == 0) {
LOGGER.info("Updating port to " + localPort);
this.getPort().compareAndSet(0, localPort);
start();
}
}
} }
} }

View File

@ -34,6 +34,7 @@ import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.client.naming.utils.UtilAndComs; import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import static com.alibaba.nacos.api.PropertyKeyConst.*; import static com.alibaba.nacos.api.PropertyKeyConst.*;
/** /**
* @author xiaojing * @author xiaojing
*/ */
@ -54,11 +55,12 @@ public class NacosRegistration implements Registration, ServiceInstance {
Properties properties = new Properties(); Properties properties = new Properties();
properties.put(SERVER_ADDR, nacosDiscoveryProperties.getServerAddr()); properties.put(SERVER_ADDR, nacosDiscoveryProperties.getServerAddr());
properties.put(NAMESPACE, nacosDiscoveryProperties.getNamespace()); properties.put(NAMESPACE, nacosDiscoveryProperties.getNamespace());
properties.put(UtilAndComs.NACOS_NAMING_LOG_NAME, nacosDiscoveryProperties.getLogName()); properties.put(UtilAndComs.NACOS_NAMING_LOG_NAME,
nacosDiscoveryProperties.getLogName());
properties.put(ENDPOINT, nacosDiscoveryProperties.getEndpoint()); properties.put(ENDPOINT, nacosDiscoveryProperties.getEndpoint());
properties.put(ACCESS_KEY,nacosDiscoveryProperties.getAccessKey()); properties.put(ACCESS_KEY, nacosDiscoveryProperties.getAccessKey());
properties.put(SECRET_KEY,nacosDiscoveryProperties.getSecretKey()); properties.put(SECRET_KEY, nacosDiscoveryProperties.getSecretKey());
properties.put(CLUSTER_NAME,nacosDiscoveryProperties.getClusterName()); properties.put(CLUSTER_NAME, nacosDiscoveryProperties.getClusterName());
try { try {
nacosNamingService = NacosFactory.createNamingService(properties); nacosNamingService = NacosFactory.createNamingService(properties);
} }
@ -134,9 +136,8 @@ public class NacosRegistration implements Registration, ServiceInstance {
@Override @Override
public String toString() { public String toString() {
return "NacosRegistration{" + return "NacosRegistration{" + "nacosDiscoveryProperties="
"nacosDiscoveryProperties=" + nacosDiscoveryProperties + + nacosDiscoveryProperties + ", nacosNamingService=" + nacosNamingService
", nacosNamingService=" + nacosNamingService + + '}';
'}';
} }
} }

View File

@ -36,7 +36,8 @@ public class NacosServerList extends AbstractServerList<NacosServer> {
private String serviceId; private String serviceId;
public NacosServerList(){} public NacosServerList() {
}
public NacosServerList(String serviceId) { public NacosServerList(String serviceId) {
this.serviceId = serviceId; this.serviceId = serviceId;
@ -54,11 +55,14 @@ public class NacosServerList extends AbstractServerList<NacosServer> {
private List<NacosServer> getServers() { private List<NacosServer> getServers() {
try { try {
List<Instance> instances = registration.getNacosNamingService().selectInstances(serviceId, true); List<Instance> instances = registration.getNacosNamingService()
.selectInstances(serviceId, true);
return instancesToServerList(instances); return instancesToServerList(instances);
} }
catch (Exception e) { catch (Exception e) {
throw new IllegalStateException("Can not get service instances from nacos, serviceId=" + serviceId, e); throw new IllegalStateException(
"Can not get service instances from nacos, serviceId=" + serviceId,
e);
} }
} }