urls = serviceBean.getExportedUrls();
urls.stream()
- .map(SpringCloudRegistry::getServiceName)
- .forEach(serviceName -> {
+ .map(URL::toString)
+ .forEach(url -> {
ServiceRestMetadata metadata = new ServiceRestMetadata();
- metadata.setName(serviceName);
+ metadata.setUrl(url);
metadata.setMeta(methodRestMetadata);
serviceRestMetadata.add(metadata);
});
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/metadata/resolver/MetadataResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/metadata/resolver/MetadataResolver.java
index 922ce6d3..c4d0a1c7 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/metadata/resolver/MetadataResolver.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/metadata/resolver/MetadataResolver.java
@@ -16,8 +16,7 @@
*/
package org.springframework.cloud.alibaba.dubbo.metadata.resolver;
-import com.alibaba.dubbo.config.spring.ServiceBean;
-
+import org.apache.dubbo.config.spring.ServiceBean;
import org.springframework.cloud.alibaba.dubbo.metadata.RestMethodMetadata;
import org.springframework.cloud.alibaba.dubbo.metadata.ServiceRestMetadata;
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/DubboInvocationHandler.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/DubboInvocationHandler.java
index 95dd73c0..ab4d18fa 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/DubboInvocationHandler.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/DubboInvocationHandler.java
@@ -16,8 +16,7 @@
*/
package org.springframework.cloud.alibaba.dubbo.openfeign;
-import com.alibaba.dubbo.rpc.service.GenericService;
-
+import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.cloud.alibaba.dubbo.metadata.RestMethodMetadata;
import org.springframework.cloud.alibaba.dubbo.service.DubboGenericServiceExecutionContext;
import org.springframework.cloud.alibaba.dubbo.service.DubboGenericServiceExecutionContextFactory;
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/FeignMethodMetadata.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/FeignMethodMetadata.java
index 0eda4d1b..52ee10e5 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/FeignMethodMetadata.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/FeignMethodMetadata.java
@@ -16,8 +16,7 @@
*/
package org.springframework.cloud.alibaba.dubbo.openfeign;
-import com.alibaba.dubbo.rpc.service.GenericService;
-
+import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.cloud.alibaba.dubbo.metadata.RestMethodMetadata;
import java.lang.reflect.Method;
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/TargeterBeanPostProcessor.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/TargeterBeanPostProcessor.java
index a4a3c77f..331e7a00 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/TargeterBeanPostProcessor.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/TargeterBeanPostProcessor.java
@@ -25,6 +25,7 @@ import org.springframework.cloud.alibaba.dubbo.service.DubboGenericServiceFactor
import org.springframework.core.env.Environment;
import static java.lang.reflect.Proxy.newProxyInstance;
+import static org.springframework.cloud.alibaba.dubbo.autoconfigure.DubboOpenFeignAutoConfiguration.TARGETER_CLASS_NAME;
import static org.springframework.util.ClassUtils.getUserClass;
import static org.springframework.util.ClassUtils.isPresent;
import static org.springframework.util.ClassUtils.resolveClassName;
@@ -36,8 +37,6 @@ import static org.springframework.util.ClassUtils.resolveClassName;
*/
public class TargeterBeanPostProcessor implements BeanPostProcessor, BeanClassLoaderAware {
- private static final String TARGETER_CLASS_NAME = "org.springframework.cloud.openfeign.Targeter";
-
private final Environment environment;
private final DubboServiceMetadataRepository dubboServiceMetadataRepository;
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/TargeterInvocationHandler.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/TargeterInvocationHandler.java
index c665c245..e606367a 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/TargeterInvocationHandler.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/openfeign/TargeterInvocationHandler.java
@@ -17,10 +17,9 @@
package org.springframework.cloud.alibaba.dubbo.openfeign;
-import com.alibaba.dubbo.rpc.service.GenericService;
-
import feign.Contract;
import feign.Target;
+import org.apache.dubbo.rpc.service.GenericService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.alibaba.dubbo.annotation.DubboTransported;
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/AbstractRegistrationFactory.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/AbstractRegistrationFactory.java
index 41d06eb0..f17c3019 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/AbstractRegistrationFactory.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/AbstractRegistrationFactory.java
@@ -16,13 +16,13 @@
*/
package org.springframework.cloud.alibaba.dubbo.registry;
-import com.alibaba.dubbo.common.Constants;
-import com.alibaba.dubbo.common.URL;
-import com.alibaba.dubbo.common.utils.NetUtils;
-
+import org.apache.dubbo.common.Constants;
+import org.apache.dubbo.common.URL;
+import org.springframework.cloud.alibaba.dubbo.registry.handler.DubboRegistryServiceIdHandler;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.serviceregistry.Registration;
+import org.springframework.context.ConfigurableApplicationContext;
import java.util.LinkedHashMap;
@@ -30,20 +30,39 @@ import java.util.LinkedHashMap;
* Abstract {@link RegistrationFactory} implementation
*
*
- * @param The subclass of {@link Registration}
+ * @param The subclass of {@link Registration}
* @author Mercy
*/
-public abstract class AbstractRegistrationFactory implements RegistrationFactory {
+public abstract class AbstractRegistrationFactory implements RegistrationFactory {
- protected ServiceInstance createServiceInstance(String serviceName, URL url) {
+ public final R create(URL url, ConfigurableApplicationContext applicationContext) {
+ ServiceInstance serviceInstance = createServiceInstance(url, applicationContext);
+ return create(serviceInstance, applicationContext);
+ }
+
+ /**
+ * Create an instance {@link ServiceInstance}. This method maybe override by sub-class.
+ *
+ * @param url The Dubbo's {@link URL}
+ * @param applicationContext {@link ConfigurableApplicationContext}
+ * @return an instance {@link ServiceInstance}
+ */
+ protected ServiceInstance createServiceInstance(URL url, ConfigurableApplicationContext applicationContext) {
+ String serviceId = createServiceId(url, applicationContext);
// Append default category if absent
String category = url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY);
URL newURL = url.addParameter(Constants.CATEGORY_KEY, category);
newURL = newURL.addParameter(Constants.PROTOCOL_KEY, url.getProtocol());
- String ip = NetUtils.getLocalHost();
+ String ip = url.getIp();
int port = newURL.getParameter(Constants.BIND_PORT_KEY, url.getPort());
- DefaultServiceInstance serviceInstance = new DefaultServiceInstance(url.toIdentityString(), serviceName, ip, port, false);
+ DefaultServiceInstance serviceInstance = new DefaultServiceInstance(url.toIdentityString(), serviceId, ip, port, false);
serviceInstance.getMetadata().putAll(new LinkedHashMap<>(newURL.getParameters()));
return serviceInstance;
}
+
+ protected String createServiceId(URL url, ConfigurableApplicationContext applicationContext) {
+ DubboRegistryServiceIdHandler handler = applicationContext.getBean(DubboRegistryServiceIdHandler.class);
+ return handler.createServiceId(url);
+ }
}
+
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/DefaultRegistrationFactory.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/DefaultRegistrationFactory.java
index ac3e35f3..1bcfd534 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/DefaultRegistrationFactory.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/DefaultRegistrationFactory.java
@@ -16,10 +16,9 @@
*/
package org.springframework.cloud.alibaba.dubbo.registry;
-import com.alibaba.dubbo.common.URL;
-
+import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.serviceregistry.Registration;
-import org.springframework.context.ApplicationContext;
+import org.springframework.context.ConfigurableApplicationContext;
/**
* Default {@link RegistrationFactory}
@@ -29,7 +28,7 @@ import org.springframework.context.ApplicationContext;
public class DefaultRegistrationFactory extends AbstractRegistrationFactory {
@Override
- public Registration create(String serviceName, URL url, ApplicationContext applicationContext) {
- return new DelegatingRegistration(createServiceInstance(serviceName, url));
+ public Registration create(ServiceInstance serviceInstance, ConfigurableApplicationContext applicationContext) {
+ return new DelegatingRegistration(serviceInstance);
}
}
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/RegistrationFactory.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/RegistrationFactory.java
index 7d8d298c..d05eea94 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/RegistrationFactory.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/RegistrationFactory.java
@@ -16,27 +16,35 @@
*/
package org.springframework.cloud.alibaba.dubbo.registry;
-import com.alibaba.dubbo.common.URL;
-
+import org.apache.dubbo.common.URL;
+import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.serviceregistry.Registration;
-import org.springframework.context.ApplicationContext;
+import org.springframework.context.ConfigurableApplicationContext;
/**
* {@link Registration} Factory to createServiceInstance a instance of {@link Registration}
*
- * @param The subclass of {@link Registration}
+ * @param The subclass of {@link Registration}
* @author Mercy
*/
-public interface RegistrationFactory {
+public interface RegistrationFactory {
/**
- * Create a instance of {@link T}
+ * Create a instance of {@link R}
*
- * @param serviceName The service name of Dubbo service interface
- * @param url The Dubbo's URL
- * @param applicationContext {@link ApplicationContext}
- * @return a instance of {@link T}
+ * @param url The Dubbo's {@link URL}
+ * @param applicationContext {@link ConfigurableApplicationContext}
+ * @return a instance of {@link R}, if null, it indicates the registration will not be executed.
*/
- T create(String serviceName, URL url, ApplicationContext applicationContext);
+ R create(URL url, ConfigurableApplicationContext applicationContext);
+
+ /**
+ * Create a instance of {@link R}
+ *
+ * @param serviceInstance {@link ServiceInstance}
+ * @param applicationContext {@link ConfigurableApplicationContext}
+ * @return a instance of {@link R}, if null, it indicates the registration will not be executed.
+ */
+ R create(ServiceInstance serviceInstance, ConfigurableApplicationContext applicationContext);
}
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/RegistrationFactoryProvider.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/RegistrationFactoryProvider.java
new file mode 100644
index 00000000..c5debc68
--- /dev/null
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/RegistrationFactoryProvider.java
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.dubbo.registry;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.FactoryBean;
+import org.springframework.cloud.client.serviceregistry.Registration;
+import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.core.ResolvableType;
+
+import java.util.List;
+
+import static org.springframework.beans.BeanUtils.instantiateClass;
+import static org.springframework.core.ResolvableType.forInstance;
+import static org.springframework.core.ResolvableType.forType;
+import static org.springframework.core.io.support.SpringFactoriesLoader.loadFactoryNames;
+import static org.springframework.util.ClassUtils.isPresent;
+import static org.springframework.util.ClassUtils.resolveClassName;
+
+/**
+ * {@link RegistrationFactory} Provider
+ *
+ * @author Mercy
+ */
+public class RegistrationFactoryProvider implements FactoryBean, ApplicationContextAware {
+
+ private final Logger logger = LoggerFactory.getLogger(getClass());
+
+ private RegistrationFactory registrationFactory;
+
+ @Override
+ public RegistrationFactory getObject() throws BeansException {
+ return registrationFactory;
+ }
+
+ @Override
+ public Class> getObjectType() {
+ return RegistrationFactory.class;
+ }
+
+ public boolean isSingleton() {
+ return true;
+ }
+
+ @Override
+ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
+ ServiceRegistry serviceRegistry = applicationContext.getBean(ServiceRegistry.class);
+ ClassLoader classLoader = applicationContext.getClassLoader();
+ this.registrationFactory = buildRegistrationFactory(serviceRegistry, classLoader);
+ }
+
+ private RegistrationFactory buildRegistrationFactory(ServiceRegistry serviceRegistry,
+ ClassLoader classLoader) {
+ RegistrationFactory registrationFactory = null;
+ List factoryClassNames = loadFactoryNames(RegistrationFactory.class, classLoader);
+
+ ResolvableType serviceRegistryType = forInstance(serviceRegistry);
+ // Get first generic Class
+ Class> registrationClass = resolveGenericClass(serviceRegistryType, ServiceRegistry.class, 0);
+
+ for (String factoryClassName : factoryClassNames) {
+ if (isPresent(factoryClassName, classLoader)) { // ignore compilation issue
+ Class> factoryClass = resolveClassName(factoryClassName, classLoader);
+ ResolvableType registrationFactoryType = forType(factoryClass);
+ Class> actualRegistrationClass = resolveGenericClass(registrationFactoryType, RegistrationFactory.class, 0);
+ if (registrationClass.equals(actualRegistrationClass)) {
+ registrationFactory = (RegistrationFactory) instantiateClass(registrationFactoryType.getRawClass());
+ break;
+ }
+ }
+ }
+
+ if (registrationFactory == null) {
+
+ if (logger.isWarnEnabled()) {
+ logger.warn("{} implementation can't be resolved by ServiceRegistry[{}]",
+ registrationClass.getSimpleName(), serviceRegistry.getClass().getName());
+ }
+
+ registrationFactory = new DefaultRegistrationFactory();
+ } else {
+ if (logger.isInfoEnabled()) {
+ logger.info("{} has been resolved by ServiceRegistry[{}]",
+ registrationFactory.getClass().getName(), serviceRegistry.getClass().getName());
+ }
+ }
+
+ return registrationFactory;
+ }
+
+ private Class> resolveGenericClass(ResolvableType implementedType, Class> interfaceClass, int index) {
+
+ ResolvableType resolvableType = implementedType;
+
+ try {
+ OUTER:
+ while (true) {
+
+ ResolvableType[] interfaceTypes = resolvableType.getInterfaces();
+
+ for (ResolvableType interfaceType : interfaceTypes) {
+ if (interfaceType.resolve().equals(interfaceClass)) {
+ resolvableType = interfaceType;
+ break OUTER;
+ }
+ }
+
+ ResolvableType superType = resolvableType.getSuperType();
+
+ Class> superClass = superType.resolve();
+
+ if (Object.class.equals(superClass)) {
+ break;
+ }
+
+ resolvableType = superType;
+ }
+
+ } catch (Throwable e) {
+ resolvableType = ResolvableType.forType(void.class);
+ }
+
+ return resolvableType.resolveGeneric(index);
+ }
+
+}
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/SpringCloudRegistry.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/SpringCloudRegistry.java
index 30678ed1..d87e1f6c 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/SpringCloudRegistry.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/SpringCloudRegistry.java
@@ -16,47 +16,37 @@
*/
package org.springframework.cloud.alibaba.dubbo.registry;
-import com.alibaba.dubbo.common.Constants;
-import com.alibaba.dubbo.common.URL;
-import com.alibaba.dubbo.common.utils.NamedThreadFactory;
-import com.alibaba.dubbo.common.utils.UrlUtils;
-import com.alibaba.dubbo.registry.NotifyListener;
-import com.alibaba.dubbo.registry.RegistryFactory;
-import com.alibaba.dubbo.registry.support.FailbackRegistry;
-
+import org.apache.dubbo.common.Constants;
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.utils.UrlUtils;
+import org.apache.dubbo.registry.NotifyListener;
+import org.apache.dubbo.registry.RegistryFactory;
+import org.apache.dubbo.registry.support.FailbackRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.cloud.alibaba.dubbo.registry.handler.DubboRegistryServiceIdHandler;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
-import org.springframework.context.ApplicationContext;
-import org.springframework.core.ResolvableType;
-import org.springframework.util.StringUtils;
+import org.springframework.context.ConfigurableApplicationContext;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
-import java.util.Objects;
+import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
-import static com.alibaba.dubbo.common.Constants.CONFIGURATORS_CATEGORY;
-import static com.alibaba.dubbo.common.Constants.CONSUMERS_CATEGORY;
-import static com.alibaba.dubbo.common.Constants.PROVIDERS_CATEGORY;
-import static com.alibaba.dubbo.common.Constants.ROUTERS_CATEGORY;
-import static java.lang.Long.getLong;
-import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
-import static org.springframework.beans.BeanUtils.instantiateClass;
-import static org.springframework.core.ResolvableType.forInstance;
-import static org.springframework.core.ResolvableType.forType;
-import static org.springframework.core.io.support.SpringFactoriesLoader.loadFactoryNames;
-import static org.springframework.util.ClassUtils.isPresent;
-import static org.springframework.util.ClassUtils.resolveClassName;
+import static java.util.Collections.singletonList;
+import static org.apache.dubbo.common.Constants.CONFIGURATORS_CATEGORY;
+import static org.apache.dubbo.common.Constants.CONSUMERS_CATEGORY;
+import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY;
+import static org.apache.dubbo.common.Constants.PROVIDER_SIDE;
+import static org.apache.dubbo.common.Constants.ROUTERS_CATEGORY;
+import static org.apache.dubbo.common.Constants.SIDE_KEY;
/**
* Dubbo {@link RegistryFactory} uses Spring Cloud Service Registration abstraction, whose protocol is "spring-cloud"
@@ -65,306 +55,131 @@ import static org.springframework.util.ClassUtils.resolveClassName;
*/
public class SpringCloudRegistry extends FailbackRegistry {
+ /**
+ * The parameter name of {@link #allServicesLookupInterval}
+ */
+ public static final String ALL_SERVICES_LOOKUP_INTERVAL_PARAM_NAME = "dubbo.all.services.lookup.interval";
+
+ /**
+ * The parameter name of {@link #registeredServicesLookupInterval}
+ */
+ public static final String REGISTERED_SERVICES_LOOKUP_INTERVAL_PARAM_NAME = "dubbo.registered.services.lookup.interval";
+
/**
* All supported categories
*/
- private static final String[] ALL_SUPPORTED_CATEGORIES = of(
+ public static final String[] ALL_SUPPORTED_CATEGORIES = of(
PROVIDERS_CATEGORY,
CONSUMERS_CATEGORY,
ROUTERS_CATEGORY,
CONFIGURATORS_CATEGORY
);
- private static final int CATEGORY_INDEX = 0;
-
- private static final int SERVICE_INTERFACE_INDEX = CATEGORY_INDEX + 1;
-
- private static final int SERVICE_VERSION_INDEX = SERVICE_INTERFACE_INDEX + 1;
-
- private static final int SERVICE_GROUP_INDEX = SERVICE_VERSION_INDEX + 1;
-
- private static final String WILDCARD = "*";
+ private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* The interval in second of lookup service names(only for Dubbo-OPS)
*/
- private static final long ALL_SERVICES_LOOKUP_INTERVAL = getLong("dubbo.all.services.lookup.interval", 30);
+ private final long allServicesLookupInterval;
- /**
- * The interval in second of lookup regigered service instances
- */
- private static final long REGISTERED_SERVICES_LOOKUP_INTERVAL = getLong("dubbo.registered.services.lookup.interval", 300);
-
- /**
- * The {@link ScheduledExecutorService Scheduler} to lookup the registered services
- */
- private static final ScheduledExecutorService registeredServicesLookupScheduler = newSingleThreadScheduledExecutor(new NamedThreadFactory("dubbo-registered-services-lookup-"));
-
- /**
- * The {@link ScheduledExecutorService Scheduler} to lookup all services (only for Dubbo-OPS)
- */
- private static volatile ScheduledExecutorService allServicesLookupScheduler;
-
- private final Logger logger = LoggerFactory.getLogger(getClass());
-
- /**
- * The separator for service name
- */
- private static final String SERVICE_NAME_SEPARATOR = ":";
-
- private final ApplicationContext applicationContext;
+ private final long registeredServicesLookupInterval;
private final ServiceRegistry serviceRegistry;
- private final DiscoveryClient discoveryClient;
-
private final RegistrationFactory registrationFactory;
- public SpringCloudRegistry(URL url, ApplicationContext applicationContext) {
+ private final DiscoveryClient discoveryClient;
+
+ private final DubboRegistryServiceIdHandler dubboRegistryServiceIdHandler;
+
+ private final ScheduledExecutorService servicesLookupScheduler;
+
+ private final ConfigurableApplicationContext applicationContext;
+
+ public SpringCloudRegistry(URL url,
+ ServiceRegistry serviceRegistry,
+ RegistrationFactory registrationFactory,
+ DiscoveryClient discoveryClient,
+ ScheduledExecutorService servicesLookupScheduler,
+ ConfigurableApplicationContext applicationContext) {
super(url);
+ this.allServicesLookupInterval = url.getParameter(ALL_SERVICES_LOOKUP_INTERVAL_PARAM_NAME, 30L);
+ this.registeredServicesLookupInterval = url.getParameter(REGISTERED_SERVICES_LOOKUP_INTERVAL_PARAM_NAME, 300L);
+ this.serviceRegistry = serviceRegistry;
+ this.registrationFactory = registrationFactory;
+ this.discoveryClient = discoveryClient;
+ this.dubboRegistryServiceIdHandler = applicationContext.getBean(DubboRegistryServiceIdHandler.class);
this.applicationContext = applicationContext;
- this.serviceRegistry = applicationContext.getBean(ServiceRegistry.class);
- this.registrationFactory = buildRegistrationFactory(serviceRegistry, applicationContext.getClassLoader());
- this.discoveryClient = applicationContext.getBean(DiscoveryClient.class);
- applicationContext.getClassLoader();
+ this.servicesLookupScheduler = servicesLookupScheduler;
}
- private RegistrationFactory buildRegistrationFactory(ServiceRegistry serviceRegistry,
- ClassLoader classLoader) {
- RegistrationFactory registrationFactory = null;
- List factoryClassNames = loadFactoryNames(RegistrationFactory.class, classLoader);
-
- ResolvableType serviceRegistryType = forInstance(serviceRegistry);
- // Get first generic Class
- Class> registrationClass = resolveGenericClass(serviceRegistryType, ServiceRegistry.class, 0);
-
- for (String factoryClassName : factoryClassNames) {
- if (isPresent(factoryClassName, classLoader)) { // ignore compilation issue
- Class> factoryClass = resolveClassName(factoryClassName, classLoader);
- ResolvableType registrationFactoryType = forType(factoryClass);
- Class> actualRegistrationClass = resolveGenericClass(registrationFactoryType, RegistrationFactory.class, 0);
- if (registrationClass.equals(actualRegistrationClass)) {
- registrationFactory = (RegistrationFactory) instantiateClass(registrationFactoryType.getRawClass());
- break;
- }
- }
- }
-
- if (registrationFactory == null) {
-
- if (logger.isWarnEnabled()) {
- logger.warn("{} implementation can't be resolved by ServiceRegistry[{}]",
- registrationClass.getSimpleName(), serviceRegistry.getClass().getName());
- }
-
- registrationFactory = new DefaultRegistrationFactory();
- } else {
- if (logger.isInfoEnabled()) {
- logger.info("{} has been resolved by ServiceRegistry[{}]",
- registrationFactory.getClass().getName(), serviceRegistry.getClass().getName());
- }
- }
-
- return registrationFactory;
- }
-
- private Class> resolveGenericClass(ResolvableType implementedType, Class> interfaceClass, int index) {
-
- ResolvableType resolvableType = implementedType;
-
- try {
- OUTER:
- while (true) {
-
- ResolvableType[] interfaceTypes = resolvableType.getInterfaces();
-
- for (ResolvableType interfaceType : interfaceTypes) {
- if (interfaceType.resolve().equals(interfaceClass)) {
- resolvableType = interfaceType;
- break OUTER;
- }
- }
-
- ResolvableType superType = resolvableType.getSuperType();
-
- Class> superClass = superType.resolve();
-
- if (Object.class.equals(superClass)) {
- break;
- }
-
- resolvableType = superType;
- }
-
- } catch (Throwable e) {
- resolvableType = ResolvableType.forType(void.class);
- }
-
- return resolvableType.resolveGeneric(index);
- }
-
-
- @Override
- protected void doRegister(URL url) {
- final String serviceName = getServiceName(url);
- final Registration registration = createRegistration(serviceName, url);
- serviceRegistry.register(registration);
+ protected boolean shouldRegister(Registration registration) {
+ Map metadata = registration.getMetadata();
+ String side = metadata.get(SIDE_KEY);
+ return PROVIDER_SIDE.equals(side); // Only register the Provider.
}
@Override
- protected void doUnregister(URL url) {
- final String serviceName = getServiceName(url);
- final Registration registration = createRegistration(serviceName, url);
- this.serviceRegistry.deregister(registration);
+ public void doRegister(URL url) {
+ final Registration registration = createRegistration(url);
+ if (shouldRegister(registration)) {
+ serviceRegistry.register(registration);
+ }
}
@Override
- protected void doSubscribe(URL url, NotifyListener listener) {
+ public void doUnregister(URL url) {
+ final Registration registration = createRegistration(url);
+ if (shouldRegister(registration)) {
+ this.serviceRegistry.deregister(registration);
+ }
+ }
+
+ @Override
+ public void doSubscribe(URL url, NotifyListener listener) {
List serviceNames = getServiceNames(url, listener);
doSubscribe(url, listener, serviceNames);
- this.registeredServicesLookupScheduler.scheduleAtFixedRate(new Runnable() {
+ this.servicesLookupScheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
doSubscribe(url, listener, serviceNames);
}
- }, REGISTERED_SERVICES_LOOKUP_INTERVAL, REGISTERED_SERVICES_LOOKUP_INTERVAL, TimeUnit.SECONDS);
+ }, registeredServicesLookupInterval, registeredServicesLookupInterval, TimeUnit.SECONDS);
}
@Override
- protected void doUnsubscribe(URL url, NotifyListener listener) {
+ public void doUnsubscribe(URL url, NotifyListener listener) {
if (isAdminProtocol(url)) {
shutdownServiceNamesLookup();
}
-
-// if (registeredServicesLookupScheduler != null) {
-// registeredServicesLookupScheduler.shutdown();
-// }
}
@Override
public boolean isAvailable() {
- return false;
+ return !discoveryClient.getServices().isEmpty();
}
private void shutdownServiceNamesLookup() {
- if (allServicesLookupScheduler != null) {
- allServicesLookupScheduler.shutdown();
+ if (servicesLookupScheduler != null) {
+ servicesLookupScheduler.shutdown();
}
}
- private Registration createRegistration(String serviceName, URL url) {
- return registrationFactory.create(serviceName, url, applicationContext);
+ private Registration createRegistration(URL url) {
+ return registrationFactory.create(url, applicationContext);
}
- public static String getServiceName(URL url) {
- String category = url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY);
- return getServiceName(url, category);
- }
-
- private static String getServiceName(URL url, String category) {
- StringBuilder serviceNameBuilder = new StringBuilder(category);
- appendIfPresent(serviceNameBuilder, url, Constants.INTERFACE_KEY);
- appendIfPresent(serviceNameBuilder, url, Constants.VERSION_KEY);
- appendIfPresent(serviceNameBuilder, url, Constants.GROUP_KEY);
- return serviceNameBuilder.toString();
- }
-
- private static void appendIfPresent(StringBuilder target, URL url, String parameterName) {
- String parameterValue = url.getParameter(parameterName);
- appendIfPresent(target, parameterValue);
- }
-
- private static void appendIfPresent(StringBuilder target, String parameterValue) {
- if (StringUtils.hasText(parameterValue)) {
- target.append(SERVICE_NAME_SEPARATOR).append(parameterValue);
- }
- }
-
- private void filterServiceNames(List serviceNames, URL url) {
-
- final String[] categories = getCategories(url);
-
- final String targetServiceInterface = url.getServiceInterface();
-
- final String targetVersion = url.getParameter(Constants.VERSION_KEY);
-
- final String targetGroup = url.getParameter(Constants.GROUP_KEY);
-
+ private void filterServiceNames(List serviceNames) {
filter(serviceNames, new Filter() {
@Override
public boolean accept(String serviceName) {
- // split service name to segments
- // (required) segments[0] = category
- // (required) segments[1] = serviceInterface
- // (required) segments[2] = version
- // (optional) segments[3] = group
- String[] segments = getServiceSegments(serviceName);
- int length = segments.length;
- if (length < SERVICE_GROUP_INDEX) { // must present 4 segments or more
- return false;
- }
-
- String category = getCategory(segments);
- if (Arrays.binarySearch(categories, category) > -1) { // no match category
- return false;
- }
-
- String serviceInterface = getServiceInterface(segments);
- if (!WILDCARD.equals(targetServiceInterface) &&
- !Objects.equals(targetServiceInterface, serviceInterface)) { // no match service interface
- return false;
- }
-
- String version = getServiceVersion(segments);
- if (!WILDCARD.equals(targetVersion) &&
- !Objects.equals(targetVersion, version)) { // no match service version
- return false;
- }
-
- String group = getServiceGroup(segments);
- if (group != null && !WILDCARD.equals(targetGroup)
- && !Objects.equals(targetGroup, group)) { // no match service group
- return false;
- }
-
- return true;
+ return dubboRegistryServiceIdHandler.supports(serviceName);
}
});
}
- public static String[] getServiceSegments(String serviceName) {
- return StringUtils.delimitedListToStringArray(serviceName, SERVICE_NAME_SEPARATOR);
- }
-
- public static String getCategory(String[] segments) {
- return segments[CATEGORY_INDEX];
- }
-
- public static String getServiceInterface(String[] segments) {
- return segments[SERVICE_INTERFACE_INDEX];
- }
-
- public static String getServiceVersion(String[] segments) {
- return segments[SERVICE_VERSION_INDEX];
- }
-
- public static String getServiceGroup(String[] segments) {
- return segments.length > SERVICE_GROUP_INDEX ? segments[SERVICE_GROUP_INDEX] : null;
- }
-
- /**
- * Get the categories from {@link URL}
- *
- * @param url {@link URL}
- * @return non-null array
- */
- private String[] getCategories(URL url) {
- return Constants.ANY_VALUE.equals(url.getServiceInterface()) ?
- ALL_SUPPORTED_CATEGORIES : of(Constants.DEFAULT_CATEGORY);
- }
-
private List getAllServiceNames() {
- return discoveryClient.getServices();
+ return new LinkedList<>(discoveryClient.getServices());
}
/**
@@ -379,7 +194,7 @@ public class SpringCloudRegistry extends FailbackRegistry {
initAllServicesLookupScheduler(url, listener);
return getServiceNamesForOps(url);
} else {
- return doGetServiceNames(url);
+ return singletonList(dubboRegistryServiceIdHandler.createServiceId(url));
}
}
@@ -389,30 +204,14 @@ public class SpringCloudRegistry extends FailbackRegistry {
}
private void initAllServicesLookupScheduler(final URL url, final NotifyListener listener) {
- if (allServicesLookupScheduler == null) {
- allServicesLookupScheduler = newSingleThreadScheduledExecutor(new NamedThreadFactory("dubbo-all-services-lookup-"));
- allServicesLookupScheduler.scheduleAtFixedRate(new Runnable() {
- @Override
- public void run() {
- List serviceNames = getAllServiceNames();
- filter(serviceNames, new Filter() {
- @Override
- public boolean accept(String serviceName) {
- boolean accepted = false;
- for (String category : ALL_SUPPORTED_CATEGORIES) {
- String prefix = category + SERVICE_NAME_SEPARATOR;
- if (StringUtils.startsWithIgnoreCase(serviceName, prefix)) {
- accepted = true;
- break;
- }
- }
- return accepted;
- }
- });
- doSubscribe(url, listener, serviceNames);
- }
- }, ALL_SERVICES_LOOKUP_INTERVAL, ALL_SERVICES_LOOKUP_INTERVAL, TimeUnit.SECONDS);
- }
+ servicesLookupScheduler.scheduleAtFixedRate(new Runnable() {
+ @Override
+ public void run() {
+ List serviceNames = getAllServiceNames();
+ filterServiceNames(serviceNames);
+ doSubscribe(url, listener, serviceNames);
+ }
+ }, allServicesLookupInterval, allServicesLookupInterval, TimeUnit.SECONDS);
}
private void doSubscribe(final URL url, final NotifyListener listener, final List serviceNames) {
@@ -422,16 +221,6 @@ public class SpringCloudRegistry extends FailbackRegistry {
}
}
- private List doGetServiceNames(URL url) {
- String[] categories = getCategories(url);
- List serviceNames = new ArrayList(categories.length);
- for (String category : categories) {
- final String serviceName = getServiceName(url, category);
- serviceNames.add(serviceName);
- }
- return serviceNames;
- }
-
/**
* Notify the Healthy {@link ServiceInstance service instance} to subscriber.
*
@@ -488,7 +277,7 @@ public class SpringCloudRegistry extends FailbackRegistry {
*/
private List getServiceNamesForOps(URL url) {
List serviceNames = getAllServiceNames();
- filterServiceNames(serviceNames, url);
+ filterServiceNames(serviceNames);
return serviceNames;
}
@@ -509,7 +298,7 @@ public class SpringCloudRegistry extends FailbackRegistry {
/**
* A filter
*/
- private interface Filter {
+ public interface Filter {
/**
* Tests whether or not the specified data should be accepted.
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/SpringCloudRegistryFactory.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/SpringCloudRegistryFactory.java
index 7b0a9169..234c65d4 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/SpringCloudRegistryFactory.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/SpringCloudRegistryFactory.java
@@ -16,11 +16,21 @@
*/
package org.springframework.cloud.alibaba.dubbo.registry;
-import com.alibaba.dubbo.common.URL;
-import com.alibaba.dubbo.registry.Registry;
-import com.alibaba.dubbo.registry.RegistryFactory;
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.utils.NamedThreadFactory;
+import org.apache.dubbo.registry.Registry;
+import org.apache.dubbo.registry.RegistryFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.cloud.client.discovery.DiscoveryClient;
+import org.springframework.cloud.client.serviceregistry.Registration;
+import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
+import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.context.ApplicationContext;
+import java.util.concurrent.ScheduledExecutorService;
+
+import static java.lang.System.getProperty;
+import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
/**
* Dubbo {@link RegistryFactory} uses Spring Cloud Service Registration abstraction, whose protocol is "spring-cloud"
@@ -31,14 +41,46 @@ import org.springframework.context.ApplicationContext;
*/
public class SpringCloudRegistryFactory implements RegistryFactory {
- private static ApplicationContext applicationContext;
+ private static String SERVICES_LOOKUP_SCHEDULER_THREAD_NAME_PREFIX =
+ getProperty("dubbo.services.lookup.scheduler.thread.name.prefix ", "dubbo-services-lookup-");
+
+ private static ConfigurableApplicationContext applicationContext;
+
+ private final Logger logger = LoggerFactory.getLogger(getClass());
+
+ private final ScheduledExecutorService servicesLookupScheduler;
+
+ private ServiceRegistry serviceRegistry;
+
+ private RegistrationFactory registrationFactory;
+
+ private DiscoveryClient discoveryClient;
+
+ private volatile boolean initialized = false;
+
+ public SpringCloudRegistryFactory() {
+ servicesLookupScheduler = newSingleThreadScheduledExecutor(
+ new NamedThreadFactory(SERVICES_LOOKUP_SCHEDULER_THREAD_NAME_PREFIX));
+ }
+
+ protected void init() {
+ if (initialized || applicationContext == null) {
+ return;
+ }
+
+ this.serviceRegistry = applicationContext.getBean(ServiceRegistry.class);
+ this.registrationFactory = applicationContext.getBean(RegistrationFactory.class);
+ this.discoveryClient = applicationContext.getBean(DiscoveryClient.class);
+ }
@Override
public Registry getRegistry(URL url) {
- return new SpringCloudRegistry(url, applicationContext);
+ init();
+ return new SpringCloudRegistry(url, serviceRegistry, registrationFactory, discoveryClient,
+ servicesLookupScheduler, applicationContext);
}
- public static void setApplicationContext(ApplicationContext applicationContext) {
+ public static void setApplicationContext(ConfigurableApplicationContext applicationContext) {
SpringCloudRegistryFactory.applicationContext = applicationContext;
}
}
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/apache/zookeeper/ZookeeperRegistrationFactory.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/apache/zookeeper/ZookeeperRegistrationFactory.java
index 77becb0e..6657343f 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/apache/zookeeper/ZookeeperRegistrationFactory.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/apache/zookeeper/ZookeeperRegistrationFactory.java
@@ -16,15 +16,13 @@
*/
package org.springframework.cloud.alibaba.dubbo.registry.apache.zookeeper;
-import com.alibaba.dubbo.common.URL;
-
import org.springframework.cloud.alibaba.dubbo.registry.AbstractRegistrationFactory;
import org.springframework.cloud.alibaba.dubbo.registry.RegistrationFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance;
import org.springframework.cloud.zookeeper.serviceregistry.ServiceInstanceRegistration;
import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperRegistration;
-import org.springframework.context.ApplicationContext;
+import org.springframework.context.ConfigurableApplicationContext;
/**
* Zookeeper {@link RegistrationFactory}
@@ -34,10 +32,7 @@ import org.springframework.context.ApplicationContext;
public class ZookeeperRegistrationFactory extends AbstractRegistrationFactory {
@Override
- public ZookeeperRegistration create(String serviceName, URL url, ApplicationContext applicationContext) {
-
- ServiceInstance serviceInstance = createServiceInstance(serviceName, url);
-
+ public ZookeeperRegistration create(ServiceInstance serviceInstance, ConfigurableApplicationContext applicationContext) {
ZookeeperInstance zookeeperInstance = new ZookeeperInstance(serviceInstance.getInstanceId(),
serviceInstance.getServiceId(), serviceInstance.getMetadata());
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/handler/DubboRegistryServiceIdHandler.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/handler/DubboRegistryServiceIdHandler.java
new file mode 100644
index 00000000..15a35029
--- /dev/null
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/handler/DubboRegistryServiceIdHandler.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.dubbo.registry.handler;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.registry.Registry;
+import org.springframework.context.ConfigurableApplicationContext;
+
+/**
+ * Dubbo {@link Registry} Spring Cloud Service Id Builder
+ *
+ * @author Mercy
+ */
+public interface DubboRegistryServiceIdHandler {
+
+ /**
+ * Supports the specified id of Spring Cloud Service or not
+ *
+ * @param serviceId the specified id of Spring Cloud Service
+ * @return if supports, return true
, or false
+ */
+ boolean supports(String serviceId);
+
+ /**
+ * Creates the id of Spring Cloud Service
+ *
+ * @param url The Dubbo's {@link URL}
+ * @return non-null
+ */
+ String createServiceId(URL url);
+
+ /**
+ * The instance if {@link ConfigurableApplicationContext} .
+ *
+ * @return non-null
+ */
+ ConfigurableApplicationContext getContext();
+
+}
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/handler/StandardDubboRegistryServiceIdHandler.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/handler/StandardDubboRegistryServiceIdHandler.java
new file mode 100644
index 00000000..caaa0706
--- /dev/null
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/handler/StandardDubboRegistryServiceIdHandler.java
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.dubbo.registry.handler;
+
+import org.apache.dubbo.common.Constants;
+import org.apache.dubbo.common.URL;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.util.StringUtils;
+
+import java.util.Objects;
+
+import static java.lang.System.getProperty;
+import static org.apache.dubbo.common.Constants.CONSUMERS_CATEGORY;
+import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY;
+import static org.springframework.util.StringUtils.startsWithIgnoreCase;
+
+/**
+ * The Standard {@link DubboRegistryServiceIdHandler}
+ *
+ * The service ID pattern is "${category}:${interface}:${version}:${group}"
+ *
+ * @author Mercy
+ */
+public class StandardDubboRegistryServiceIdHandler implements DubboRegistryServiceIdHandler {
+
+ /**
+ * The separator for service name that could be changed by the Java Property "dubbo.service.name.separator".
+ */
+ protected static final String SERVICE_NAME_SEPARATOR = getProperty("dubbo.service.name.separator", ":");
+
+ private final ConfigurableApplicationContext context;
+
+ public StandardDubboRegistryServiceIdHandler(ConfigurableApplicationContext context) {
+ this.context = context;
+ }
+
+ @Override
+ public boolean supports(String serviceId) {
+ return startsWithIgnoreCase(serviceId, PROVIDERS_CATEGORY) ||
+ startsWithIgnoreCase(serviceId, CONSUMERS_CATEGORY);
+ }
+
+ @Override
+ public String createServiceId(URL url) {
+ String category = url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY);
+ if (!Objects.equals(category, PROVIDERS_CATEGORY) && !Objects.equals(category, CONSUMERS_CATEGORY)) {
+ category = PROVIDERS_CATEGORY;
+ }
+ return createServiceId(url, category);
+ }
+
+ @Override
+ public ConfigurableApplicationContext getContext() {
+ return context;
+ }
+
+ /**
+ * This method maybe override by sub-class.
+ *
+ * @param url The Dubbo's {@link URL}
+ * @param category The category
+ * @return
+ */
+ protected String createServiceId(URL url, String category) {
+ StringBuilder serviceNameBuilder = new StringBuilder(category);
+ appendIfPresent(serviceNameBuilder, url, Constants.INTERFACE_KEY);
+ appendIfPresent(serviceNameBuilder, url, Constants.VERSION_KEY);
+ appendIfPresent(serviceNameBuilder, url, Constants.GROUP_KEY);
+ return serviceNameBuilder.toString();
+ }
+
+ private static void appendIfPresent(StringBuilder target, URL url, String parameterName) {
+ String parameterValue = url.getParameter(parameterName);
+ appendIfPresent(target, parameterValue);
+ }
+
+ private static void appendIfPresent(StringBuilder target, String parameterValue) {
+ if (StringUtils.hasText(parameterValue)) {
+ target.append(SERVICE_NAME_SEPARATOR).append(parameterValue);
+ }
+ }
+}
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/hashicorp/consul/ConsulRegistrationFactory.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/hashicorp/consul/ConsulRegistrationFactory.java
index 89c19acf..a5861fb9 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/hashicorp/consul/ConsulRegistrationFactory.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/hashicorp/consul/ConsulRegistrationFactory.java
@@ -16,8 +16,6 @@
*/
package org.springframework.cloud.alibaba.dubbo.registry.hashicorp.consul;
-import com.alibaba.dubbo.common.URL;
-
import com.ecwid.consul.v1.agent.model.NewService;
import org.springframework.cloud.alibaba.dubbo.registry.AbstractRegistrationFactory;
import org.springframework.cloud.alibaba.dubbo.registry.RegistrationFactory;
@@ -25,7 +23,7 @@ import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.discovery.ConsulServerUtils;
import org.springframework.cloud.consul.serviceregistry.ConsulRegistration;
-import org.springframework.context.ApplicationContext;
+import org.springframework.context.ConfigurableApplicationContext;
import java.util.LinkedHashSet;
import java.util.LinkedList;
@@ -41,9 +39,7 @@ import java.util.Set;
public class ConsulRegistrationFactory extends AbstractRegistrationFactory {
@Override
- public ConsulRegistration create(String serviceName, URL url, ApplicationContext applicationContext) {
- ServiceInstance serviceInstance = createServiceInstance(serviceName, url);
-
+ public ConsulRegistration create(ServiceInstance serviceInstance, ConfigurableApplicationContext applicationContext) {
Map metadata = getMetadata(serviceInstance);
List tags = createTags(metadata);
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/netflix/eureka/EurekaRegistrationFactory.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/netflix/eureka/EurekaRegistrationFactory.java
index af54039a..84fafa62 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/netflix/eureka/EurekaRegistrationFactory.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/registry/netflix/eureka/EurekaRegistrationFactory.java
@@ -16,8 +16,6 @@
*/
package org.springframework.cloud.alibaba.dubbo.registry.netflix.eureka;
-import com.alibaba.dubbo.common.URL;
-
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.discovery.EurekaClientConfig;
import org.springframework.beans.BeanUtils;
@@ -28,7 +26,7 @@ import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.netflix.eureka.CloudEurekaInstanceConfig;
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration;
-import org.springframework.context.ApplicationContext;
+import org.springframework.context.ConfigurableApplicationContext;
/**
* {@link EurekaRegistration} Factory
@@ -38,8 +36,7 @@ import org.springframework.context.ApplicationContext;
public class EurekaRegistrationFactory extends AbstractRegistrationFactory {
@Override
- public EurekaRegistration create(String serviceName, URL url, ApplicationContext applicationContext) {
- ServiceInstance serviceInstance = createServiceInstance(serviceName, url);
+ public EurekaRegistration create(ServiceInstance serviceInstance, ConfigurableApplicationContext applicationContext) {
CloudEurekaInstanceConfig cloudEurekaInstanceConfig = applicationContext.getBean(CloudEurekaInstanceConfig.class);
ObjectProvider healthCheckHandler = applicationContext.getBeanProvider(HealthCheckHandler.class);
EurekaClientConfig eurekaClientConfig = applicationContext.getBean(EurekaClientConfig.class);
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/DubboGenericServiceExecutionContext.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/DubboGenericServiceExecutionContext.java
index 5bf8c691..640fc009 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/DubboGenericServiceExecutionContext.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/DubboGenericServiceExecutionContext.java
@@ -16,7 +16,7 @@
*/
package org.springframework.cloud.alibaba.dubbo.service;
-import com.alibaba.dubbo.rpc.service.GenericService;
+import org.apache.dubbo.rpc.service.GenericService;
/**
* Dubbo {@link GenericService} execution context
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/DubboGenericServiceFactory.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/DubboGenericServiceFactory.java
index f85fbac8..e15bbb69 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/DubboGenericServiceFactory.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/DubboGenericServiceFactory.java
@@ -16,9 +16,9 @@
*/
package org.springframework.cloud.alibaba.dubbo.service;
-import com.alibaba.dubbo.config.spring.ReferenceBean;
-import com.alibaba.dubbo.rpc.service.GenericService;
-
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.config.spring.ReferenceBean;
+import org.apache.dubbo.rpc.service.GenericService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.alibaba.dubbo.metadata.DubboServiceMetadata;
@@ -31,12 +31,10 @@ import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-import static com.alibaba.dubbo.common.Constants.DEFAULT_CLUSTER;
-import static com.alibaba.dubbo.common.Constants.DEFAULT_PROTOCOL;
-import static org.springframework.cloud.alibaba.dubbo.registry.SpringCloudRegistry.getServiceGroup;
-import static org.springframework.cloud.alibaba.dubbo.registry.SpringCloudRegistry.getServiceInterface;
-import static org.springframework.cloud.alibaba.dubbo.registry.SpringCloudRegistry.getServiceSegments;
-import static org.springframework.cloud.alibaba.dubbo.registry.SpringCloudRegistry.getServiceVersion;
+import static org.apache.dubbo.common.Constants.DEFAULT_CLUSTER;
+import static org.apache.dubbo.common.Constants.DEFAULT_PROTOCOL;
+import static org.apache.dubbo.common.Constants.GROUP_KEY;
+import static org.apache.dubbo.common.Constants.VERSION_KEY;
/**
* Dubbo {@link GenericService} Factory
@@ -67,11 +65,11 @@ public class DubboGenericServiceFactory {
private ReferenceBean build(ServiceRestMetadata serviceRestMetadata,
DubboTransportedMetadata dubboTransportedMetadata) {
- String dubboServiceName = serviceRestMetadata.getName();
- String[] segments = getServiceSegments(dubboServiceName);
- String interfaceName = getServiceInterface(segments);
- String version = getServiceVersion(segments);
- String group = getServiceGroup(segments);
+ String urlValue = serviceRestMetadata.getUrl();
+ URL url = URL.valueOf(urlValue);
+ String interfaceName = url.getServiceInterface();
+ String version = url.getParameter(VERSION_KEY);
+ String group = url.getParameter(GROUP_KEY);
String protocol = dubboTransportedMetadata.getProtocol();
String cluster = dubboTransportedMetadata.getCluster();
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/DubboMetadataConfigServiceInvocationHandler.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/DubboMetadataConfigServiceInvocationHandler.java
index 94014d77..8f354857 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/DubboMetadataConfigServiceInvocationHandler.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/DubboMetadataConfigServiceInvocationHandler.java
@@ -16,7 +16,7 @@
*/
package org.springframework.cloud.alibaba.dubbo.service;
-import com.alibaba.dubbo.rpc.service.GenericService;
+import org.apache.dubbo.rpc.service.GenericService;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/PublishingDubboMetadataConfigService.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/PublishingDubboMetadataConfigService.java
index 799e7caa..fa49e94b 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/PublishingDubboMetadataConfigService.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/PublishingDubboMetadataConfigService.java
@@ -16,8 +16,6 @@
*/
package org.springframework.cloud.alibaba.dubbo.service;
-import com.alibaba.dubbo.config.annotation.Service;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
@@ -28,15 +26,13 @@ import javax.annotation.PostConstruct;
import java.util.LinkedHashSet;
import java.util.Set;
-import static org.springframework.cloud.alibaba.dubbo.autoconfigure.DubboMetadataAutoConfiguration.METADATA_PROTOCOL_BEAN_NAME;
+import static org.springframework.util.ObjectUtils.isEmpty;
/**
* Publishing {@link DubboMetadataConfigService} implementation
*
* @author Mercy
*/
-@Service(version = "${spring.application.name}", protocol = METADATA_PROTOCOL_BEAN_NAME)
-// Use current Spring application name as the Dubbo Service version
public class PublishingDubboMetadataConfigService implements DubboMetadataConfigService {
/**
@@ -69,7 +65,9 @@ public class PublishingDubboMetadataConfigService implements DubboMetadataConfig
public String getServiceRestMetadata() {
String serviceRestMetadataJsonConfig = null;
try {
- serviceRestMetadataJsonConfig = objectMapper.writeValueAsString(serviceRestMetadata);
+ if (!isEmpty(serviceRestMetadata)) {
+ serviceRestMetadataJsonConfig = objectMapper.writeValueAsString(serviceRestMetadata);
+ }
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
diff --git a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/parameter/DubboGenericServiceParameterResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/parameter/DubboGenericServiceParameterResolver.java
index 58ed2263..93a28264 100644
--- a/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/parameter/DubboGenericServiceParameterResolver.java
+++ b/spring-cloud-alibaba-dubbo/src/main/java/org/springframework/cloud/alibaba/dubbo/service/parameter/DubboGenericServiceParameterResolver.java
@@ -16,8 +16,7 @@
*/
package org.springframework.cloud.alibaba.dubbo.service.parameter;
-import com.alibaba.dubbo.rpc.service.GenericService;
-
+import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.cloud.alibaba.dubbo.http.HttpServerRequest;
import org.springframework.cloud.alibaba.dubbo.metadata.MethodParameterMetadata;
import org.springframework.cloud.alibaba.dubbo.metadata.RestMethodMetadata;
diff --git a/spring-cloud-alibaba-dubbo/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-dubbo/src/main/resources/META-INF/spring.factories
index f90bb175..ed1c9c3f 100644
--- a/spring-cloud-alibaba-dubbo/src/main/resources/META-INF/spring.factories
+++ b/spring-cloud-alibaba-dubbo/src/main/resources/META-INF/spring.factories
@@ -1,7 +1,7 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.alibaba.dubbo.autoconfigure.DubboMetadataAutoConfiguration,\
org.springframework.cloud.alibaba.dubbo.autoconfigure.DubboOpenFeignAutoConfiguration,\
- org.springframework.cloud.alibaba.dubbo.autoconfigure.DubboRestMetadataRegistrationAutoConfiguration,\
+ org.springframework.cloud.alibaba.dubbo.autoconfigure.DubboMetadataEventHandlingAutoConfiguration,\
org.springframework.cloud.alibaba.dubbo.autoconfigure.DubboLoadBalancedRestTemplateAutoConfiguration,\
org.springframework.cloud.alibaba.dubbo.autoconfigure.DubboServiceAutoConfiguration
@@ -9,7 +9,6 @@ org.springframework.context.ApplicationContextInitializer=\
org.springframework.cloud.alibaba.dubbo.context.DubboServiceRegistrationApplicationContextInitializer
org.springframework.cloud.alibaba.dubbo.registry.RegistrationFactory=\
- org.springframework.cloud.alibaba.dubbo.registry.DefaultRegistrationFactory,\
org.springframework.cloud.alibaba.dubbo.registry.netflix.eureka.EurekaRegistrationFactory,\
org.springframework.cloud.alibaba.dubbo.registry.apache.zookeeper.ZookeeperRegistrationFactory,\
org.springframework.cloud.alibaba.dubbo.registry.hashicorp.consul.ConsulRegistrationFactory
\ No newline at end of file
diff --git a/spring-cloud-alibaba-examples/fescar-example/account-service/src/main/resources/application.properties b/spring-cloud-alibaba-examples/fescar-example/account-service/src/main/resources/application.properties
index 10f45c59..68b91d01 100644
--- a/spring-cloud-alibaba-examples/fescar-example/account-service/src/main/resources/application.properties
+++ b/spring-cloud-alibaba-examples/fescar-example/account-service/src/main/resources/application.properties
@@ -5,5 +5,5 @@ mysql.server.ip=127.0.0.1
mysql.server.port=3306
mysql.db.name=demo
-mysql.user.name=xxxxx
-mysql.user.password=xxxxx
\ No newline at end of file
+mysql.user.name=root
+mysql.user.password=123456
\ No newline at end of file
diff --git a/spring-cloud-alibaba-examples/fescar-example/order-service/src/main/java/org/springframework/cloud/alibaba/cloud/examples/OrderController.java b/spring-cloud-alibaba-examples/fescar-example/order-service/src/main/java/org/springframework/cloud/alibaba/cloud/examples/OrderController.java
index 2e0e0f81..546392d1 100644
--- a/spring-cloud-alibaba-examples/fescar-example/order-service/src/main/java/org/springframework/cloud/alibaba/cloud/examples/OrderController.java
+++ b/spring-cloud-alibaba-examples/fescar-example/order-service/src/main/java/org/springframework/cloud/alibaba/cloud/examples/OrderController.java
@@ -16,11 +16,6 @@
package org.springframework.cloud.alibaba.cloud.examples;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.util.Random;
-
import com.alibaba.fescar.core.context.RootContext;
import org.slf4j.Logger;
@@ -40,92 +35,97 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.util.Random;
+
/**
* @author xiaojing
*/
@RestController
public class OrderController {
- private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
- private static final String SUCCESS = "SUCCESS";
- private static final String FAIL = "FAIL";
- private static final String USER_ID = "U100001";
- private static final String COMMODITY_CODE = "C00321";
+ private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
+ private static final String SUCCESS = "SUCCESS";
+ private static final String FAIL = "FAIL";
+ private static final String USER_ID = "U100001";
+ private static final String COMMODITY_CODE = "C00321";
- private final JdbcTemplate jdbcTemplate;
- private final RestTemplate restTemplate;
- private Random random;
+ private final JdbcTemplate jdbcTemplate;
+ private final RestTemplate restTemplate;
+ private Random random;
- public OrderController(JdbcTemplate jdbcTemplate, RestTemplate restTemplate) {
- this.jdbcTemplate = jdbcTemplate;
- this.restTemplate = restTemplate;
- this.random = new Random();
- }
+ public OrderController(JdbcTemplate jdbcTemplate, RestTemplate restTemplate) {
+ this.jdbcTemplate = jdbcTemplate;
+ this.restTemplate = restTemplate;
+ this.random = new Random();
+ }
- @RequestMapping(value = "/order", method = RequestMethod.POST, produces = "application/json")
- public String order(String userId, String commodityCode, int orderCount) {
- LOGGER.info("Order Service Begin ... xid: " + RootContext.getXID());
+ @RequestMapping(value = "/order", method = RequestMethod.POST, produces = "application/json")
+ public String order(String userId, String commodityCode, int orderCount) {
+ LOGGER.info("Order Service Begin ... xid: " + RootContext.getXID());
- int orderMoney = calculate(commodityCode, orderCount);
+ int orderMoney = calculate(commodityCode, orderCount);
- invokerAccountService(orderMoney);
+ invokerAccountService(orderMoney);
- final Order order = new Order();
- order.userId = userId;
- order.commodityCode = commodityCode;
- order.count = orderCount;
- order.money = orderMoney;
+ final Order order = new Order();
+ order.userId = userId;
+ order.commodityCode = commodityCode;
+ order.count = orderCount;
+ order.money = orderMoney;
- KeyHolder keyHolder = new GeneratedKeyHolder();
+ KeyHolder keyHolder = new GeneratedKeyHolder();
- int result = jdbcTemplate.update(new PreparedStatementCreator() {
+ int result = jdbcTemplate.update(new PreparedStatementCreator() {
- @Override
- public PreparedStatement createPreparedStatement(Connection con)
- throws SQLException {
- PreparedStatement pst = con.prepareStatement(
- "insert into order_tbl (user_id, commodity_code, count, money) values (?, ?, ?, ?)",
- PreparedStatement.RETURN_GENERATED_KEYS);
- pst.setObject(1, order.userId);
- pst.setObject(2, order.commodityCode);
- pst.setObject(3, order.count);
- pst.setObject(4, order.money);
- return pst;
- }
- }, keyHolder);
+ @Override
+ public PreparedStatement createPreparedStatement(Connection con)
+ throws SQLException {
+ PreparedStatement pst = con.prepareStatement(
+ "insert into order_tbl (user_id, commodity_code, count, money) values (?, ?, ?, ?)",
+ PreparedStatement.RETURN_GENERATED_KEYS);
+ pst.setObject(1, order.userId);
+ pst.setObject(2, order.commodityCode);
+ pst.setObject(3, order.count);
+ pst.setObject(4, order.money);
+ return pst;
+ }
+ }, keyHolder);
- order.id = (long) keyHolder.getKey();
+ order.id = keyHolder.getKey().longValue();
- if (random.nextBoolean()) {
- throw new RuntimeException("this is a mock Exception");
- }
+// if (random.nextBoolean()) {
+// throw new RuntimeException("this is a mock Exception");
+// }
- LOGGER.info("Order Service End ... Created " + order);
+ LOGGER.info("Order Service End ... Created " + order);
- if (result == 1) {
- return SUCCESS;
- }
- return FAIL;
- }
+ if (result == 1) {
+ return SUCCESS;
+ }
+ return FAIL;
+ }
- private int calculate(String commodityId, int orderCount) {
- return 2 * orderCount;
- }
+ private int calculate(String commodityId, int orderCount) {
+ return 2 * orderCount;
+ }
- private void invokerAccountService(int orderMoney) {
- String url = "http://127.0.0.1:18084/account";
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
+ private void invokerAccountService(int orderMoney) {
+ String url = "http://127.0.0.1:18084/account";
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
- MultiValueMap map = new LinkedMultiValueMap();
+ MultiValueMap map = new LinkedMultiValueMap();
- map.add("userId", USER_ID);
- map.add("money", orderMoney + "");
+ map.add("userId", USER_ID);
+ map.add("money", orderMoney + "");
- HttpEntity> request = new HttpEntity>(
- map, headers);
+ HttpEntity> request = new HttpEntity>(
+ map, headers);
- ResponseEntity response = restTemplate.postForEntity(url, request,
- String.class);
- }
+ ResponseEntity response = restTemplate.postForEntity(url, request,
+ String.class);
+ }
}
diff --git a/spring-cloud-alibaba-examples/fescar-example/order-service/src/main/resources/application.properties b/spring-cloud-alibaba-examples/fescar-example/order-service/src/main/resources/application.properties
index f3e417d8..c88342af 100644
--- a/spring-cloud-alibaba-examples/fescar-example/order-service/src/main/resources/application.properties
+++ b/spring-cloud-alibaba-examples/fescar-example/order-service/src/main/resources/application.properties
@@ -5,5 +5,5 @@ mysql.server.ip=127.0.0.1
mysql.server.port=3306
mysql.db.name=demo
-mysql.user.name=xxxxx
-mysql.user.password=xxxxx
\ No newline at end of file
+mysql.user.name=root
+mysql.user.password=123456
\ No newline at end of file
diff --git a/spring-cloud-alibaba-examples/fescar-example/storage-service/src/main/resources/application.properties b/spring-cloud-alibaba-examples/fescar-example/storage-service/src/main/resources/application.properties
index 832eaecd..b65047c8 100644
--- a/spring-cloud-alibaba-examples/fescar-example/storage-service/src/main/resources/application.properties
+++ b/spring-cloud-alibaba-examples/fescar-example/storage-service/src/main/resources/application.properties
@@ -5,5 +5,5 @@ mysql.server.ip=127.0.0.1
mysql.server.port=3306
mysql.db.name=demo
-mysql.user.name=xxxxx
-mysql.user.password=xxxxx
\ No newline at end of file
+mysql.user.name=root
+mysql.user.password=123456
\ No newline at end of file
diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/bootstrap.properties b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/bootstrap.properties
index 831d8ff7..375be66e 100644
--- a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/bootstrap.properties
+++ b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/bootstrap.properties
@@ -1,4 +1,4 @@
-spring.application.name=sca-nacos-config
+spring.application.name=nacos-config-example
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.shared-data-ids=base-common.properties,common.properties
spring.cloud.nacos.config.refreshable-dataids=common.properties
\ No newline at end of file
diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-discovery-example/pom.xml b/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-discovery-example/pom.xml
index 6af752d7..2aa37cf6 100644
--- a/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-discovery-example/pom.xml
+++ b/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-discovery-example/pom.xml
@@ -19,7 +19,6 @@
org.springframework.cloud
spring-cloud-starter-gateway
- 2.0.2.RELEASE
diff --git a/spring-cloud-alibaba-examples/sms-example/pom.xml b/spring-cloud-alibaba-examples/sms-example/pom.xml
index f466cc66..d405a38d 100644
--- a/spring-cloud-alibaba-examples/sms-example/pom.xml
+++ b/spring-cloud-alibaba-examples/sms-example/pom.xml
@@ -3,47 +3,22 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- alibaba.com
sms-example
- 0.0.1-SNAPSHOT
jar
-
- sms-example
- Demo project for Spring Boot
+ Example demonstrating how to use alicloud sms
- org.springframework.boot
- spring-boot-starter-parent
- 2.0.6.RELEASE
-
+ spring-cloud-alibaba-examples
+ org.springframework.cloud
+ 0.2.2.BUILD-SNAPSHOT
+ ../pom.xml
UTF-8
UTF-8
- 1.8
- Finchley.SR2
- 0.2.2.BUILD-SNAPSHOT
-
-
-
- org.springframework.cloud
- spring-cloud-dependencies
- ${spring-cloud.version}
- pom
- import
-
-
- org.springframework.cloud
- spring-cloud-alibaba-dependencies
- ${spring-cloud-alibaba-alicloud.version}
- pom
- import
-
-
-
@@ -59,11 +34,6 @@
org.springframework.cloud
spring-cloud-starter-alicloud-sms
-
- alibaba.com
- env-extension
- 0.2.2.BUILD-SNAPSHOT
-
@@ -72,6 +42,14 @@
org.springframework.boot
spring-boot-maven-plugin
+
+ org.apache.maven.plugins
+ maven-deploy-plugin
+ ${maven-deploy-plugin.version}
+
+ true
+
+
diff --git a/spring-cloud-alibaba-examples/sms-example/src/main/java/org/springframework/cloud/alibaba/cloud/example/SmsApplication.java b/spring-cloud-alibaba-examples/sms-example/src/main/java/org/springframework/cloud/alibaba/cloud/example/SmsApplication.java
index 83f25a94..abbd8efb 100644
--- a/spring-cloud-alibaba-examples/sms-example/src/main/java/org/springframework/cloud/alibaba/cloud/example/SmsApplication.java
+++ b/spring-cloud-alibaba-examples/sms-example/src/main/java/org/springframework/cloud/alibaba/cloud/example/SmsApplication.java
@@ -15,7 +15,6 @@
*/
package org.springframework.cloud.alibaba.cloud.example;
-import org.springframework.alicloud.env.extension.ImportExtraConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -23,7 +22,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
*
*/
@SpringBootApplication
-@ImportExtraConfig(name = "/Users/toava/sms.properties")
public class SmsApplication {
public static void main(String[] args) throws Exception{
diff --git a/spring-cloud-alibaba-examples/sms-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/sms-example/src/main/resources/application.properties
index 8c689827..4464cfe9 100644
--- a/spring-cloud-alibaba-examples/sms-example/src/main/resources/application.properties
+++ b/spring-cloud-alibaba-examples/sms-example/src/main/resources/application.properties
@@ -1,4 +1,9 @@
spring.application.name=sca-sms-example
server.port=9051
-# config management
+# config sms
+spring.cloud.alicloud.access-key=*****
+spring.cloud.alicloud.secret-key=******
+spring.cloud.alicloud.sms.report-queue-name=*****
+spring.cloud.alicloud.sms.up-queue-name=*****
+#config endpoint
management.endpoints.web.exposure.include=*
\ No newline at end of file
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/pom.xml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/pom.xml
index 93f33466..6a96eb0d 100644
--- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/pom.xml
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/pom.xml
@@ -19,12 +19,11 @@
spring-cloud-dubbo-sample-api
spring-cloud-dubbo-provider-sample
spring-cloud-dubbo-consumer-sample
+ spring-cloud-dubbo-provider-web-sample
- 2.6.5
- 0.2.1.RELEASE
- 0.0.2
+ 2.7.0
2.1.0.RELEASE
2.1.0.RELEASE
4.0.1
@@ -44,7 +43,7 @@
- com.alibaba
+ org.apache.dubbo
dubbo-dependencies-bom
${dubbo.version}
pom
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/bootstrap/DubboSpringCloudConsumerBootstrap.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/bootstrap/DubboSpringCloudConsumerBootstrap.java
index 2d72b79f..8c2a0c9e 100644
--- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/bootstrap/DubboSpringCloudConsumerBootstrap.java
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/bootstrap/DubboSpringCloudConsumerBootstrap.java
@@ -16,8 +16,7 @@
*/
package org.springframework.cloud.alibaba.dubbo.bootstrap;
-import com.alibaba.dubbo.config.annotation.Reference;
-
+import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
@@ -95,7 +94,7 @@ public class DubboSpringCloudConsumerBootstrap {
}
@FeignClient("${provider.application.name}")
- @DubboTransported
+ @DubboTransported()
public interface DubboFeignRestService {
@GetMapping(value = "/param")
@@ -209,7 +208,7 @@ public class DubboSpringCloudConsumerBootstrap {
public static void main(String[] args) {
new SpringApplicationBuilder(DubboSpringCloudConsumerBootstrap.class)
- .profiles("nacos")
+ .properties("spring.profiles.active=nacos")
.run(args);
}
}
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/resources/application.yaml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/resources/application.yaml
index 83d0d835..263a5699 100644
--- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/resources/application.yaml
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/resources/application.yaml
@@ -1,5 +1,12 @@
dubbo:
registry:
- address: spring-cloud://nacos
+ # The Spring Cloud Dubbo's registry extension
+ address: spring-cloud://localhost
+# The traditional Dubbo's registry
+# address: zookeeper://127.0.0.1:2181
server:
- port: 7070
\ No newline at end of file
+ port: 0
+
+provider:
+ application:
+ name: spring-cloud-alibaba-dubbo-web-provider
\ No newline at end of file
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/resources/bootstrap.yaml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/resources/bootstrap.yaml
index 1d25940c..dca555cf 100644
--- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/resources/bootstrap.yaml
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/resources/bootstrap.yaml
@@ -24,10 +24,6 @@ ribbon:
nacos:
enabled: false
-provider:
- application:
- name: spring-cloud-alibaba-dubbo-provider
-
---
spring:
profiles: nacos
@@ -51,7 +47,7 @@ eureka:
client:
enabled: true
service-url:
- defaultZone: http://127.0.0.1:9090/eureka/
+ defaultZone: http://127.0.0.1:8761/eureka/
---
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/pom.xml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/pom.xml
index 9ebd00a1..152e91aa 100644
--- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/pom.xml
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/pom.xml
@@ -17,9 +17,10 @@
+
- org.springframework.boot
- spring-boot-starter-web
+ org.springframework
+ spring-web
@@ -30,6 +31,11 @@
+
+ io.netty
+ netty-all
+
+
org.jboss.resteasy
resteasy-jaxrs
@@ -60,6 +66,11 @@
resteasy-jaxb-provider
+
+ org.hibernate.validator
+ hibernate-validator
+
+
\ No newline at end of file
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/bootstrap/DubboSpringCloudProviderBootstrap.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/bootstrap/DubboSpringCloudProviderBootstrap.java
index 4fbf8ea8..4606a190 100644
--- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/bootstrap/DubboSpringCloudProviderBootstrap.java
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/bootstrap/DubboSpringCloudProviderBootstrap.java
@@ -29,7 +29,7 @@ public class DubboSpringCloudProviderBootstrap {
public static void main(String[] args) {
new SpringApplicationBuilder(DubboSpringCloudProviderBootstrap.class)
- .profiles("nacos")
+ .properties("spring.profiles.active=nacos")
.run(args);
}
}
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/service/StandardRestService.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/service/StandardRestService.java
index 642fdb0d..aeea2b16 100644
--- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/service/StandardRestService.java
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/service/StandardRestService.java
@@ -16,18 +16,9 @@
*/
package org.springframework.cloud.alibaba.dubbo.service;
-import com.alibaba.dubbo.rpc.RpcContext;
-
+import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.http.MediaType;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestHeader;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
@@ -38,9 +29,11 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;
+import static org.springframework.cloud.alibaba.dubbo.util.LoggerUtils.log;
import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;
/**
@@ -48,50 +41,46 @@ import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;
*
* @author Mercy
*/
-@com.alibaba.dubbo.config.annotation.Service(version = "1.0.0", protocol = {"dubbo", "rest"})
-@RestController
+@Service(version = "1.0.0", protocol = {"dubbo", "rest"})
@Path("/")
public class StandardRestService implements RestService {
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
- @GetMapping(value = "/param")
- @Path("/param")
+ @Path("param")
@GET
- public String param(@RequestParam @QueryParam("param") String param) {
+ public String param(@QueryParam("param") String param) {
log("/param", param);
return param;
}
@Override
- @PostMapping("/params")
- @Path("/params")
+ @Path("params")
@POST
- public String params(@RequestParam @QueryParam("a") int a, @RequestParam @QueryParam("b") String b) {
+ public String params(@QueryParam("a") int a, @QueryParam("b") String b) {
log("/params", a + b);
return a + b;
}
@Override
- @GetMapping("/headers")
- @Path("/headers")
+ @Path("headers")
@GET
- public String headers(@RequestHeader("h") @HeaderParam("h") String header,
- @RequestHeader("h2") @HeaderParam("h2") String header2,
- @RequestParam("v") @QueryParam("v") Integer param) {
+ public String headers(@HeaderParam("h") String header,
+ @HeaderParam("h2") String header2,
+ @QueryParam("v")
+ Integer param) {
String result = header + " , " + header2 + " , " + param;
log("/headers", result);
return result;
}
@Override
- @GetMapping("/path-variables/{p1}/{p2}")
- @Path("/path-variables/{p1}/{p2}")
+ @Path("path-variables/{p1}/{p2}")
@GET
- public String pathVariables(@PathVariable("p1") @PathParam("p1") String path1,
- @PathVariable("p2") @PathParam("p2") String path2,
- @RequestParam("v") @QueryParam("v") String param) {
+ public String pathVariables(@PathParam("p1") String path1,
+ @PathParam("p2") String path2,
+ @QueryParam("v") String param) {
String result = path1 + " , " + path2 + " , " + param;
log("/path-variables", result);
return result;
@@ -101,19 +90,17 @@ public class StandardRestService implements RestService {
// @CookieValue also does not support
@Override
- @PostMapping("/form")
- @Path("/form")
+ @Path("form")
@POST
- public String form(@RequestParam("f") @FormParam("f") String form) {
+ public String form(@FormParam("f") String form) {
return String.valueOf(form);
}
@Override
- @PostMapping(value = "/request/body/map", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
- @Path("/request/body/map")
+ @Path("request/body/map")
@POST
@Produces(APPLICATION_JSON_VALUE)
- public User requestBodyMap(@RequestBody Map data, @RequestParam("param") @QueryParam("param") String param) {
+ public User requestBodyMap(Map data, @QueryParam("param") String param) {
User user = new User();
user.setId(((Integer) data.get("id")).longValue());
user.setName((String) data.get("name"));
@@ -122,28 +109,15 @@ public class StandardRestService implements RestService {
return user;
}
- @PostMapping(value = "/request/body/user", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
- @Path("/request/body/user")
+ @Path("request/body/user")
@POST
@Override
- @Consumes(MediaType.APPLICATION_JSON_UTF8_VALUE)
- public Map requestBodyUser(@RequestBody User user) {
+ @Consumes(MediaType.APPLICATION_JSON)
+ public Map requestBodyUser(User user) {
Map map = new HashMap<>();
map.put("id", user.getId());
map.put("name", user.getName());
map.put("age", user.getAge());
return map;
}
-
- private void log(String url, Object result) {
- String message = String.format("The client[%s] uses '%s' protocol to call %s : %s",
- RpcContext.getContext().getRemoteHostName(),
- RpcContext.getContext().getUrl() == null ? "N/A" : RpcContext.getContext().getUrl().getProtocol(),
- url,
- result
- );
- if (logger.isInfoEnabled()) {
- logger.info(message);
- }
- }
}
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/resources/application.yaml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/resources/application.yaml
index 2b3eb54e..056b4856 100644
--- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/resources/application.yaml
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/resources/application.yaml
@@ -4,17 +4,16 @@ dubbo:
protocols:
dubbo:
name: dubbo
- port: 12345
+ port: -1
rest:
name: rest
- port: 8081
+ port: 9090
server: netty
registry:
- address: spring-cloud://nacos
-
+# The Spring Cloud Dubbo's registry extension
+ address: spring-cloud://localhost
+# The traditional Dubbo's registry
+# address: zookeeper://127.0.0.1:2181
feign:
hystrix:
- enabled: true
-
-server:
- port: 8080
\ No newline at end of file
+ enabled: true
\ No newline at end of file
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/resources/bootstrap.yaml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/resources/bootstrap.yaml
index c845d8ca..0d8dfca9 100644
--- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/resources/bootstrap.yaml
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/resources/bootstrap.yaml
@@ -4,6 +4,7 @@ spring:
main:
allow-bean-definition-overriding: true
+
# default disable all
cloud:
nacos:
@@ -40,7 +41,7 @@ eureka:
client:
enabled: true
service-url:
- defaultZone: http://127.0.0.1:9090/eureka/
+ defaultZone: http://127.0.0.1:8761/eureka/
---
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/pom.xml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/pom.xml
new file mode 100644
index 00000000..af30d4b2
--- /dev/null
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/pom.xml
@@ -0,0 +1,33 @@
+
+
+
+ spring-cloud-alibaba-dubbo-examples
+ org.springframework.cloud
+ 0.2.2.BUILD-SNAPSHOT
+ ../pom.xml
+
+ 4.0.0
+
+ org.springframework.cloud
+ spring-cloud-dubbo-provider-web-sample
+ Spring Cloud Dubbo Provider Web Sample
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+
+ org.springframework.cloud
+ spring-cloud-dubbo-sample-api
+ ${project.version}
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/bootstrap/DubboSpringCloudWebProviderBootstrap.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/bootstrap/DubboSpringCloudWebProviderBootstrap.java
new file mode 100644
index 00000000..799a3a74
--- /dev/null
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/bootstrap/DubboSpringCloudWebProviderBootstrap.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.dubbo.bootstrap;
+
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.builder.SpringApplicationBuilder;
+import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
+
+/**
+ * Dubbo Spring Cloud Provider Bootstrap
+ */
+@EnableDiscoveryClient
+@EnableAutoConfiguration
+public class DubboSpringCloudWebProviderBootstrap {
+
+ public static void main(String[] args) {
+ new SpringApplicationBuilder(DubboSpringCloudWebProviderBootstrap.class)
+ .properties("spring.profiles.active=nacos")
+ .run(args);
+ }
+}
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/service/SpringRestService.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/service/SpringRestService.java
new file mode 100644
index 00000000..f39fd70e
--- /dev/null
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/org/springframework/cloud/alibaba/dubbo/service/SpringRestService.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.dubbo.service;
+
+import org.apache.dubbo.config.annotation.Service;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.springframework.cloud.alibaba.dubbo.util.LoggerUtils.log;
+
+/**
+ * Spring MVC {@link RestService}
+ *
+ * @author Mercy
+ */
+@Service(version = "1.0.0")
+@RestController
+public class SpringRestService implements RestService {
+
+ private Logger logger = LoggerFactory.getLogger(getClass());
+
+ @Override
+ @GetMapping(value = "/param")
+ public String param(@RequestParam String param) {
+ log("/param", param);
+ return param;
+ }
+
+ @Override
+ @PostMapping("/params")
+ public String params(@RequestParam int a, @RequestParam String b) {
+ log("/params", a + b);
+ return a + b;
+ }
+
+ @Override
+ @GetMapping("/headers")
+ public String headers(@RequestHeader("h") String header,
+ @RequestHeader("h2") String header2,
+ @RequestParam("v") Integer param) {
+ String result = header + " , " + header2 + " , " + param;
+ log("/headers", result);
+ return result;
+ }
+
+ @Override
+ @GetMapping("/path-variables/{p1}/{p2}")
+ public String pathVariables(@PathVariable("p1") String path1,
+ @PathVariable("p2") String path2,
+ @RequestParam("v") String param) {
+ String result = path1 + " , " + path2 + " , " + param;
+ log("/path-variables", result);
+ return result;
+ }
+
+ @Override
+ @PostMapping("/form")
+ public String form(@RequestParam("f") String form) {
+ return String.valueOf(form);
+ }
+
+ @Override
+ @PostMapping(value = "/request/body/map", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
+ public User requestBodyMap(@RequestBody Map data, @RequestParam("param") String param) {
+ User user = new User();
+ user.setId(((Integer) data.get("id")).longValue());
+ user.setName((String) data.get("name"));
+ user.setAge((Integer) data.get("age"));
+ log("/request/body/map", param);
+ return user;
+ }
+
+ @PostMapping(value = "/request/body/user", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
+ @Override
+ public Map requestBodyUser(@RequestBody User user) {
+ Map map = new HashMap<>();
+ map.put("id", user.getId());
+ map.put("name", user.getName());
+ map.put("age", user.getAge());
+ return map;
+ }
+
+}
+
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/resources/application.yaml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/resources/application.yaml
new file mode 100644
index 00000000..a890294c
--- /dev/null
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/resources/application.yaml
@@ -0,0 +1,19 @@
+dubbo:
+ scan:
+ base-packages: org.springframework.cloud.alibaba.dubbo.service
+ protocols:
+ dubbo:
+ name: dubbo
+ port: -1
+ registry:
+# The Spring Cloud Dubbo's registry extension
+ address: spring-cloud://localhost
+# The traditional Dubbo's registry
+# address: zookeeper://127.0.0.1:2181
+
+feign:
+ hystrix:
+ enabled: true
+
+server:
+ port: 8080
\ No newline at end of file
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/resources/bootstrap.yaml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/resources/bootstrap.yaml
new file mode 100644
index 00000000..fd82247b
--- /dev/null
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/resources/bootstrap.yaml
@@ -0,0 +1,64 @@
+spring:
+ application:
+ name: spring-cloud-alibaba-dubbo-web-provider
+ main:
+ allow-bean-definition-overriding: true
+
+
+ # default disable all
+ cloud:
+ nacos:
+ discovery:
+ enabled: false
+ register-enabled: false
+ zookeeper:
+ enabled: false
+ consul:
+ enabled: false
+
+eureka:
+ client:
+ enabled: false
+
+
+---
+spring:
+ profiles: nacos
+
+ cloud:
+ nacos:
+ discovery:
+ enabled: true
+ register-enabled: true
+ server-addr: 127.0.0.1:8848
+
+
+---
+spring:
+ profiles: eureka
+
+eureka:
+ client:
+ enabled: true
+ service-url:
+ defaultZone: http://127.0.0.1:8761/eureka/
+
+
+---
+spring:
+ profiles: zookeeper
+ cloud:
+ zookeeper:
+ enabled: true
+ connect-string: 127.0.0.1:2181
+
+
+---
+spring:
+ profiles: consul
+
+ cloud:
+ consul:
+ enabled: true
+ host: 127.0.0.1
+ port: 8500
\ No newline at end of file
diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/org/springframework/cloud/alibaba/dubbo/util/LoggerUtils.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/org/springframework/cloud/alibaba/dubbo/util/LoggerUtils.java
new file mode 100644
index 00000000..1985c283
--- /dev/null
+++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/org/springframework/cloud/alibaba/dubbo/util/LoggerUtils.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.dubbo.util;
+
+import org.apache.dubbo.rpc.RpcContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Logger Utilities
+ */
+public abstract class LoggerUtils {
+
+ private static final Logger logger = LoggerFactory.getLogger(LoggerUtils.class);
+
+ public static void log(String url, Object result) {
+ String message = String.format("The client[%s] uses '%s' protocol to call %s : %s",
+ RpcContext.getContext().getRemoteHostName(),
+ RpcContext.getContext().getUrl() == null ? "N/A" : RpcContext.getContext().getUrl().getProtocol(),
+ url,
+ result
+ );
+ if (logger.isInfoEnabled()) {
+ logger.info(message);
+ }
+ }
+}
diff --git a/spring-cloud-alibaba-fescar/src/main/java/org/springframework/cloud/alibaba/fescar/rest/FescarRestTemplateAutoConfiguration.java b/spring-cloud-alibaba-fescar/src/main/java/org/springframework/cloud/alibaba/fescar/rest/FescarRestTemplateAutoConfiguration.java
index 91191ed0..11fde4df 100644
--- a/spring-cloud-alibaba-fescar/src/main/java/org/springframework/cloud/alibaba/fescar/rest/FescarRestTemplateAutoConfiguration.java
+++ b/spring-cloud-alibaba-fescar/src/main/java/org/springframework/cloud/alibaba/fescar/rest/FescarRestTemplateAutoConfiguration.java
@@ -31,18 +31,17 @@
package org.springframework.cloud.alibaba.fescar.rest;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import javax.annotation.PostConstruct;
-
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;
+import javax.annotation.PostConstruct;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
/**
* @author xiaojing
*/
diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigAutoConfiguration.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigAutoConfiguration.java
index 3833293e..caacccd8 100644
--- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigAutoConfiguration.java
+++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigAutoConfiguration.java
@@ -17,6 +17,7 @@
package org.springframework.cloud.alibaba.nacos;
import org.springframework.beans.factory.BeanFactoryUtils;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.alibaba.nacos.refresh.NacosContextRefresher;
import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshHistory;
import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshProperties;
@@ -28,6 +29,7 @@ import org.springframework.context.annotation.Configuration;
* @author juven.xuxb
*/
@Configuration
+@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public class NacosConfigAutoConfiguration {
@Bean
diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigBootstrapConfiguration.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigBootstrapConfiguration.java
index 94933a4d..5a6ad2bb 100644
--- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigBootstrapConfiguration.java
+++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigBootstrapConfiguration.java
@@ -26,6 +26,7 @@ import org.springframework.context.annotation.Configuration;
* @author xiaojing
*/
@Configuration
+@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public class NacosConfigBootstrapConfiguration {
@Bean
@@ -35,7 +36,6 @@ public class NacosConfigBootstrapConfiguration {
}
@Bean
- @ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public NacosPropertySourceLocator nacosPropertySourceLocator(
NacosConfigProperties nacosConfigProperties) {
return new NacosPropertySourceLocator(nacosConfigProperties);
diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigProperties.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigProperties.java
index 5d13c01c..1518dcff 100644
--- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigProperties.java
+++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/NacosConfigProperties.java
@@ -55,11 +55,6 @@ public class NacosConfigProperties {
private static final Logger log = LoggerFactory
.getLogger(NacosConfigProperties.class);
- /**
- * whether to enable nacos config.
- */
- private boolean enabled = true;
-
/**
* nacos config server address
*/
@@ -122,8 +117,6 @@ public class NacosConfigProperties {
private String name;
- private String[] activeProfiles;
-
/**
* the dataids for configurable multiple shared configurations , multiple separated by
* commas .
@@ -142,24 +135,8 @@ public class NacosConfigProperties {
private ConfigService configService;
- @Autowired
- private Environment environment;
-
- @PostConstruct
- public void init() {
- this.activeProfiles = environment.getActiveProfiles();
- }
-
// todo sts support
- public boolean isEnabled() {
- return enabled;
- }
-
- public void setEnabled(boolean enabled) {
- this.enabled = enabled;
- }
-
public String getServerAddr() {
return serverAddr;
}
@@ -260,10 +237,6 @@ public class NacosConfigProperties {
return name;
}
- public String[] getActiveProfiles() {
- return activeProfiles;
- }
-
public String getSharedDataids() {
return sharedDataids;
}
@@ -292,10 +265,6 @@ public class NacosConfigProperties {
this.name = name;
}
- public void setActiveProfiles(String[] activeProfiles) {
- this.activeProfiles = activeProfiles;
- }
-
public static class Config {
/**
* the data id of extended configuration
@@ -337,17 +306,15 @@ public class NacosConfigProperties {
@Override
public String toString() {
- 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 + '}';
+ return "NacosConfigProperties{" + "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 + '\''
+ + ", sharedDataids='" + sharedDataids + '\'' + ", refreshableDataids='"
+ + refreshableDataids + '\'' + ", extConfig=" + extConfig + '}';
}
public ConfigService configServiceInstance() {
diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceLocator.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceLocator.java
index 4c560658..306066eb 100644
--- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceLocator.java
+++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceLocator.java
@@ -71,7 +71,6 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
timeout);
String name = nacosConfigProperties.getName();
- String nacosGroup = nacosConfigProperties.getGroup();
String dataIdPrefix = nacosConfigProperties.getPrefix();
if (StringUtils.isEmpty(dataIdPrefix)) {
dataIdPrefix = name;
@@ -81,17 +80,12 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
dataIdPrefix = env.getProperty("spring.application.name");
}
- List profiles = Arrays.asList(env.getActiveProfiles());
- nacosConfigProperties.setActiveProfiles(profiles.toArray(new String[0]));
-
- String fileExtension = nacosConfigProperties.getFileExtension();
-
CompositePropertySource composite = new CompositePropertySource(
NACOS_PROPERTY_SOURCE_NAME);
loadSharedConfiguration(composite);
loadExtConfiguration(composite);
- loadApplicationConfiguration(composite, nacosGroup, dataIdPrefix, fileExtension);
+ loadApplicationConfiguration(composite, dataIdPrefix, nacosConfigProperties, env);
return composite;
}
@@ -152,11 +146,15 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
}
private void loadApplicationConfiguration(
- CompositePropertySource compositePropertySource, String nacosGroup,
- String dataIdPrefix, String fileExtension) {
+ CompositePropertySource compositePropertySource, String dataIdPrefix,
+ NacosConfigProperties properties, Environment environment) {
+
+ String fileExtension = properties.getFileExtension();
+ String nacosGroup = properties.getGroup();
+
loadNacosDataIfPresent(compositePropertySource,
dataIdPrefix + DOT + fileExtension, nacosGroup, fileExtension, true);
- for (String profile : nacosConfigProperties.getActiveProfiles()) {
+ for (String profile : environment.getActiveProfiles()) {
String dataId = dataIdPrefix + SEP1 + profile + DOT + fileExtension;
loadNacosDataIfPresent(compositePropertySource, dataId, nacosGroup,
fileExtension, true);
diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java
index e853546d..21d77f7f 100644
--- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java
+++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java
@@ -21,6 +21,7 @@ import org.springframework.boot.actuate.autoconfigure.endpoint.condition.Conditi
import org.springframework.boot.actuate.endpoint.annotation.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.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.cloud.alibaba.nacos.NacosConfigProperties;
import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshHistory;
@@ -31,6 +32,7 @@ import org.springframework.context.annotation.Bean;
*/
@ConditionalOnWebApplication
@ConditionalOnClass(value = Endpoint.class)
+@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public class NacosConfigEndpointAutoConfiguration {
@Autowired
diff --git a/spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json
index 3ce2a169..597126e8 100644
--- a/spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json
+++ b/spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json
@@ -32,6 +32,12 @@
"name": "spring.cloud.nacos.config.ext-config",
"type": "java.util.List",
"description": "a set of extended configurations ."
+ },
+ {
+ "name": "spring.cloud.nacos.config.enabled",
+ "type": "java.lang.Boolean",
+ "defaultValue": true,
+ "description": "enable nacos config or not."
}
]
}
\ No newline at end of file
diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/EndpointTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/EndpointTests.java
deleted file mode 100644
index 5ef53f03..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/EndpointTests.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.cloud.alibaba.nacos;
-
-import org.junit.Test;
-import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigEndpoint;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * @author pbting
- * @date 2019-01-17 2:25 PM
- */
-public class EndpointTests extends NacosPowerMockitBaseTests {
-
- @Test
- public void nacosConfigEndpoint() {
-
- NacosConfigEndpoint nacosConfigEndpoint = super.context
- .getBean(NacosConfigEndpoint.class);
- assertThat(nacosConfigEndpoint != null).isEqualTo(true);
- }
-
- @Test
- public void endpointInvoke() {
- NacosConfigEndpoint nacosConfigEndpoint = this.context
- .getBean(NacosConfigEndpoint.class);
- assertThat(nacosConfigEndpoint.invoke() != null).isEqualTo(true);
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigAutoConfigurationTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigAutoConfigurationTests.java
deleted file mode 100644
index f8c29c46..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigAutoConfigurationTests.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2018 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.alibaba.nacos;
-
-import org.junit.Test;
-import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceLocator;
-import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshProperties;
-import org.springframework.core.env.CompositePropertySource;
-import org.springframework.core.env.PropertySource;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * @author xiaojing
- * @author pbting
- */
-public class NacosConfigAutoConfigurationTests extends NacosPowerMockitBaseTests {
- @Test
- public void testNacosConfigProperties() {
-
- NacosConfigProperties nacosConfigProperties = context.getParent()
- .getBean(NacosConfigProperties.class);
- assertThat(nacosConfigProperties.getFileExtension()).isEqualTo("properties");
- assertThat(nacosConfigProperties.getPrefix() == null).isEqualTo(true);
- assertThat(nacosConfigProperties.getNamespace() == null).isEqualTo(true);
- assertThat(nacosConfigProperties.getName()).isEqualTo("sca-nacos-config");
- assertThat(nacosConfigProperties.getServerAddr()).isEqualTo("127.0.0.1:8848");
- assertThat(nacosConfigProperties.getEncode()).isEqualTo("utf-8");
- assertThat(nacosConfigProperties.getActiveProfiles())
- .isEqualTo(new String[] { "develop" });
- assertThat(nacosConfigProperties.getSharedDataids())
- .isEqualTo("base-common.properties,common.properties");
- assertThat(nacosConfigProperties.getRefreshableDataids())
- .isEqualTo("common.properties");
- assertThat(nacosConfigProperties.getExtConfig().size()).isEqualTo(3);
- assertThat(nacosConfigProperties.getExtConfig().get(0).getDataId())
- .isEqualTo("ext00.yaml");
- assertThat(nacosConfigProperties.getExtConfig().get(1).getGroup())
- .isEqualTo("EXT01_GROUP");
- assertThat(nacosConfigProperties.getExtConfig().get(1).isRefresh())
- .isEqualTo(true);
- }
-
- @Test
- public void nacosPropertySourceLocator() {
- NacosPropertySourceLocator nacosPropertySourceLocator = this.context
- .getBean(NacosPropertySourceLocator.class);
- PropertySource propertySource = nacosPropertySourceLocator
- .locate(this.context.getEnvironment());
- assertThat(propertySource instanceof CompositePropertySource).isEqualTo(true);
- }
-
- @Test
- public void testNacosRefreshProperties() {
-
- NacosRefreshProperties nacosRefreshProperties = this.context
- .getBean(NacosRefreshProperties.class);
- assertThat(nacosRefreshProperties.isEnabled()).isEqualTo(true);
-
- }
-
-}
diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigHealthIndicatorTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigHealthIndicatorTests.java
deleted file mode 100644
index 1fd434b5..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigHealthIndicatorTests.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.cloud.alibaba.nacos;
-
-import org.junit.Test;
-import org.springframework.boot.actuate.health.Health;
-import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigHealthIndicator;
-import org.springframework.util.ReflectionUtils;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * @author pbting
- * @date 2019-01-17 2:58 PM
- */
-public class NacosConfigHealthIndicatorTests extends NacosPowerMockitBaseTests {
-
- @Test
- public void nacosConfigHealthIndicatorInstance() {
- NacosConfigHealthIndicator nacosConfigHealthIndicator = this.context
- .getBean(NacosConfigHealthIndicator.class);
-
- assertThat(nacosConfigHealthIndicator != null).isEqualTo(true);
- }
-
- @Test
- public void testHealthCheck() {
-
- NacosConfigHealthIndicator nacosConfigHealthIndicator = this.context
- .getBean(NacosConfigHealthIndicator.class);
-
- Health.Builder builder = Health.up();
-
- Method method = ReflectionUtils.findMethod(NacosConfigHealthIndicator.class,
- "doHealthCheck", Health.Builder.class);
- ReflectionUtils.makeAccessible(method);
- assertThat(method != null).isEqualTo(true);
-
- try {
- method.invoke(nacosConfigHealthIndicator, builder);
- assertThat(builder != null).isEqualTo(true);
- }
- catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- catch (InvocationTargetException e) {
- e.printStackTrace();
- }
-
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigurationExtConfigTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigurationExtConfigTests.java
new file mode 100644
index 00000000..cc7098b1
--- /dev/null
+++ b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigurationExtConfigTests.java
@@ -0,0 +1,153 @@
+/*
+ * 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 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.nacos.client.config.NacosConfigService;
+
+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.PowerMockIgnore;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.powermock.modules.junit4.PowerMockRunnerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceLocator;
+import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.env.Environment;
+import org.springframework.test.context.junit4.SpringRunner;
+
+/**
+ * @author xiaojing
+ */
+
+@RunWith(PowerMockRunner.class)
+@PowerMockIgnore("javax.management.*")
+@PowerMockRunnerDelegate(SpringRunner.class)
+@PrepareForTest({ NacosConfigService.class })
+@SpringBootTest(classes = NacosConfigurationExtConfigTests.TestConfig.class, properties = {
+ "spring.application.name=myTestService1", "spring.profiles.active=dev,test",
+ "spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
+ "spring.cloud.nacos.config.encode=utf-8",
+ "spring.cloud.nacos.config.timeout=1000",
+ "spring.cloud.nacos.config.file-extension=properties",
+
+ "spring.cloud.nacos.config.ext-config[0].data-id=ext-config-common01.properties",
+
+ "spring.cloud.nacos.config.ext-config[1].data-id=ext-config-common02.properties",
+ "spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
+
+ "spring.cloud.nacos.config.shared-dataids=common1.properties,common2.properties",
+
+ "spring.cloud.nacos.config.accessKey=test-accessKey",
+ "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
+public class NacosConfigurationExtConfigTests {
+
+ static {
+
+ try {
+ // when(any(ConfigService.class).getConfig(eq("test-name.properties"),
+ // eq("test-group"), any())).thenReturn("user.name=hello");
+
+ Method method = PowerMockito.method(NacosConfigService.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";
+ }
+
+ if ("test-name-dev.properties".equals(args[0])
+ && "DEFAULT_GROUP".equals(args[1])) {
+ return "user.name=dev";
+ }
+
+ if ("ext-config-common01.properties".equals(args[0])
+ && "DEFAULT_GROUP".equals(args[1])) {
+ return "test-ext-config1=config1\ntest-ext-config2=config1";
+ }
+ if ("ext-config-common02.properties".equals(args[0])
+ && "GLOBAL_GROUP".equals(args[1])) {
+ return "test-ext-config2=config2";
+ }
+
+ if ("common1.properties".equals(args[0])
+ && "DEFAULT_GROUP".equals(args[1])) {
+ return "test-common1=common1\ntest-common2=common1";
+ }
+
+ if ("common2.properties".equals(args[0])
+ && "DEFAULT_GROUP".equals(args[1])) {
+ return "test-common2=common2";
+ }
+
+ return "";
+ }
+ });
+
+ }
+ catch (Exception ignore) {
+ ignore.printStackTrace();
+
+ }
+ }
+
+ @Autowired
+ private Environment environment;
+
+ @Autowired
+ private NacosPropertySourceLocator locator;
+
+ @Autowired
+ private NacosConfigProperties properties;
+
+ @Test
+ public void contextLoads() throws Exception {
+
+ assertNotNull("NacosPropertySourceLocator was not created", locator);
+ assertNotNull("NacosConfigProperties was not created", properties);
+
+ Assert.assertEquals(environment.getProperty("test-ext-config1"), "config1");
+ Assert.assertEquals(environment.getProperty("test-ext-config2"), "config2");
+ Assert.assertEquals(environment.getProperty("test-common1"), "common1");
+ Assert.assertEquals(environment.getProperty("test-common2"), "common2");
+
+ }
+
+ @Configuration
+ @EnableAutoConfiguration
+ @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
+ NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
+ public static class TestConfig {
+ }
+}
diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigurationTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigurationTests.java
new file mode 100644
index 00000000..fc2a3b12
--- /dev/null
+++ b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigurationTests.java
@@ -0,0 +1,255 @@
+/*
+ * 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 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 java.util.Map;
+
+import com.alibaba.nacos.client.config.NacosConfigService;
+
+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.PowerMockIgnore;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.powermock.modules.junit4.PowerMockRunnerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceLocator;
+import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigEndpoint;
+import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
+import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshHistory;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.env.Environment;
+import org.springframework.test.context.junit4.SpringRunner;
+
+/**
+ * @author xiaojing
+ */
+
+@RunWith(PowerMockRunner.class)
+@PowerMockIgnore("javax.management.*")
+@PowerMockRunnerDelegate(SpringRunner.class)
+@PrepareForTest({ NacosConfigService.class })
+@SpringBootTest(classes = NacosConfigurationTests.TestConfig.class, properties = {
+ "spring.application.name=myTestService1", "spring.profiles.active=dev,test",
+ "spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
+ "spring.cloud.nacos.config.endpoint=test-endpoint",
+ "spring.cloud.nacos.config.namespace=test-namespace",
+ "spring.cloud.nacos.config.encode=utf-8",
+ "spring.cloud.nacos.config.timeout=1000",
+ "spring.cloud.nacos.config.group=test-group",
+ "spring.cloud.nacos.config.name=test-name",
+ "spring.cloud.nacos.config.cluster-name=test-cluster",
+ "spring.cloud.nacos.config.file-extension=properties",
+ "spring.cloud.nacos.config.contextPath=test-contextpath",
+
+ "spring.cloud.nacos.config.ext-config[0].data-id=ext-config-common01.properties",
+
+ "spring.cloud.nacos.config.ext-config[1].data-id=ext-config-common02.properties",
+ "spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
+
+ "spring.cloud.nacos.config.shared-dataids=common1.properties,common2.properties",
+
+ "spring.cloud.nacos.config.accessKey=test-accessKey",
+ "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
+public class NacosConfigurationTests {
+
+ static {
+
+ try {
+ // when(any(ConfigService.class).getConfig(eq("test-name.properties"),
+ // eq("test-group"), any())).thenReturn("user.name=hello");
+
+ Method method = PowerMockito.method(NacosConfigService.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";
+ }
+
+ if ("ext-config-common01.properties".equals(args[0])
+ && "DEFAULT_GROUP".equals(args[1])) {
+ return "test-ext-config1=config1\ntest-ext-config2=config1";
+ }
+ if ("ext-config-common02.properties".equals(args[0])
+ && "GLOBAL_GROUP".equals(args[1])) {
+ return "test-ext-config2=config2";
+ }
+
+ if ("common1.properties".equals(args[0])
+ && "DEFAULT_GROUP".equals(args[1])) {
+ return "test-common1=common1\ntest-common2=common1";
+ }
+
+ if ("common2.properties".equals(args[0])
+ && "DEFAULT_GROUP".equals(args[1])) {
+ return "test-common2=common2";
+ }
+
+ return "";
+ }
+ });
+
+ }
+ catch (Exception ignore) {
+ ignore.printStackTrace();
+
+ }
+ }
+
+ @Autowired
+ private Environment environment;
+
+ @Autowired
+ private NacosPropertySourceLocator locator;
+
+ @Autowired
+ private NacosConfigProperties properties;
+
+ @Autowired
+ private NacosRefreshHistory refreshHistory;
+
+ @Test
+ public void contextLoads() throws Exception {
+
+ assertNotNull("NacosPropertySourceLocator was not created", locator);
+ assertNotNull("NacosConfigProperties was not created", properties);
+
+ checkoutNacosConfigServerAddr();
+ checkoutNacosConfigEndpoint();
+ checkoutNacosConfigNamespace();
+ checkoutNacosConfigClusterName();
+ checkoutNacosConfigAccessKey();
+ checkoutNacosConfigSecrectKey();
+ checkoutNacosConfigName();
+ checkoutNacosConfigGroup();
+ checkoutNacosConfigContextPath();
+ checkoutNacosConfigFileExtension();
+ checkoutNacosConfigTimeout();
+ checkoutNacosConfigEncode();
+
+ checkoutEndpoint();
+ checkoutDataLoad();
+
+ }
+
+ private void checkoutNacosConfigServerAddr() {
+ assertEquals("NacosConfigProperties server address is wrong", "127.0.0.1:8848",
+ properties.getServerAddr());
+
+ }
+
+ private void checkoutNacosConfigEndpoint() {
+ assertEquals("NacosConfigProperties endpoint is wrong", "test-endpoint",
+ properties.getEndpoint());
+
+ }
+
+ private void checkoutNacosConfigNamespace() {
+ assertEquals("NacosConfigProperties namespace is wrong", "test-namespace",
+ properties.getNamespace());
+
+ }
+
+ private void checkoutNacosConfigClusterName() {
+ assertEquals("NacosConfigProperties' cluster is wrong", "test-cluster",
+ properties.getClusterName());
+ }
+
+ private void checkoutNacosConfigAccessKey() {
+ assertEquals("NacosConfigProperties' is access key is wrong", "test-accessKey",
+ properties.getAccessKey());
+ }
+
+ private void checkoutNacosConfigSecrectKey() {
+ assertEquals("NacosConfigProperties' is secret key is wrong", "test-secretKey",
+ properties.getSecretKey());
+ }
+
+ private void checkoutNacosConfigContextPath() {
+ assertEquals("NacosConfigProperties' context path is wrong", "test-contextpath",
+ properties.getContextPath());
+ }
+
+ private void checkoutNacosConfigName() {
+ assertEquals("NacosConfigProperties' name is wrong", "test-name",
+ properties.getName());
+ }
+
+ private void checkoutNacosConfigGroup() {
+ assertEquals("NacosConfigProperties' group is wrong", "test-group",
+ properties.getGroup());
+ }
+
+ private void checkoutNacosConfigFileExtension() {
+ assertEquals("NacosConfigProperties' file extension is wrong", "properties",
+ properties.getFileExtension());
+ }
+
+ private void checkoutNacosConfigTimeout() {
+ assertEquals("NacosConfigProperties' timeout is wrong", 1000,
+ properties.getTimeout());
+ }
+
+ private void checkoutNacosConfigEncode() {
+ assertEquals("NacosConfigProperties' encode is wrong", "utf-8",
+ properties.getEncode());
+ }
+
+ private void checkoutDataLoad() {
+
+ Assert.assertEquals(environment.getProperty("user.name"), "dev");
+ Assert.assertEquals(environment.getProperty("user.age"), "12");
+ }
+
+ private void checkoutEndpoint() throws Exception {
+ NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties,
+ refreshHistory);
+ Map map = nacosConfigEndpoint.invoke();
+ assertEquals(map.get("NacosConfigProperties"), properties);
+ assertEquals(map.get("RefreshHistory"), refreshHistory.getRecords());
+ }
+
+ @Configuration
+ @EnableAutoConfiguration
+ @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
+ NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
+ public static class TestConfig {
+ }
+}
diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosFileExtensionTest.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosFileExtensionTest.java
new file mode 100644
index 00000000..979cac3f
--- /dev/null
+++ b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosFileExtensionTest.java
@@ -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.alibaba.nacos;
+
+import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+
+import com.alibaba.nacos.client.config.NacosConfigService;
+
+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.PowerMockIgnore;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.powermock.modules.junit4.PowerMockRunnerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.env.Environment;
+import org.springframework.test.context.junit4.SpringRunner;
+
+/**
+ * @author xiaojing
+ */
+
+@RunWith(PowerMockRunner.class)
+@PowerMockIgnore("javax.management.*")
+@PowerMockRunnerDelegate(SpringRunner.class)
+@PrepareForTest({ NacosConfigService.class })
+@SpringBootTest(classes = NacosFileExtensionTest.TestConfig.class, properties = {
+ "spring.application.name=test-name",
+ "spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
+ "spring.cloud.nacos.config.file-extension=yaml" }, webEnvironment = NONE)
+public class NacosFileExtensionTest {
+
+ static {
+
+ try {
+ Method method = PowerMockito.method(NacosConfigService.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({ NacosConfigEndpointAutoConfiguration.class,
+ NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
+ public static class TestConfig {
+ }
+}
diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosPowerMockitBaseTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosPowerMockitBaseTests.java
deleted file mode 100644
index ada71a9c..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosPowerMockitBaseTests.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Copyright (C) 2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.cloud.alibaba.nacos;
-
-import com.alibaba.nacos.api.config.ConfigService;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.api.support.MethodProxy;
-import org.powermock.core.classloader.annotations.PowerMockIgnore;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-import org.powermock.modules.junit4.PowerMockRunnerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
-import org.springframework.boot.autoconfigure.AutoConfigureBefore;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.cloud.alibaba.nacos.client.NacosPropertySource;
-import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceBuilder;
-import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
-import org.springframework.cloud.context.refresh.ContextRefresher;
-import org.springframework.cloud.context.scope.refresh.RefreshScope;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.util.ReflectionUtils;
-
-import java.io.IOException;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * @author pbting
- * @date 2019-01-17 8:54 PM
- */
-@RunWith(PowerMockRunner.class)
-@PowerMockRunnerDelegate(SpringRunner.class)
-@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*" })
-@PrepareForTest({ NacosPropertySourceBuilder.class })
-@SpringBootTest(classes = { NacosConfigBootstrapConfiguration.class,
- NacosConfigEndpointAutoConfiguration.class, NacosConfigAutoConfiguration.class,
- NacosPowerMockitBaseTests.TestConfiguration.class }, properties = {
- "spring.application.name=sca-nacos-config",
- "spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
- "spring.cloud.nacos.config.name=sca-nacos-config",
- // "spring.cloud.nacos.config.refresh.enabled=false",
- "spring.cloud.nacos.config.encode=utf-8",
- "spring.cloud.nacos.config.shared-data-ids=base-common.properties,common.properties",
- "spring.cloud.nacos.config.refreshable-dataids=common.properties",
- "spring.cloud.nacos.config.ext-config[0].data-id=ext00.yaml",
- "spring.cloud.nacos.config.ext-config[1].data-id=ext01.yml",
- "spring.cloud.nacos.config.ext-config[1].group=EXT01_GROUP",
- "spring.cloud.nacos.config.ext-config[1].refresh=true",
- "spring.cloud.nacos.config.ext-config[2].data-id=ext02.yaml",
- "spring.profiles.active=develop", "server.port=19090" })
-public class NacosPowerMockitBaseTests {
-
- private final static List DATAIDS = Arrays.asList("common.properties",
- "base-common.properties", "ext00.yaml", "ext01.yml", "ext02.yaml",
- "sca-nacos-config.properties", "sca-nacos-config-develop.properties");
-
- private final static HashMap VALUES = new HashMap<>();
-
- @Autowired
- protected ApplicationContext context;
-
- static {
- initDataIds();
- try {
- final Constructor constructor = ReflectionUtils.accessibleConstructor(
- NacosPropertySource.class, String.class, String.class, Map.class,
- Date.class, boolean.class);
- Method method = PowerMockito.method(NacosPropertySourceBuilder.class, "build",
- String.class, String.class, String.class, boolean.class);
- MethodProxy.proxy(method, new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- Properties properties = VALUES.get(args[0].toString());
- if (properties == null) {
- properties = new Properties();
- properties.put("user.name", args[0].toString());
- }
- Object instance = constructor.newInstance(args[1].toString(),
- args[0].toString(), properties, new Date(), args[3]);
- return instance;
- }
- });
- }
- catch (NoSuchMethodException e) {
- e.printStackTrace();
- }
- }
-
- private static void initDataIds() {
- DATAIDS.forEach(dataId -> {
- String realpath = "/" + dataId;
- ClassPathResource classPathResource = new ClassPathResource(realpath);
- if (realpath.endsWith("properties")) {
- Properties properties = new Properties();
- try {
- properties.load(classPathResource.getInputStream());
- VALUES.put(dataId, properties);
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- if (realpath.endsWith("yaml") || realpath.endsWith("yml")) {
- YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
- yamlFactory.setResources(classPathResource);
- try {
- VALUES.put(dataId, yamlFactory.getObject());
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- }
-
- public NacosPropertySourceBuilder nacosPropertySourceBuilderInstance() {
- NacosConfigProperties nacosConfigProperties = this.context
- .getBean(NacosConfigProperties.class);
-
- ConfigService configService = nacosConfigProperties.configServiceInstance();
- long timeout = nacosConfigProperties.getTimeout();
- NacosPropertySourceBuilder nacosPropertySourceBuilder = new NacosPropertySourceBuilder(
- configService, timeout);
- return nacosPropertySourceBuilder;
- }
-
- @Configuration
- @AutoConfigureBefore(NacosConfigAutoConfiguration.class)
- static class TestConfiguration {
-
- @Autowired
- ConfigurableApplicationContext context;
-
- @Bean
- ContextRefresher contextRefresher() {
- RefreshScope refreshScope = new RefreshScope();
- refreshScope.setApplicationContext(context);
- return new ContextRefresher(context, refreshScope);
- }
- }
-
- @Test
- public void testAppContext() {
- System.err.println(this.context);
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosPropertySourceBuilderTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosPropertySourceBuilderTests.java
deleted file mode 100644
index 40248d25..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosPropertySourceBuilderTests.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Copyright (C) 2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.cloud.alibaba.nacos;
-
-import org.junit.Test;
-import org.powermock.api.support.MethodProxy;
-import org.springframework.cloud.alibaba.nacos.client.NacosPropertySource;
-import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceBuilder;
-import org.springframework.util.ReflectionUtils;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * @author pbting
- * @date 2019-01-17 11:49 AM
- */
-public class NacosPropertySourceBuilderTests extends NacosPowerMockitBaseTests {
-
- @Test
- public void nacosPropertySourceBuilder() {
-
- assertThat(nacosPropertySourceBuilderInstance() != null).isEqualTo(true);
- }
-
- @Test
- public void getConfigByProperties() {
- try {
- final HashMap value = new HashMap<>();
- value.put("dev.mode", "local-mock");
-
- final Constructor constructor = ReflectionUtils.accessibleConstructor(
- NacosPropertySource.class, String.class, String.class, Map.class,
- Date.class, boolean.class);
-
- NacosPropertySourceBuilder nacosPropertySourceBuilder = nacosPropertySourceBuilderInstance();
-
- Method method = ReflectionUtils.findMethod(NacosPropertySourceBuilder.class,
- "build", String.class, String.class, String.class, boolean.class);
- ReflectionUtils.makeAccessible(method);
- assertThat(method != null).isEqualTo(true);
- MethodProxy.proxy(method, new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- Object instance = constructor.newInstance(args[1].toString(),
- args[0].toString(), value, new Date(), args[3]);
- return instance;
- }
- });
-
- Object result = method.invoke(nacosPropertySourceBuilder,
- "mock-nacos-config.properties", "DEFAULT_GROUP", "properties", true);
- assertThat(result != null).isEqualTo(true);
- assertThat(result instanceof NacosPropertySource).isEqualTo(true);
- NacosPropertySource nacosPropertySource = (NacosPropertySource) result;
- assertThat(nacosPropertySource.getProperty("dev.mode"))
- .isEqualTo("local-mock");
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Test
- public void getConfigByYaml() {
-
- try {
- //
- final HashMap value = new HashMap<>();
- value.put("mock-ext-config", "mock-ext-config-value");
-
- final Constructor constructor = ReflectionUtils.accessibleConstructor(
- NacosPropertySource.class, String.class, String.class, Map.class,
- Date.class, boolean.class);
-
- Method method = ReflectionUtils.findMethod(NacosPropertySourceBuilder.class,
- "build", String.class, String.class, String.class, boolean.class);
- ReflectionUtils.makeAccessible(method);
- assertThat(method != null).isEqualTo(true);
-
- MethodProxy.proxy(method, new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- Object instance = constructor.newInstance(args[1].toString(),
- args[0].toString(), value, new Date(), args[3]);
- return instance;
- }
- });
-
- NacosPropertySourceBuilder nacosPropertySourceBuilder = nacosPropertySourceBuilderInstance();
- Object result = method.invoke(nacosPropertySourceBuilder, "ext-config.yaml",
- "DEFAULT_GROUP", "yaml", true);
- assertThat(result != null).isEqualTo(true);
- assertThat(result instanceof NacosPropertySource).isEqualTo(true);
- NacosPropertySource nacosPropertySource = (NacosPropertySource) result;
- assertThat(nacosPropertySource.getProperty("mock-ext-config"))
- .isEqualTo("mock-ext-config-value");
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Test
- public void getConfigByYml() {
- try {
- //
- final HashMap value = new HashMap<>();
- value.put("mock-ext-config-yml", "mock-ext-config-yml-value");
-
- final Constructor constructor = ReflectionUtils.accessibleConstructor(
- NacosPropertySource.class, String.class, String.class, Map.class,
- Date.class, boolean.class);
-
- Method method = ReflectionUtils.findMethod(NacosPropertySourceBuilder.class,
- "build", String.class, String.class, String.class, boolean.class);
- ReflectionUtils.makeAccessible(method);
- assertThat(method != null).isEqualTo(true);
-
- MethodProxy.proxy(method, new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- Object instance = constructor.newInstance(args[1].toString(),
- args[0].toString(), value, new Date(), args[3]);
- return instance;
- }
- });
-
- NacosPropertySourceBuilder nacosPropertySourceBuilder = nacosPropertySourceBuilderInstance();
- Object result = method.invoke(nacosPropertySourceBuilder, "ext-config.yml",
- "DEFAULT_GROUP", "yml", true);
- assertThat(result != null).isEqualTo(true);
- assertThat(result instanceof NacosPropertySource).isEqualTo(true);
- NacosPropertySource nacosPropertySource = (NacosPropertySource) result;
- assertThat(nacosPropertySource.getProperty("mock-ext-config-yml"))
- .isEqualTo("mock-ext-config-yml-value");
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Test
- public void getEmpty() {
- NacosPropertySourceBuilder nacosPropertySourceBuilder = nacosPropertySourceBuilderInstance();
-
- Method method = ReflectionUtils.findMethod(NacosPropertySourceBuilder.class,
- "build", String.class, String.class, String.class, boolean.class);
- ReflectionUtils.makeAccessible(method);
- assertThat(method != null).isEqualTo(true);
-
- try {
- Object result = method.invoke(nacosPropertySourceBuilder, "nacos-empty.yml",
- "DEFAULT_GROUP", "yml", true);
- assertThat(result != null).isEqualTo(true);
- assertThat(result instanceof NacosPropertySource).isEqualTo(true);
- NacosPropertySource nacosPropertySource = (NacosPropertySource) result;
- assertThat(nacosPropertySource.getProperty("address")).isEqualTo(null);
- }
- catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- catch (InvocationTargetException e) {
- e.printStackTrace();
- }
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosSharedAndExtConfigTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosSharedAndExtConfigTests.java
deleted file mode 100644
index 90fe3ca4..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosSharedAndExtConfigTests.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.cloud.alibaba.nacos;
-
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.concurrent.TimeUnit;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * @author pbting
- * @date 2019-01-17 11:46 AM
- */
-public class NacosSharedAndExtConfigTests extends NacosPowerMockitBaseTests {
- private final static Logger log = LoggerFactory
- .getLogger(NacosSharedAndExtConfigTests.class);
-
- @Test
- public void testSharedConfigPriority() {
- String userName = this.context.getEnvironment().getProperty("user.address");
- assertThat(userName).isEqualTo("zhejiang-ningbo");
- }
-
- @Test
- public void testSharedConfigRefresh() {
-
- while (true) {
- // ContextRefresher contextRefresher = this.context
- // .getBean(ContextRefresher.class);
- // contextRefresher.refresh();
- String userName = this.context.getEnvironment().getProperty("user.address");
- try {
- assertThat(userName).isEqualTo("zhejiang-ningbo");
- TimeUnit.SECONDS.sleep(1);
- log.info("user name is {}", userName);
- }
- catch (InterruptedException e) {
- e.printStackTrace();
- }
- // 真实测试时将这里 注释掉
- break;
- }
- }
-
- @Test
- public void testExtConfigPriority() {
- String extKey = this.context.getEnvironment().getProperty("ext.key");
- assertThat(extKey).isEqualTo("ext.value02");
- }
-
- @Test
- public void testExtOtherGroup() {
- String userExt = this.context.getEnvironment().getProperty("user.ext");
- assertThat(userExt).isEqualTo("EXT01_GROUP-value");
- }
-
- @Test
- public void testExtRefresh() {
- while (true) {
- // ContextRefresher contextRefresher = this.context
- // .getBean(ContextRefresher.class);
- // contextRefresher.refresh();
- String userExt = this.context.getEnvironment().getProperty("user.ext");
- try {
- assertThat(userExt).isEqualTo("EXT01_GROUP-value");
- TimeUnit.SECONDS.sleep(1);
- log.info("user name is {}", userExt);
- }
- catch (InterruptedException e) {
- e.printStackTrace();
- }
- break;
- }
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosConfigEndpointTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosConfigEndpointTests.java
new file mode 100644
index 00000000..ef823960
--- /dev/null
+++ b/spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosConfigEndpointTests.java
@@ -0,0 +1,141 @@
+/*
+ * 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.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 com.alibaba.nacos.client.config.NacosConfigService;
+
+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.PowerMockIgnore;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.powermock.modules.junit4.PowerMockRunnerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.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.alibaba.nacos.NacosConfigAutoConfiguration;
+import org.springframework.cloud.alibaba.nacos.NacosConfigBootstrapConfiguration;
+import org.springframework.cloud.alibaba.nacos.NacosConfigProperties;
+import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshHistory;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.test.context.junit4.SpringRunner;
+
+/**
+ * @author xiaojing
+ */
+
+@RunWith(PowerMockRunner.class)
+@PowerMockIgnore("javax.management.*")
+@PowerMockRunnerDelegate(SpringRunner.class)
+@PrepareForTest({ NacosConfigService.class })
+@SpringBootTest(classes = NacosConfigEndpointTests.TestConfig.class, properties = {
+ "spring.application.name=test-name",
+ "spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
+ "spring.cloud.nacos.config.file-extension=properties" }, webEnvironment = NONE)
+public class NacosConfigEndpointTests {
+
+ static {
+
+ try {
+
+ Method method = PowerMockito.method(NacosConfigService.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 NacosConfigProperties properties;
+
+ @Autowired
+ private NacosRefreshHistory refreshHistory;
+
+ @Test
+ public void contextLoads() throws Exception {
+
+ checkoutEndpoint();
+ checkoutAcmHealthIndicator();
+
+ }
+
+ private void checkoutAcmHealthIndicator() {
+ try {
+ Builder builder = new Builder();
+
+ NacosConfigHealthIndicator healthIndicator = new NacosConfigHealthIndicator(
+ properties, properties.configServiceInstance());
+ healthIndicator.doHealthCheck(builder);
+
+ Builder builder1 = new Builder();
+ List 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 {
+ NacosConfigEndpoint endpoint = new NacosConfigEndpoint(properties,
+ refreshHistory);
+ Map map = endpoint.invoke();
+ assertEquals(map.get("NacosConfigProperties"), properties);
+ assertEquals(map.get("RefreshHistory"), refreshHistory.getRecords());
+ }
+
+ @Configuration
+ @EnableAutoConfiguration
+ @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
+ NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
+ public static class TestConfig {
+ }
+}
diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/base-common.properties b/spring-cloud-alibaba-nacos-config/src/test/resources/base-common.properties
deleted file mode 100644
index 71137acf..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/resources/base-common.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-user.name=base-common-value
-user.address=zhejiang-hangzhou
\ No newline at end of file
diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/common.properties b/spring-cloud-alibaba-nacos-config/src/test/resources/common.properties
deleted file mode 100644
index d8f61776..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/resources/common.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-user.name=common-value
-user.address=zhejiang-ningbo
\ No newline at end of file
diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/ext00.yaml b/spring-cloud-alibaba-nacos-config/src/test/resources/ext00.yaml
deleted file mode 100644
index 4d70f674..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/resources/ext00.yaml
+++ /dev/null
@@ -1,4 +0,0 @@
-user:
- name: ext-00-value
-ext:
- key: ext.value00
\ No newline at end of file
diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/ext01.yml b/spring-cloud-alibaba-nacos-config/src/test/resources/ext01.yml
deleted file mode 100644
index c689c09e..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/resources/ext01.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-user:
- name: ext-01-value
- ext: EXT01_GROUP-value
-ext:
- key: ext.value01
diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/ext02.yaml b/spring-cloud-alibaba-nacos-config/src/test/resources/ext02.yaml
deleted file mode 100644
index 9cc47740..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/resources/ext02.yaml
+++ /dev/null
@@ -1,5 +0,0 @@
-user:
- name: ext-02-value
-ext:
- key: ext.value02
-app-local-common: update app local shared cguration for Nacos
\ No newline at end of file
diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/sca-nacos-config-develop.properties b/spring-cloud-alibaba-nacos-config/src/test/resources/sca-nacos-config-develop.properties
deleted file mode 100644
index 21a6ef58..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/resources/sca-nacos-config-develop.properties
+++ /dev/null
@@ -1 +0,0 @@
-user.name=sca-nacos-config-value-develop
\ No newline at end of file
diff --git a/spring-cloud-alibaba-nacos-config/src/test/resources/sca-nacos-config.properties b/spring-cloud-alibaba-nacos-config/src/test/resources/sca-nacos-config.properties
deleted file mode 100644
index db268f2c..00000000
--- a/spring-cloud-alibaba-nacos-config/src/test/resources/sca-nacos-config.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-user.name=sca-nacos-config-value
-dev.mode=local
\ No newline at end of file
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java
index 3bde6e42..97e04060 100644
--- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java
+++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java
@@ -28,6 +28,7 @@ import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAut
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;
@@ -43,7 +44,8 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnNacosDiscoveryEnabled
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
@AutoConfigureBefore(NacosDiscoveryClientAutoConfiguration.class)
-@AutoConfigureAfter(AutoServiceRegistrationConfiguration.class)
+@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class,
+ AutoServiceRegistrationAutoConfiguration.class })
public class NacosDiscoveryAutoConfiguration {
@Bean
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java
index a86b24d6..4805460f 100644
--- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java
+++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java
@@ -57,7 +57,7 @@ import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR;
@ConfigurationProperties("spring.cloud.nacos.discovery")
public class NacosDiscoveryProperties {
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger log = LoggerFactory
.getLogger(NacosDiscoveryProperties.class);
/**
@@ -413,7 +413,7 @@ public class NacosDiscoveryProperties {
namingService = NacosFactory.createNamingService(properties);
}
catch (Exception e) {
- LOGGER.error("create naming service error!properties={},e=,", this, e);
+ log.error("create naming service error!properties={},e=,", this, e);
return null;
}
return namingService;
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClient.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClient.java
index a820144e..ccf2e838 100644
--- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClient.java
+++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClient.java
@@ -18,6 +18,7 @@ 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.cloud.alibaba.nacos.NacosDiscoveryProperties;
@@ -25,7 +26,11 @@ import org.springframework.cloud.alibaba.nacos.NacosServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
/**
* @author xiaojing
@@ -33,75 +38,74 @@ import java.util.*;
*/
public class NacosDiscoveryClient implements DiscoveryClient {
- private static final Logger LOGGER = LoggerFactory
- .getLogger(NacosDiscoveryClient.class);
- public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client";
+ private static final Logger log = LoggerFactory
+ .getLogger(NacosDiscoveryClient.class);
+ public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client";
- private NacosDiscoveryProperties discoveryProperties;
+ private NacosDiscoveryProperties discoveryProperties;
- public NacosDiscoveryClient(NacosDiscoveryProperties discoveryProperties) {
- this.discoveryProperties = discoveryProperties;
- }
+ public NacosDiscoveryClient(NacosDiscoveryProperties discoveryProperties) {
+ this.discoveryProperties = discoveryProperties;
+ }
- @Override
- public String description() {
- return DESCRIPTION;
- }
+ @Override
+ public String description() {
+ return DESCRIPTION;
+ }
- @Override
- public List getInstances(String serviceId) {
- try {
- List instances = discoveryProperties.namingServiceInstance()
- .selectInstances(serviceId, true);
- return hostToServiceInstanceList(instances, serviceId);
- }
- catch (Exception e) {
- throw new RuntimeException(
- "Can not get hosts from nacos server. serviceId: " + serviceId, e);
- }
- }
+ @Override
+ public List getInstances(String serviceId) {
+ try {
+ List instances = discoveryProperties.namingServiceInstance()
+ .selectInstances(serviceId, true);
+ return hostToServiceInstanceList(instances, serviceId);
+ } catch (Exception e) {
+ throw new RuntimeException(
+ "Can not get hosts from nacos server. serviceId: " + serviceId, e);
+ }
+ }
- private static ServiceInstance hostToServiceInstance(Instance instance,
- String serviceId) {
- NacosServiceInstance nacosServiceInstance = new NacosServiceInstance();
- nacosServiceInstance.setHost(instance.getIp());
- nacosServiceInstance.setPort(instance.getPort());
- nacosServiceInstance.setServiceId(serviceId);
- Map 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);
+ private static ServiceInstance hostToServiceInstance(Instance instance,
+ String serviceId) {
+ NacosServiceInstance nacosServiceInstance = new NacosServiceInstance();
+ nacosServiceInstance.setHost(instance.getIp());
+ nacosServiceInstance.setPort(instance.getPort());
+ nacosServiceInstance.setServiceId(serviceId);
- if (metadata.containsKey("secure")) {
- boolean secure = Boolean.parseBoolean(metadata.get("secure"));
- nacosServiceInstance.setSecure(secure);
- }
- return nacosServiceInstance;
- }
+ Map metadata = new HashMap<>();
+ metadata.put("nacos.instanceId", instance.getInstanceId());
+ metadata.put("nacos.weight", instance.getWeight() + "");
+ metadata.put("nacos.healthy", instance.isHealthy() + "");
+ metadata.put("nacos.cluster", instance.getClusterName() + "");
+ metadata.putAll(instance.getMetadata());
+ nacosServiceInstance.setMetadata(metadata);
- private static List hostToServiceInstanceList(
- List instances, String serviceId) {
- List result = new ArrayList<>(instances.size());
- for (Instance instance : instances) {
- result.add(hostToServiceInstance(instance, serviceId));
- }
- return result;
- }
+ if (metadata.containsKey("secure")) {
+ boolean secure = Boolean.parseBoolean(metadata.get("secure"));
+ nacosServiceInstance.setSecure(secure);
+ }
+ return nacosServiceInstance;
+ }
- @Override
- public List getServices() {
+ private static List hostToServiceInstanceList(
+ List instances, String serviceId) {
+ List result = new ArrayList<>(instances.size());
+ for (Instance instance : instances) {
+ result.add(hostToServiceInstance(instance, serviceId));
+ }
+ return result;
+ }
- try {
- ListView services = discoveryProperties.namingServiceInstance()
- .getServicesOfServer(1, Integer.MAX_VALUE);
- return services.getData();
- }
- catch (Exception e) {
- LOGGER.error("get service name from nacos server fail,", e);
- return Collections.emptyList();
- }
- }
+ @Override
+ public List getServices() {
+
+ try {
+ ListView services = discoveryProperties.namingServiceInstance()
+ .getServicesOfServer(1, Integer.MAX_VALUE);
+ return services.getData();
+ } catch (Exception e) {
+ log.error("get service name from nacos server fail,", e);
+ return Collections.emptyList();
+ }
+ }
}
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java
index 5fe818b3..29858fb7 100644
--- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java
+++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java
@@ -18,6 +18,7 @@ package org.springframework.cloud.alibaba.nacos.discovery;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.alibaba.nacos.ConditionalOnNacosDiscoveryEnabled;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
@@ -33,6 +34,7 @@ import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnNacosDiscoveryEnabled
@EnableConfigurationProperties
+@ConditionalOnProperty(value = "spring.cloud.nacos.discovery.enabled", matchIfMissing = true)
@AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class,
CommonsClientAutoConfiguration.class })
public class NacosDiscoveryClientAutoConfiguration {
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java
index 43bec39a..6ceec414 100644
--- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java
+++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java
@@ -37,7 +37,7 @@ import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
@Endpoint(id = "nacos-discovery")
public class NacosDiscoveryEndpoint {
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger log = LoggerFactory
.getLogger(NacosDiscoveryEndpoint.class);
private NacosDiscoveryProperties nacosDiscoveryProperties;
@@ -61,7 +61,7 @@ public class NacosDiscoveryEndpoint {
subscribe = namingService.getSubscribeServices();
}
catch (Exception e) {
- LOGGER.error("get subscribe services from nacos fail,", e);
+ log.error("get subscribe services from nacos fail,", e);
}
result.put("subscribe", subscribe);
return result;
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistration.java
index 4f7094f0..54c22a19 100644
--- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistration.java
+++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosAutoServiceRegistration.java
@@ -31,7 +31,7 @@ import org.springframework.util.StringUtils;
*/
public class NacosAutoServiceRegistration
extends AbstractAutoServiceRegistration {
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger log = LoggerFactory
.getLogger(NacosAutoServiceRegistration.class);
private NacosRegistration registration;
@@ -65,7 +65,7 @@ public class NacosAutoServiceRegistration
@Override
protected void register() {
if (!this.registration.getNacosDiscoveryProperties().isRegisterEnabled()) {
- LOGGER.debug("Registration disabled.");
+ log.debug("Registration disabled.");
return;
}
if (this.registration.getPort() < 0) {
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosServiceRegistry.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosServiceRegistry.java
index 8633c302..5e9d423f 100644
--- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosServiceRegistry.java
+++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosServiceRegistry.java
@@ -32,7 +32,7 @@ import org.springframework.util.StringUtils;
*/
public class NacosServiceRegistry implements ServiceRegistry {
- private static Logger logger = LoggerFactory.getLogger(NacosServiceRegistry.class);
+ private static final Logger log = LoggerFactory.getLogger(NacosServiceRegistry.class);
private final NacosDiscoveryProperties nacosDiscoveryProperties;
@@ -47,7 +47,7 @@ public class NacosServiceRegistry implements ServiceRegistry {
public void register(Registration registration) {
if (StringUtils.isEmpty(registration.getServiceId())) {
- logger.info("No service to register for nacos client...");
+ log.warn("No service to register for nacos client...");
return;
}
@@ -62,11 +62,11 @@ public class NacosServiceRegistry implements ServiceRegistry {
try {
namingService.registerInstance(serviceId, instance);
- logger.info("nacos registry, {} {}:{} register finished", serviceId,
+ log.info("nacos registry, {} {}:{} register finished", serviceId,
instance.getIp(), instance.getPort());
}
catch (Exception e) {
- logger.error("nacos registry, {} register failed...{},", serviceId,
+ log.error("nacos registry, {} register failed...{},", serviceId,
registration.toString(), e);
}
}
@@ -74,10 +74,10 @@ public class NacosServiceRegistry implements ServiceRegistry {
@Override
public void deregister(Registration registration) {
- logger.info("De-registering from Nacos Server now...");
+ log.info("De-registering from Nacos Server now...");
if (StringUtils.isEmpty(registration.getServiceId())) {
- logger.info("No dom to de-register for nacos client...");
+ log.warn("No dom to de-register for nacos client...");
return;
}
@@ -89,11 +89,11 @@ public class NacosServiceRegistry implements ServiceRegistry {
registration.getPort(), nacosDiscoveryProperties.getClusterName());
}
catch (Exception e) {
- logger.error("ERR_NACOS_DEREGISTER, de-register failed...{},",
+ log.error("ERR_NACOS_DEREGISTER, de-register failed...{},",
registration.toString(), e);
}
- logger.info("De-registration finished.");
+ log.info("De-registration finished.");
}
@Override
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json
index d0e82a51..75e8abd4 100644
--- a/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json
+++ b/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json
@@ -5,6 +5,12 @@
"defaultValue": "${spring.application.name}",
"description": "the service name to register, default value is ${spring.application.name}."
},
+ {
+ "name": "spring.cloud.nacos.discovery.enabled",
+ "type": "java.lang.Boolean",
+ "defaultValue": true,
+ "description": "enable nacos discovery or not."
+ },
{
"name": "spring.cloud.nacos.discovery.namingLoadCacheAtStart",
"type": "java.lang.Boolean",
diff --git a/spring-cloud-alibaba-sentinel-zuul/src/main/java/org/springframework/cloud/alibaba/sentinel/zuul/SentinelZuulAutoConfiguration.java b/spring-cloud-alibaba-sentinel-zuul/src/main/java/org/springframework/cloud/alibaba/sentinel/zuul/SentinelZuulAutoConfiguration.java
index 73d4cf79..35577cae 100644
--- a/spring-cloud-alibaba-sentinel-zuul/src/main/java/org/springframework/cloud/alibaba/sentinel/zuul/SentinelZuulAutoConfiguration.java
+++ b/spring-cloud-alibaba-sentinel-zuul/src/main/java/org/springframework/cloud/alibaba/sentinel/zuul/SentinelZuulAutoConfiguration.java
@@ -16,6 +16,17 @@
package org.springframework.cloud.alibaba.sentinel.zuul;
+import static org.springframework.cloud.alibaba.sentinel.zuul.SentinelZuulAutoConfiguration.PREFIX;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.support.DefaultListableBeanFactory;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.cloud.alibaba.sentinel.zuul.handler.FallBackProviderHandler;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.env.Environment;
+
import com.alibaba.csp.sentinel.adapter.zuul.fallback.DefaultRequestOriginParser;
import com.alibaba.csp.sentinel.adapter.zuul.fallback.DefaultUrlCleaner;
import com.alibaba.csp.sentinel.adapter.zuul.fallback.RequestOriginParser;
@@ -25,17 +36,8 @@ import com.alibaba.csp.sentinel.adapter.zuul.filters.SentinelPostFilter;
import com.alibaba.csp.sentinel.adapter.zuul.filters.SentinelPreFilter;
import com.alibaba.csp.sentinel.adapter.zuul.properties.SentinelZuulProperties;
import com.alibaba.csp.sentinel.util.StringUtil;
-import com.netflix.zuul.ZuulFilter;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.support.DefaultListableBeanFactory;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
-import org.springframework.cloud.alibaba.sentinel.zuul.listener.FallBackProviderListener;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.core.env.Environment;
-import static org.springframework.cloud.alibaba.sentinel.zuul.SentinelZuulAutoConfiguration.PREFIX;
+import com.netflix.zuul.ZuulFilter;
/**
* Sentinel Spring Cloud Zuul AutoConfiguration
@@ -43,68 +45,70 @@ import static org.springframework.cloud.alibaba.sentinel.zuul.SentinelZuulAutoCo
* @author tiger
*/
@Configuration
-@ConditionalOnProperty(prefix = PREFIX, name = "enabled", havingValue = "true")
+@ConditionalOnProperty(prefix = PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class SentinelZuulAutoConfiguration {
- @Autowired
- private Environment environment;
+ @Autowired
+ private Environment environment;
- public static final String PREFIX = "spring.cloud.alibaba.sentinel.zuul";
+ public static final String PREFIX = "spring.cloud.sentinel.zuul";
- @Bean
- public SentinelZuulProperties sentinelZuulProperties() {
- SentinelZuulProperties properties = new SentinelZuulProperties();
- String enabledStr = environment.getProperty(PREFIX + "." + "enabled");
- String preOrderStr = environment.getProperty(PREFIX + "." + "order.pre");
- String postOrderStr = environment.getProperty(PREFIX + "." + "order.post");
- String errorOrderStr = environment.getProperty(PREFIX + "." + "order.error");
- if (StringUtil.isNotEmpty(enabledStr)) {
- Boolean enabled = Boolean.valueOf(enabledStr);
- properties.setEnabled(enabled);
- }
- if (StringUtil.isNotEmpty(preOrderStr)) {
- properties.getOrder().setPre(Integer.parseInt(preOrderStr));
- }
- if (StringUtil.isNotEmpty(postOrderStr)) {
- properties.getOrder().setPost(Integer.parseInt(postOrderStr));
- }
- if (StringUtil.isNotEmpty(errorOrderStr)) {
- properties.getOrder().setError(Integer.parseInt(errorOrderStr));
- }
- return properties;
- }
+ @Bean
+ public SentinelZuulProperties sentinelZuulProperties() {
+ SentinelZuulProperties properties = new SentinelZuulProperties();
+ String enabledStr = environment.getProperty(PREFIX + "." + "enabled");
+ String preOrderStr = environment.getProperty(PREFIX + "." + "order.pre");
+ String postOrderStr = environment.getProperty(PREFIX + "." + "order.post");
+ String errorOrderStr = environment.getProperty(PREFIX + "." + "order.error");
+ if (StringUtil.isNotEmpty(enabledStr)) {
+ Boolean enabled = Boolean.valueOf(enabledStr);
+ properties.setEnabled(enabled);
+ }
+ if (StringUtil.isNotEmpty(preOrderStr)) {
+ properties.getOrder().setPre(Integer.parseInt(preOrderStr));
+ }
+ if (StringUtil.isNotEmpty(postOrderStr)) {
+ properties.getOrder().setPost(Integer.parseInt(postOrderStr));
+ }
+ if (StringUtil.isNotEmpty(errorOrderStr)) {
+ properties.getOrder().setError(Integer.parseInt(errorOrderStr));
+ }
+ return properties;
+ }
- @Bean
- @ConditionalOnMissingBean(UrlCleaner.class)
- public UrlCleaner urlCleaner(){
- return new DefaultUrlCleaner();
- }
+ @Bean
+ @ConditionalOnMissingBean(UrlCleaner.class)
+ public UrlCleaner urlCleaner() {
+ return new DefaultUrlCleaner();
+ }
- @Bean
- @ConditionalOnMissingBean(RequestOriginParser.class)
- public RequestOriginParser requestOriginParser(){
- return new DefaultRequestOriginParser();
- }
+ @Bean
+ @ConditionalOnMissingBean(RequestOriginParser.class)
+ public RequestOriginParser requestOriginParser() {
+ return new DefaultRequestOriginParser();
+ }
- @Bean
- public ZuulFilter preFilter(SentinelZuulProperties sentinelZuulProperties,UrlCleaner urlCleaner,
- RequestOriginParser requestOriginParser) {
- return new SentinelPreFilter(sentinelZuulProperties,urlCleaner,requestOriginParser);
- }
+ @Bean
+ public ZuulFilter preFilter(SentinelZuulProperties sentinelZuulProperties,
+ UrlCleaner urlCleaner, RequestOriginParser requestOriginParser) {
+ return new SentinelPreFilter(sentinelZuulProperties, urlCleaner,
+ requestOriginParser);
+ }
- @Bean
- public ZuulFilter postFilter(SentinelZuulProperties sentinelZuulProperties) {
- return new SentinelPostFilter(sentinelZuulProperties);
- }
+ @Bean
+ public ZuulFilter postFilter(SentinelZuulProperties sentinelZuulProperties) {
+ return new SentinelPostFilter(sentinelZuulProperties);
+ }
- @Bean
- public ZuulFilter errorFilter(SentinelZuulProperties sentinelZuulProperties) {
- return new SentinelErrorFilter(sentinelZuulProperties);
- }
+ @Bean
+ public ZuulFilter errorFilter(SentinelZuulProperties sentinelZuulProperties) {
+ return new SentinelErrorFilter(sentinelZuulProperties);
+ }
- @Bean
- public FallBackProviderListener fallBackProviderListener(DefaultListableBeanFactory beanFactory) {
- return new FallBackProviderListener(beanFactory);
- }
+ @Bean
+ public FallBackProviderHandler fallBackProviderListener(
+ DefaultListableBeanFactory beanFactory) {
+ return new FallBackProviderHandler(beanFactory);
+ }
}
diff --git a/spring-cloud-alibaba-sentinel-zuul/src/main/java/org/springframework/cloud/alibaba/sentinel/zuul/handler/FallBackProviderHandler.java b/spring-cloud-alibaba-sentinel-zuul/src/main/java/org/springframework/cloud/alibaba/sentinel/zuul/handler/FallBackProviderHandler.java
new file mode 100644
index 00000000..564fc446
--- /dev/null
+++ b/spring-cloud-alibaba-sentinel-zuul/src/main/java/org/springframework/cloud/alibaba/sentinel/zuul/handler/FallBackProviderHandler.java
@@ -0,0 +1,45 @@
+package org.springframework.cloud.alibaba.sentinel.zuul.handler;
+
+import java.util.Map;
+
+import org.apache.commons.collections.MapUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.SmartInitializingSingleton;
+import org.springframework.beans.factory.support.DefaultListableBeanFactory;
+
+import com.alibaba.csp.sentinel.adapter.zuul.fallback.DefaultBlockFallbackProvider;
+import com.alibaba.csp.sentinel.adapter.zuul.fallback.ZuulBlockFallbackManager;
+import com.alibaba.csp.sentinel.adapter.zuul.fallback.ZuulBlockFallbackProvider;
+
+/**
+ * @author tiger
+ */
+public class FallBackProviderHandler implements SmartInitializingSingleton {
+
+ private static final Logger logger = LoggerFactory
+ .getLogger(FallBackProviderHandler.class);
+
+ private final DefaultListableBeanFactory beanFactory;
+
+ public FallBackProviderHandler(DefaultListableBeanFactory beanFactory) {
+ this.beanFactory = beanFactory;
+ }
+
+ @Override
+ public void afterSingletonsInstantiated() {
+ Map providerMap = beanFactory
+ .getBeansOfType(ZuulBlockFallbackProvider.class);
+ if (MapUtils.isNotEmpty(providerMap)) {
+ providerMap.forEach((k, v) -> {
+ logger.info("[Sentinel Zuul] Register provider name:{}, instance: {}", k,
+ v);
+ ZuulBlockFallbackManager.registerProvider(v);
+ });
+ }
+ else {
+ logger.info("[Sentinel Zuul] Register default fallback provider. ");
+ ZuulBlockFallbackManager.registerProvider(new DefaultBlockFallbackProvider());
+ }
+ }
+}
diff --git a/spring-cloud-alibaba-sentinel-zuul/src/main/java/org/springframework/cloud/alibaba/sentinel/zuul/listener/FallBackProviderListener.java b/spring-cloud-alibaba-sentinel-zuul/src/main/java/org/springframework/cloud/alibaba/sentinel/zuul/listener/FallBackProviderListener.java
deleted file mode 100644
index d727a0e4..00000000
--- a/spring-cloud-alibaba-sentinel-zuul/src/main/java/org/springframework/cloud/alibaba/sentinel/zuul/listener/FallBackProviderListener.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package org.springframework.cloud.alibaba.sentinel.zuul.listener;
-
-import com.alibaba.csp.sentinel.adapter.zuul.fallback.DefaultBlockFallbackProvider;
-import com.alibaba.csp.sentinel.adapter.zuul.fallback.ZuulBlockFallbackManager;
-import com.alibaba.csp.sentinel.adapter.zuul.fallback.ZuulBlockFallbackProvider;
-import org.apache.commons.collections.MapUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.SmartInitializingSingleton;
-import org.springframework.beans.factory.support.DefaultListableBeanFactory;
-import org.springframework.boot.context.event.ApplicationStartedEvent;
-import org.springframework.context.event.EventListener;
-
-import java.util.Map;
-
-
-/**
- * @author tiger
- */
-public class FallBackProviderListener implements SmartInitializingSingleton {
-
- private static final Logger logger = LoggerFactory.getLogger(FallBackProviderListener.class);
-
- private final DefaultListableBeanFactory beanFactory;
-
- public FallBackProviderListener(DefaultListableBeanFactory beanFactory) {
- this.beanFactory = beanFactory;
- }
-
- @Override
- public void afterSingletonsInstantiated() {
- Map providerMap = beanFactory.getBeansOfType(ZuulBlockFallbackProvider.class);
- if (MapUtils.isNotEmpty(providerMap)) {
- providerMap.forEach((k, v) -> {
- logger.info("[Sentinel] Register provider name:{}, instance: {}", k, v);
- ZuulBlockFallbackManager.registerProvider(v);
- });
- } else {
- logger.info("[Sentinel] Register default fallback provider. ");
- ZuulBlockFallbackManager.registerProvider(new DefaultBlockFallbackProvider());
- }
- }
-}
diff --git a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelProperties.java b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelProperties.java
index d4621bd7..68cedb64 100644
--- a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelProperties.java
+++ b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelProperties.java
@@ -16,17 +16,18 @@
package org.springframework.cloud.alibaba.sentinel;
-import com.alibaba.csp.sentinel.config.SentinelConfig;
-import com.alibaba.csp.sentinel.log.LogBase;
-import com.alibaba.csp.sentinel.transport.config.TransportConfig;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.alibaba.sentinel.datasource.config.DataSourcePropertiesConfiguration;
import org.springframework.core.Ordered;
import org.springframework.validation.annotation.Validated;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
+import com.alibaba.csp.sentinel.config.SentinelConfig;
+import com.alibaba.csp.sentinel.log.LogBase;
+import com.alibaba.csp.sentinel.transport.config.TransportConfig;
/**
* {@link ConfigurationProperties} for Sentinel.
@@ -306,6 +307,12 @@ public class SentinelProperties {
*/
private List urlPatterns;
+ /**
+ * Enable to instance
+ * {@link com.alibaba.csp.sentinel.adapter.servlet.CommonFilter}.
+ */
+ private boolean enabled = true;
+
public int getOrder() {
return this.order;
}
@@ -321,6 +328,14 @@ public class SentinelProperties {
public void setUrlPatterns(List urlPatterns) {
this.urlPatterns = urlPatterns;
}
+
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(boolean enabled) {
+ this.enabled = enabled;
+ }
}
public static class Log {
diff --git a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelWebAutoConfiguration.java b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelWebAutoConfiguration.java
index 1eea41e9..5a73f2cb 100644
--- a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelWebAutoConfiguration.java
+++ b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/SentinelWebAutoConfiguration.java
@@ -16,7 +16,10 @@
package org.springframework.cloud.alibaba.sentinel;
-import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.Filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -28,9 +31,7 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import javax.servlet.Filter;
-import java.util.ArrayList;
-import java.util.List;
+import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
/**
* @author xiaojing
@@ -48,7 +49,8 @@ public class SentinelWebAutoConfiguration {
private SentinelProperties properties;
@Bean
- public FilterRegistrationBean servletRequestListener() {
+ @ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true)
+ public FilterRegistrationBean sentinelFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean<>();
SentinelProperties.Filter filterConfig = properties.getFilter();
diff --git a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/endpoint/SentinelEndpoint.java b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/endpoint/SentinelEndpoint.java
index f42898bc..9562fdc0 100644
--- a/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/endpoint/SentinelEndpoint.java
+++ b/spring-cloud-alibaba-sentinel/src/main/java/org/springframework/cloud/alibaba/sentinel/endpoint/SentinelEndpoint.java
@@ -16,6 +16,13 @@
package org.springframework.cloud.alibaba.sentinel.endpoint;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
+import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
+import org.springframework.cloud.alibaba.sentinel.SentinelProperties;
+
import com.alibaba.csp.sentinel.adapter.servlet.config.WebServletConfig;
import com.alibaba.csp.sentinel.config.SentinelConfig;
import com.alibaba.csp.sentinel.log.LogBase;
@@ -25,12 +32,7 @@ import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
-import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
-import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
-import org.springframework.cloud.alibaba.sentinel.SentinelProperties;
-
-import java.util.HashMap;
-import java.util.Map;
+import com.alibaba.csp.sentinel.util.AppNameUtil;
/**
* Endpoint for Sentinel, contains ans properties and rules
@@ -50,6 +52,7 @@ public class SentinelEndpoint {
final Map result = new HashMap<>();
if (sentinelProperties.isEnabled()) {
+ result.put("appName", AppNameUtil.getAppName());
result.put("logDir", LogBase.getLogBaseDir());
result.put("logUsePid", LogBase.isLogNameUsePid());
result.put("blockPage", WebServletConfig.getBlockPage());
diff --git a/spring-cloud-alibaba-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-alibaba-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json
index b445fc6a..80fec1a5 100644
--- a/spring-cloud-alibaba-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json
+++ b/spring-cloud-alibaba-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json
@@ -39,6 +39,12 @@
"defaultValue": "Integer.MIN_VALUE",
"description": "sentinel filter chain order, will be set to FilterRegistrationBean."
},
+ {
+ "name": "spring.cloud.sentinel.filter.enabled",
+ "type": "java.lang.Boolean",
+ "defaultValue": true,
+ "description": "Enable to instance com.alibaba.csp.sentinel.adapter.servlet.CommonFilter."
+ },
{
"name": "spring.cloud.sentinel.metric.charset",
"type": "java.lang.String",
diff --git a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySourceLocator.java b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySourceLocator.java
index cb5ebdfb..62ded421 100644
--- a/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySourceLocator.java
+++ b/spring-cloud-alicloud-acm/src/main/java/org/springframework/cloud/alicloud/acm/bootstrap/AcmPropertySourceLocator.java
@@ -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);
diff --git a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmConfigurationTests.java b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmConfigurationTests.java
index ea6a4bdb..9d09fd7a 100644
--- a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmConfigurationTests.java
+++ b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmConfigurationTests.java
@@ -126,6 +126,7 @@ public class AcmConfigurationTests {
checkoutAcmProfiles();
checkoutAcmRefreshEnabled();
checkoutDataLoad();
+ checkoutProfileDataLoad();
}
private void checkoutAcmServerAddr() {
@@ -178,10 +179,13 @@ public class AcmConfigurationTests {
}
private void checkoutDataLoad() {
- Assert.assertEquals(environment.getProperty("user.name"), "dev");
Assert.assertEquals(environment.getProperty("user.age"), "12");
}
+ private void checkoutProfileDataLoad() {
+ Assert.assertEquals(environment.getProperty("user.name"), "dev");
+ }
+
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class,
diff --git a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmFileExtensionTest.java b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmFileExtensionTest.java
new file mode 100644
index 00000000..b463cf8f
--- /dev/null
+++ b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmFileExtensionTest.java
@@ -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 {
+ }
+}
diff --git a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmGroupConfigurationTest.java b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmGroupConfigurationTest.java
index 2e8076ab..030b26d0 100644
--- a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmGroupConfigurationTest.java
+++ b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/AcmGroupConfigurationTest.java
@@ -67,11 +67,11 @@ public class AcmGroupConfigurationTest {
throws Throwable {
if ("com.test:application.properties".equals(args[0])
&& "test-group".equals(args[1])) {
- return "com.test.value=com.test";
+ 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";
+ return "com.test.hello.value=com.test.hello\ntest.priority=2";
}
return "";
}
@@ -91,6 +91,7 @@ public class AcmGroupConfigurationTest {
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");
diff --git a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/endpoint/AcmEndpointTests.java b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/endpoint/AcmEndpointTests.java
index dcef7f48..d05ddb5f 100644
--- a/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/endpoint/AcmEndpointTests.java
+++ b/spring-cloud-alicloud-acm/src/test/java/org/springframework/cloud/alicloud/acm/endpoint/AcmEndpointTests.java
@@ -35,19 +35,15 @@ 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.actuate.health.HealthIndicator;
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.bootstrap.AcmPropertySourceLocator;
import org.springframework.cloud.alicloud.acm.refresh.AcmRefreshHistory;
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;
import com.alibaba.edas.acm.ConfigService;
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java
index fb96cfc1..a2958484 100644
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java
+++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java
@@ -21,16 +21,15 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionMissingClass;
import org.springframework.cloud.alicloud.ans.registry.AnsAutoServiceRegistration;
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;
-import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
/**
@@ -38,11 +37,11 @@ import org.springframework.context.annotation.Configuration;
*/
@Configuration
@EnableConfigurationProperties
-@Conditional(MigrateOnConditionMissingClass.class)
@ConditionalOnClass(name = "org.springframework.boot.web.context.WebServerInitializedEvent")
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
@ConditionalOnAnsEnabled
-@AutoConfigureAfter(AutoServiceRegistrationConfiguration.class)
+@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class,
+ AutoServiceRegistrationAutoConfiguration.class })
public class AnsAutoConfiguration {
@Bean
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClient.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClient.java
index 6f93a979..493dfdcd 100644
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClient.java
+++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClient.java
@@ -22,12 +22,7 @@ import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
/**
* @author xiaolongzuo
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientAutoConfiguration.java
index 06508b07..e035b2a3 100644
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientAutoConfiguration.java
+++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientAutoConfiguration.java
@@ -19,11 +19,9 @@ package org.springframework.cloud.alicloud.ans;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionMissingClass;
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.Conditional;
import org.springframework.context.annotation.Configuration;
/**
@@ -31,7 +29,6 @@ import org.springframework.context.annotation.Configuration;
* @author pbting
*/
@Configuration
-@Conditional(MigrateOnConditionMissingClass.class)
@ConditionalOnMissingBean(DiscoveryClient.class)
@EnableConfigurationProperties
@AutoConfigureBefore(SimpleDiscoveryClientAutoConfiguration.class)
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/endpoint/AnsEndpoint.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/endpoint/AnsEndpoint.java
index baefdb56..7688074e 100644
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/endpoint/AnsEndpoint.java
+++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/endpoint/AnsEndpoint.java
@@ -19,8 +19,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.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
@@ -37,7 +37,7 @@ import java.util.Set;
@Endpoint(id = "ans")
public class AnsEndpoint {
- private static final Log log = LogFactory.getLog(AnsEndpoint.class);
+ private static final Logger log = LoggerFactory.getLogger(AnsEndpoint.class);
private AnsProperties ansProperties;
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpoint.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpoint.java
deleted file mode 100644
index 59b2146a..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpoint.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package org.springframework.cloud.alicloud.ans.migrate;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
-import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentMap;
-
-@Endpoint(id = "migrate")
-public class MigrateEndpoint {
-
- private static final Logger log = LoggerFactory.getLogger(MigrateEndpoint.class);
-
- public MigrateEndpoint() {
- }
-
- /**
- * @return ans endpoint
- */
- @ReadOperation
- public Map> invoke() {
-
- Map> result = ServerListInvocationHandler
- .getServerRegistry();
-
- log.info("migrate server list :" + result);
- return result;
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpointAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpointAutoConfiguration.java
deleted file mode 100644
index af572837..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpointAutoConfiguration.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.springframework.cloud.alicloud.ans.migrate;
-
-import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Conditional;
-
-/**
- * @author pbting
- */
-@ConditionalOnWebApplication
-@ConditionalOnClass(value = Endpoint.class)
-@Conditional(MigrateOnConditionClass.class)
-public class MigrateEndpointAutoConfiguration {
-
- @Bean
- public MigrateEndpoint ansEndpoint() {
- return new MigrateEndpoint();
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnCondition.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnCondition.java
deleted file mode 100644
index 86816587..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnCondition.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package org.springframework.cloud.alicloud.ans.migrate;
-
-import org.springframework.beans.factory.BeanClassLoaderAware;
-import org.springframework.context.annotation.Condition;
-import org.springframework.context.annotation.ConditionContext;
-import org.springframework.core.type.AnnotatedTypeMetadata;
-import org.springframework.util.ClassUtils;
-
-/**
- * @author pbting
- */
-public abstract class MigrateOnCondition implements Condition, BeanClassLoaderAware {
-
- final String[] conditionOnClass = new String[] {
- "org.springframework.cloud.consul.serviceregistry.ConsulAutoServiceRegistration",
- "org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration" };
-
- ClassLoader classLoader;
-
- @Override
- public void setBeanClassLoader(ClassLoader classLoader) {
- this.classLoader = classLoader;
- }
-
- @Override
- public abstract boolean matches(ConditionContext context,
- AnnotatedTypeMetadata metadata);
-
- boolean isPresent(String className, ClassLoader classLoader) {
- if (classLoader == null) {
- classLoader = ClassUtils.getDefaultClassLoader();
- }
-
- try {
- forName(className, classLoader);
- return true;
- }
- catch (Throwable throwable) {
- return false;
- }
- }
-
- Class> forName(String className, ClassLoader classLoader)
- throws ClassNotFoundException {
- return classLoader != null ? classLoader.loadClass(className)
- : Class.forName(className);
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionClass.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionClass.java
deleted file mode 100644
index 9e99c9f8..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionClass.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package org.springframework.cloud.alicloud.ans.migrate;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.annotation.ConditionContext;
-import org.springframework.core.type.AnnotatedTypeMetadata;
-
-/**
- * @author pbting
- */
-public class MigrateOnConditionClass extends MigrateOnCondition {
-
- private static final Logger log = LoggerFactory
- .getLogger(MigrateOnConditionClass.class);
-
- @Override
- public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
- boolean result = isPresent(conditionOnClass[0], classLoader)
- || isPresent(conditionOnClass[1], classLoader);
- log.info("the result of matcher is " + result);
- return result;
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionMissingClass.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionMissingClass.java
deleted file mode 100644
index b5653bb7..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionMissingClass.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package org.springframework.cloud.alicloud.ans.migrate;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.annotation.ConditionContext;
-import org.springframework.core.type.AnnotatedTypeMetadata;
-
-/**
- * @author pbting
- */
-public class MigrateOnConditionMissingClass extends MigrateOnConditionClass {
- private static final Logger log = LoggerFactory
- .getLogger(MigrateOnConditionMissingClass.class);
-
- @Override
- public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
- boolean result = !super.matches(context, metadata);
- log.info(" the result of matcher is " + result);
- return result;
- }
-
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateProxyManager.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateProxyManager.java
deleted file mode 100644
index f44f1af9..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateProxyManager.java
+++ /dev/null
@@ -1,97 +0,0 @@
-package org.springframework.cloud.alicloud.ans.migrate;
-
-import com.netflix.client.config.IClientConfig;
-import com.netflix.loadbalancer.ILoadBalancer;
-import com.netflix.loadbalancer.Server;
-import com.netflix.loadbalancer.ServerList;
-import org.aopalliance.aop.Advice;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.aop.AfterReturningAdvice;
-import org.springframework.aop.framework.ProxyFactory;
-
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.ConcurrentSkipListSet;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * @author pbting
- */
-final class MigrateProxyManager {
-
- private static final Logger log = LoggerFactory.getLogger(MigrateProxyManager.class);
- private final static AtomicBoolean IS_PROXY = new AtomicBoolean(true);
-
- private final static Set SERVICES_ID = new ConcurrentSkipListSet<>();
-
- private static Object springProxyFactory(Object target, ClassLoader classLoader,
- List adviceList, Class... interfaces) {
- final ProxyFactory proxyFactory = new ProxyFactory(interfaces);
- proxyFactory.setTarget(target);
- adviceList.forEach(advice -> proxyFactory.addAdvice(advice));
- return proxyFactory.getProxy(classLoader);
- }
-
- static Object newServerListProxy(Object bean, ClassLoader classLoader,
- IClientConfig clientConfig) {
- bean = springProxyFactory(bean, classLoader,
- Arrays.asList(new ServerListInvocationHandler(clientConfig)),
- new Class[] { ServerList.class });
- log.info("[service id]" + clientConfig.getClientName()
- + " new a ServerList proxy instance for spring cloud netflix to spring cloud alibaba ");
- collectServiceId(clientConfig.getClientName());
- return bean;
- }
-
- static Object newLoadBalancerProxy(Object bean, ClassLoader classLoader,
- final IClientConfig clientConfig) {
-
- bean = springProxyFactory(bean, classLoader,
- Arrays.asList(new AfterReturningAdvice() {
- private final IClientConfig iclientConfig = clientConfig;
-
- @Override
- public void afterReturning(Object returnValue, Method method,
- Object[] args, Object target) {
- String methodName = method.getName();
- if ("chooseServer".equals(methodName)) {
- String serviceId = iclientConfig.getClientName();
- Server server = (Server) returnValue;
- server = ServerListInvocationHandler
- .checkAndGetServiceServer(serviceId, server);
- ServerListInvocationHandler.incrementCallService(serviceId,
- server);
- }
- }
- }), new Class[] { ILoadBalancer.class });
- log.info("[service id]" + clientConfig.getClientName()
- + " new a ILoadBalancer proxy instance for spring cloud netflix to spring cloud alibaba ");
- return bean;
- }
-
- static void migrateProxyClose() {
- IS_PROXY.set(false);
- }
-
- static void migrateProxyUp() {
- IS_PROXY.set(true);
- }
-
- static boolean isMigrateProxy() {
-
- return IS_PROXY.get();
- }
-
- static void collectServiceId(String serviceId) {
- SERVICES_ID.add(serviceId);
- }
-
- static Set getServicesId() {
-
- return Collections.unmodifiableSet(SERVICES_ID);
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRefreshEventListener.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRefreshEventListener.java
deleted file mode 100644
index 70d12113..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRefreshEventListener.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package org.springframework.cloud.alicloud.ans.migrate;
-
-import com.netflix.loadbalancer.ILoadBalancer;
-import org.springframework.cloud.context.named.NamedContextFactory;
-import org.springframework.cloud.endpoint.event.RefreshEvent;
-import org.springframework.context.ApplicationListener;
-import org.springframework.core.env.Environment;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.PostConstruct;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-
-/**
- * @author pbting
- */
-@Component
-public class MigrateRefreshEventListener implements ApplicationListener {
-
- private final static int CHECK_INTERVAL = 1;
-
- private final static String MIGRATE_SWITCH = "spring.cloud.alicloud.migrate.ans.switch";
-
- private volatile String lastScaMigrateAnsSwitchValue = "true";
-
- private Environment environment;
-
- private NamedContextFactory namedContextFactory;
-
- public MigrateRefreshEventListener(Environment environment,
- NamedContextFactory namedContextFactory) {
- this.environment = environment;
- this.namedContextFactory = namedContextFactory;
- }
-
- @PostConstruct
- public void initTimerCheck() {
- Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(
- () -> onApplicationEvent(null), CHECK_INTERVAL, CHECK_INTERVAL,
- TimeUnit.SECONDS);
- }
-
- @Override
- public void onApplicationEvent(RefreshEvent event) {
- String value = environment.getProperty(MIGRATE_SWITCH, "true");
- // check 1: check the value
- if (value.equals(lastScaMigrateAnsSwitchValue)) {
- return;
- }
-
- updateLastScaMigrateAnsResetValue(value);
-
- // step 1: migrate up
- if ("true".equals(value)) {
- MigrateProxyManager.migrateProxyUp();
- serviceIdContextInit();
- return;
- }
-
- // step 2: migrate close
- if ("false".equals(value)) {
- MigrateProxyManager.migrateProxyClose();
- serviceIdContextInit();
- return;
- }
- }
-
- private void serviceIdContextInit() {
- namedContextFactory.destroy();
- // initializer each spring context for service id
- MigrateProxyManager.getServicesId().forEach(serviceId -> namedContextFactory
- .getInstance(serviceId, ILoadBalancer.class));
- }
-
- private synchronized void updateLastScaMigrateAnsResetValue(String value) {
- this.lastScaMigrateAnsSwitchValue = value;
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRibbonBeanPostProcessor.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRibbonBeanPostProcessor.java
deleted file mode 100644
index b03a1890..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRibbonBeanPostProcessor.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package org.springframework.cloud.alicloud.ans.migrate;
-
-import com.netflix.client.config.IClientConfig;
-import com.netflix.loadbalancer.ILoadBalancer;
-import com.netflix.loadbalancer.ServerList;
-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;
-
-public class MigrateRibbonBeanPostProcessor
- implements BeanPostProcessor, BeanClassLoaderAware {
-
- private static final Logger log = LoggerFactory.getLogger(MigrateOnCondition.class);
-
- private ClassLoader classLoader;
- private IClientConfig clientConfig;
-
- public MigrateRibbonBeanPostProcessor(IClientConfig clientConfig) {
- this.clientConfig = clientConfig;
- }
-
- @Override
- public Object postProcessAfterInitialization(Object bean, String beanName)
- throws BeansException {
-
- // step 1 : check the bean whether proxy or not
- if (!MigrateProxyManager.isMigrateProxy()) {
- log.info("Migrate proxy is Close.");
- return bean;
- }
-
- // step 2 : proxy the designated bean
- if (bean instanceof ServerList) {
- bean = MigrateProxyManager.newServerListProxy(bean, classLoader,
- clientConfig);
- }
-
- if (bean instanceof ILoadBalancer) {
- bean = MigrateProxyManager.newLoadBalancerProxy(bean, classLoader,
- clientConfig);
- }
- return bean;
- }
-
- @Override
- public void setBeanClassLoader(ClassLoader classLoader) {
- this.classLoader = classLoader;
- }
-
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateServiceRegistry.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateServiceRegistry.java
deleted file mode 100644
index 11ca9e9c..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateServiceRegistry.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package org.springframework.cloud.alicloud.ans.migrate;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.boot.web.context.WebServerInitializedEvent;
-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.ServiceRegistry;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.event.EventListener;
-import org.springframework.stereotype.Component;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * @author pbting
- */
-@Component
-public class MigrateServiceRegistry {
-
- private static final Logger log = LoggerFactory
- .getLogger(MigrateServiceRegistry.class);
-
- private AtomicBoolean running = new AtomicBoolean(false);
-
- private ServiceRegistry serviceRegistry;
- private AnsRegistration ansRegistration;
-
- public MigrateServiceRegistry(AnsProperties ansProperties,
- ApplicationContext context) {
- this.ansRegistration = new AnsRegistration(ansProperties, context);
- this.ansRegistration.init();
- this.serviceRegistry = new AnsServiceRegistry();
- }
-
- @EventListener(WebServerInitializedEvent.class)
- public void onApplicationEvent(WebServerInitializedEvent event) {
- int serverPort = event.getWebServer().getPort();
- this.ansRegistration.setPort(serverPort);
- log.info("[ Migrate ] change the port to " + serverPort);
- if (!this.running.get()) {
- long s = System.currentTimeMillis();
- log.info("[Migrate] start to registry server to ANS");
- this.serviceRegistry.register(this.ansRegistration);
- log.info("[migrate] end to registry server to ANS cost time with "
- + (System.currentTimeMillis() - s) + " ms.");
- this.running.set(true);
- }
- }
-
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrationAutoconfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrationAutoconfiguration.java
deleted file mode 100644
index 8f632bf1..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrationAutoconfiguration.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package org.springframework.cloud.alicloud.ans.migrate;
-
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
-import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.cloud.alicloud.ans.ConditionalOnAnsEnabled;
-import org.springframework.cloud.alicloud.context.ans.AnsProperties;
-import org.springframework.cloud.context.named.NamedContextFactory;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Conditional;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.core.env.Environment;
-
-/**
- * @author pbting
- */
-@Configuration
-@EnableConfigurationProperties
-@Conditional(MigrateOnConditionClass.class)
-@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
-@ConditionalOnAnsEnabled
-public class MigrationAutoconfiguration {
-
- @Bean
- public MigrateServiceRegistry migrationManger(AnsProperties ansProperties,
- ApplicationContext applicationContext) {
-
- return new MigrateServiceRegistry(ansProperties, applicationContext);
- }
-
- @Bean
- public MigrateRefreshEventListener migrateRefreshEventListener(
- Environment environment,
- @Qualifier(value = "springClientFactory") NamedContextFactory namedContextFactory) {
-
- return new MigrateRefreshEventListener(environment, namedContextFactory);
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerListInvocationHandler.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerListInvocationHandler.java
deleted file mode 100644
index 16d533c1..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerListInvocationHandler.java
+++ /dev/null
@@ -1,170 +0,0 @@
-package org.springframework.cloud.alicloud.ans.migrate;
-
-import com.netflix.client.config.IClientConfig;
-import com.netflix.loadbalancer.Server;
-import org.aopalliance.intercept.MethodInterceptor;
-import org.aopalliance.intercept.MethodInvocation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.cloud.alicloud.ans.ribbon.AnsServer;
-import org.springframework.cloud.alicloud.ans.ribbon.AnsServerList;
-
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.ConcurrentSkipListSet;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * @author pbting
- */
-class ServerListInvocationHandler implements MethodInterceptor {
-
- private static final Logger log = LoggerFactory
- .getLogger(ServerListInvocationHandler.class);
-
- private final static ConcurrentMap SERVER_LIST_CONCURRENT_MAP = new ConcurrentHashMap<>();
-
- private final static ConcurrentMap> CALL_SERVICE_COUNT = new ConcurrentHashMap<>();
-
- private final static Set INTERCEPTOR_METHOD_NAME = new ConcurrentSkipListSet();
-
- private IClientConfig clientConfig;
- private AnsServerList ansServerList;
- private AtomicBoolean isFirst = new AtomicBoolean(false);
-
- static {
- INTERCEPTOR_METHOD_NAME.add("getInitialListOfServers");
- INTERCEPTOR_METHOD_NAME.add("getUpdatedListOfServers");
- }
-
- ServerListInvocationHandler(IClientConfig clientConfig) {
- this.clientConfig = clientConfig;
- this.ansServerList = new AnsServerList(clientConfig.getClientName());
- SERVER_LIST_CONCURRENT_MAP.put(ansServerList.getDom(), ansServerList);
- }
-
- @Override
- public Object invoke(MethodInvocation invocation) throws Throwable {
- String methodName = invocation.getMethod().getName();
- // step 1: check the method is not interceptor
- if (!INTERCEPTOR_METHOD_NAME.contains(methodName)) {
- return invocation.proceed();
- }
-
- // step 2: interceptor the method
- List serverList = (List) invocation.proceed();
- long s = System.currentTimeMillis();
- log.info("[ START ] merage server list for " + clientConfig.getClientName());
- serverList = mergeAnsServerList(serverList);
- log.info("[ END ] merage server list for " + clientConfig.getClientName()
- + ", cost time " + (System.currentTimeMillis() - s) + " ms .");
- return serverList;
- }
-
- /**
- * 后台线程 和 Eureka 两个注册中心进行 Merage 的时候,List 表中始终保持是有效的 Server. 即不考虑 ANS 客户端本地容灾的情况
- */
- private List mergeAnsServerList(final List source) {
- if (isFirst.compareAndSet(false, true)) {
- return source;
- }
-
- // step 1: get all of server list and filter the alive
- List ansServerList = filterAliveAnsServer(
- this.ansServerList.getInitialListOfServers());
-
- if (ansServerList.isEmpty()) {
- return source;
- }
-
- log.info("[" + this.clientConfig.getClientName() + "] Get Server List from ANS:"
- + ansServerList + "; loadbalancer server list override before:" + source);
-
- // step 2:remove servers of that have in load balancer list
- final Iterator serverIterator = source.iterator();
- while (serverIterator.hasNext()) {
- final Server server = serverIterator.next();
- ansServerList.forEach(ansServer -> {
- if (server.getHostPort()
- .equals(ansServer.getHealthService().toInetAddr())) {
- // by: ZoneAffinityPredicate
- serverIterator.remove();
- log.info("Source Server is remove " + server.getHostPort()
- + ", and from ANS Server is override:"
- + ansServer.toString());
- }
- // fix bug: mast be set the zone, update server list,will filter
- ansServer.setZone(server.getZone());
- ansServer.setSchemea(server.getScheme());
- ansServer.setId(ansServer.getHealthService().toInetAddr());
- ansServer.setReadyToServe(true);
- });
- }
-
- ansServerList.forEach(ansServer -> source.add(ansServer));
- log.info("[" + this.clientConfig.getClientName() + "] "
- + "; loadbalancer server list override after:" + source);
- // override
- return source;
- }
-
- private List filterAliveAnsServer(List sourceServerList) {
- final List resultServerList = new LinkedList<>();
- sourceServerList.forEach(ansServer -> {
- boolean isAlive = ansServer.isAlive(3);
- if (isAlive) {
- resultServerList.add(ansServer);
- }
- log.warn(ansServer.toString() + " isAlive :" + isAlive);
- });
- return resultServerList;
- }
-
- static Map> getServerRegistry() {
-
- return Collections.unmodifiableMap(CALL_SERVICE_COUNT);
- }
-
- static Server checkAndGetServiceServer(String serviceId, Server server) {
- if (server != null) {
- return server;
- }
-
- log.warn(String.format("[%s] refers the server is null", server));
-
- List ansServerList = SERVER_LIST_CONCURRENT_MAP.get(serviceId)
- .getInitialListOfServers();
-
- if (!ansServerList.isEmpty()) {
- return ansServerList.get(0);
- }
-
- return server;
- }
-
- static void incrementCallService(String serviceId, Server server) {
- ConcurrentMap concurrentHashMap = CALL_SERVICE_COUNT
- .putIfAbsent(serviceId, new ConcurrentHashMap<>());
-
- if (concurrentHashMap == null) {
- concurrentHashMap = CALL_SERVICE_COUNT.get(serviceId);
- }
-
- String ipPort = server.getHostPort();
- ServerWrapper serverWraper = concurrentHashMap.putIfAbsent(ipPort,
- new ServerWrapper(server, new AtomicLong()));
-
- if (serverWraper == null) {
- serverWraper = concurrentHashMap.get(ipPort);
- }
- serverWraper.setServer(server);
- serverWraper.getCallCount().incrementAndGet();
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerWrapper.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerWrapper.java
deleted file mode 100644
index 4fbccfdf..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerWrapper.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package org.springframework.cloud.alicloud.ans.migrate;
-
-import com.netflix.loadbalancer.Server;
-
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * @author pbting
- */
-public class ServerWrapper {
-
- private Server server;
- private AtomicLong callCount;
-
- public ServerWrapper() {
- }
-
- public ServerWrapper(Server server, AtomicLong callCount) {
- this.server = server;
- this.callCount = callCount;
- }
-
- public Server getServer() {
- return server;
- }
-
- public void setServer(Server server) {
- this.server = server;
- }
-
- public AtomicLong getCallCount() {
- return callCount;
- }
-
- public void setCallCount(AtomicLong callCount) {
- this.callCount = callCount;
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java
index 4158dedb..56a37ade 100644
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java
+++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java
@@ -18,7 +18,6 @@ package org.springframework.cloud.alicloud.ans.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.ServiceRegistry;
@@ -34,7 +33,6 @@ public class AnsAutoServiceRegistration
private static final Logger log = LoggerFactory
.getLogger(AnsAutoServiceRegistration.class);
- @Autowired
private AnsRegistration registration;
public AnsAutoServiceRegistration(ServiceRegistry serviceRegistry,
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsServiceRegistry.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsServiceRegistry.java
index 6c4f6e03..05b43639 100644
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsServiceRegistry.java
+++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsServiceRegistry.java
@@ -41,11 +41,11 @@ public class AnsServiceRegistry implements ServiceRegistry {
public void register(AnsRegistration registration) {
if (!registration.isRegisterEnabled()) {
- log.info("Registration is disabled...");
+ log.warn("Registration is disabled...");
return;
}
if (StringUtils.isEmpty(registration.getServiceId())) {
- log.info("No service to register for client...");
+ log.warn("No service to register for client...");
return;
}
@@ -63,14 +63,13 @@ public class AnsServiceRegistry implements ServiceRegistry {
NamingService.regDom(dom, registration.getHost(), registration.getPort(),
registration.getRegisterWeight(dom), registration.getCluster(),
tags);
- log.info("INFO_ANS_REGISTER, " + dom + " "
- + registration.getAnsProperties().getClientIp() + ":"
- + registration.getAnsProperties().getClientPort()
- + " register finished");
+ log.info("INFO_ANS_REGISTER, {} {}:{} register finished", dom,
+ registration.getAnsProperties().getClientIp(),
+ registration.getAnsProperties().getClientPort());
}
catch (Exception e) {
- log.error("ERR_ANS_REGISTER, " + dom + " register failed..."
- + registration.toString() + ",", e);
+ log.error("ERR_ANS_REGISTER, {} register failed...{},", dom,
+ registration.toString(), e);
}
}
}
@@ -81,7 +80,7 @@ public class AnsServiceRegistry implements ServiceRegistry {
log.info("De-registering from ANSServer now...");
if (StringUtils.isEmpty(registration.getServiceId())) {
- log.info("No dom to de-register for client...");
+ log.warn("No dom to de-register for client...");
return;
}
@@ -90,8 +89,8 @@ public class AnsServiceRegistry implements ServiceRegistry {
registration.getPort(), registration.getCluster());
}
catch (Exception e) {
- log.error("ERR_ANS_DEREGISTER, de-register failed..."
- + registration.toString() + ",", e);
+ log.error("ERR_ANS_DEREGISTER, de-register failed...{},",
+ registration.toString(), e);
}
log.info("De-registration finished.");
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfiguration.java
index c67c6c38..d189a4da 100644
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfiguration.java
+++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfiguration.java
@@ -19,9 +19,7 @@ package org.springframework.cloud.alicloud.ans.ribbon;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ServerList;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionMissingClass;
import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
/**
@@ -29,7 +27,6 @@ import org.springframework.context.annotation.Configuration;
* @author pbting
*/
@Configuration
-@Conditional(MigrateOnConditionMissingClass.class)
public class AnsRibbonClientConfiguration {
@Bean
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServer.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServer.java
index d19f6287..55684a64 100644
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServer.java
+++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServer.java
@@ -16,16 +16,12 @@
package org.springframework.cloud.alicloud.ans.ribbon;
+import java.util.Collections;
+import java.util.Map;
+
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
import com.netflix.loadbalancer.Server;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-
/**
* @author xiaolongzuo
*/
@@ -38,8 +34,7 @@ public class AnsServer extends Server {
public AnsServer(final Host host, final String dom) {
super(host.getIp(), host.getPort());
this.host = host;
- this.metadata = new HashMap();
- this.metadata.put("source", "ANS");
+ this.metadata = Collections.emptyMap();
metaInfo = new MetaInfo() {
@Override
public String getAppName() {
@@ -64,33 +59,6 @@ public class AnsServer extends Server {
};
}
- @Override
- public boolean isAlive() {
-
- return true;
- }
-
- /**
- *
- * @param timeOut Unit: Seconds
- * @return
- */
- public boolean isAlive(long timeOut) {
- try {
- String hostName = this.host.getHostname();
- hostName = hostName != null && hostName.trim().length() > 0 ? hostName
- : this.host.getIp();
- Socket socket = new Socket();
- socket.connect(new InetSocketAddress(hostName, this.host.getPort()),
- (int) TimeUnit.SECONDS.toMillis(timeOut));
- socket.close();
- return true;
- }
- catch (IOException e) {
- return false;
- }
- }
-
@Override
public MetaInfo getMetaInfo() {
return metaInfo;
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerList.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerList.java
index c3b308be..f34f19ff 100644
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerList.java
+++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerList.java
@@ -16,23 +16,19 @@
package org.springframework.cloud.alicloud.ans.ribbon;
-import com.alibaba.ans.core.NamingService;
-import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
-
-import com.netflix.client.config.IClientConfig;
-import com.netflix.loadbalancer.AbstractServerList;
-
import java.util.ArrayList;
import java.util.List;
+import com.alibaba.ans.core.NamingService;
+import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
+import com.netflix.client.config.IClientConfig;
+import com.netflix.loadbalancer.AbstractServerList;
+
/**
* @author xiaolongzuo
- * @author pbting
*/
public class AnsServerList extends AbstractServerList {
- private final static int CONNECT_TIME_OUT = 3;
-
private String dom;
public AnsServerList(String dom) {
@@ -64,12 +60,10 @@ public class AnsServerList extends AbstractServerList {
List result = new ArrayList(hosts.size());
for (Host host : hosts) {
if (host.isValid()) {
- AnsServer ansServer = hostToServer(host);
- if (ansServer.isAlive(CONNECT_TIME_OUT)) {
- result.add(ansServer);
- }
+ result.add(hostToServer(host));
}
}
+
return result;
}
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/MigrateRibbonCofiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/MigrateRibbonCofiguration.java
deleted file mode 100644
index 9074b786..00000000
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/MigrateRibbonCofiguration.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package org.springframework.cloud.alicloud.ans.ribbon;
-
-import com.netflix.client.config.IClientConfig;
-import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionClass;
-import org.springframework.cloud.alicloud.ans.migrate.MigrateRibbonBeanPostProcessor;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Conditional;
-import org.springframework.context.annotation.Configuration;
-
-@Configuration
-@Conditional(MigrateOnConditionClass.class)
-public class MigrateRibbonCofiguration {
-
- @Bean
- public MigrateRibbonBeanPostProcessor migrateBeanPostProcessor(IClientConfig clientConfig) {
-
- return new MigrateRibbonBeanPostProcessor(clientConfig);
- }
-}
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/RibbonAnsAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/RibbonAnsAutoConfiguration.java
index cf7d52ff..4333cb53 100644
--- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/RibbonAnsAutoConfiguration.java
+++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/RibbonAnsAutoConfiguration.java
@@ -34,7 +34,6 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnBean(SpringClientFactory.class)
@ConditionalOnRibbonAns
@AutoConfigureAfter(RibbonAutoConfiguration.class)
-@RibbonClients(defaultConfiguration = { AnsRibbonClientConfiguration.class,
- MigrateRibbonCofiguration.class })
+@RibbonClients(defaultConfiguration = AnsRibbonClientConfiguration.class)
public class RibbonAnsAutoConfiguration {
}
diff --git a/spring-cloud-alicloud-ans/src/main/resources/META-INF/spring.factories b/spring-cloud-alicloud-ans/src/main/resources/META-INF/spring.factories
index 63f54329..02177b93 100644
--- a/spring-cloud-alicloud-ans/src/main/resources/META-INF/spring.factories
+++ b/spring-cloud-alicloud-ans/src/main/resources/META-INF/spring.factories
@@ -2,6 +2,4 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.alicloud.ans.endpoint.AnsEndpointAutoConfiguration,\
org.springframework.cloud.alicloud.ans.ribbon.RibbonAnsAutoConfiguration,\
org.springframework.cloud.alicloud.ans.AnsAutoConfiguration,\
- org.springframework.cloud.alicloud.ans.migrate.MigrateEndpointAutoConfiguration,\
- org.springframework.cloud.alicloud.ans.migrate.MigrationAutoconfiguration,\
org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration
\ No newline at end of file
diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerListTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerListTests.java
index 815fa89d..b7cf34e3 100644
--- a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerListTests.java
+++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerListTests.java
@@ -71,8 +71,6 @@ public class AnsServerListTests {
PowerMockito.mockStatic(NamingService.class);
when(NamingService.getHosts(anyString())).thenReturn(hosts);
- PowerMockito.stub(PowerMockito.method(AnsServer.class, "isAlive", long.class))
- .toReturn(true);
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
@@ -101,8 +99,6 @@ public class AnsServerListTests {
when(NamingService.getHosts(eq("test-service"))).thenReturn(
hosts.stream().filter(Host::isValid).collect(Collectors.toList()));
- PowerMockito.stub(PowerMockito.method(AnsServer.class, "isAlive", long.class))
- .toReturn(true);
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
@@ -132,8 +128,6 @@ public class AnsServerListTests {
PowerMockito.mockStatic(NamingService.class);
when(NamingService.getHosts(eq("test-service"))).thenReturn(
hosts.stream().filter(Host::isValid).collect(Collectors.toList()));
- PowerMockito.stub(PowerMockito.method(AnsServer.class, "isAlive", long.class))
- .toReturn(true);
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
diff --git a/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/SmsServiceImpl.java b/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/SmsServiceImpl.java
index 3b83cfb6..91a0cccb 100644
--- a/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/SmsServiceImpl.java
+++ b/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/SmsServiceImpl.java
@@ -17,15 +17,20 @@ package org.springframework.cloud.alicloud.sms;
import java.text.ParseException;
-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.context.AliCloudProperties;
import org.springframework.cloud.alicloud.context.sms.SmsProperties;
import org.springframework.cloud.alicloud.sms.base.DefaultAlicomMessagePuller;
import org.springframework.cloud.alicloud.sms.endpoint.EndpointManager;
import org.springframework.cloud.alicloud.sms.endpoint.ReceiveMessageEntity;
-import com.aliyuncs.dysmsapi.model.v20170525.*;
+import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
+import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
+import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsRequest;
+import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsResponse;
+import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
+import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
@@ -34,7 +39,7 @@ import com.aliyuncs.exceptions.ServerException;
*/
public final class SmsServiceImpl extends AbstractSmsService {
- private static final Log log = LogFactory.getLog(SmsServiceImpl.class);
+ private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);
/**
* will expose user to call this method send sms message
* @param sendSmsRequest
diff --git a/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/base/DefaultAlicomMessagePuller.java b/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/base/DefaultAlicomMessagePuller.java
index 50fe2ed6..df03a071 100755
--- a/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/base/DefaultAlicomMessagePuller.java
+++ b/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/base/DefaultAlicomMessagePuller.java
@@ -15,14 +15,6 @@
*/
package org.springframework.cloud.alicloud.sms.base;
-import com.aliyun.mns.client.CloudQueue;
-import com.aliyun.mns.common.ClientException;
-import com.aliyun.mns.common.ServiceException;
-import com.aliyun.mns.model.Message;
-import org.apache.commons.lang3.concurrent.BasicThreadFactory;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@@ -33,12 +25,22 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
+import org.apache.commons.lang3.concurrent.BasicThreadFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.aliyun.mns.client.CloudQueue;
+import com.aliyun.mns.common.ClientException;
+import com.aliyun.mns.common.ServiceException;
+import com.aliyun.mns.model.Message;
+
/**
* 阿里通信官方消息默认拉取工具类
*/
public class DefaultAlicomMessagePuller {
- private Log logger = LogFactory.getLog(DefaultAlicomMessagePuller.class);
+ private static final Logger log = LoggerFactory
+ .getLogger(DefaultAlicomMessagePuller.class);
private String mnsAccountEndpoint = "https://1943695596114318.mns.cn-hangzhou.aliyuncs.com/";// 阿里通信消息的endpoint,固定。
private String endpointNameForPop = "cn-hangzhou";
@@ -103,7 +105,7 @@ public class DefaultAlicomMessagePuller {
sPollingMap.put(queueName, false);
lockObj.notifyAll();
if (debugLogOpen) {
- logger.info("PullMessageTask_WakeUp:Everyone WakeUp and Work!");
+ log.info("PullMessageTask_WakeUp:Everyone WakeUp and Work!");
}
}
}
@@ -131,7 +133,7 @@ public class DefaultAlicomMessagePuller {
if (p != null && p) {
try {
if (debugLogOpen) {
- logger.info("PullMessageTask_sleep:"
+ log.info("PullMessageTask_sleep:"
+ Thread.currentThread().getName()
+ " Have a nice sleep!");
}
@@ -140,7 +142,7 @@ public class DefaultAlicomMessagePuller {
}
catch (InterruptedException e) {
if (debugLogOpen) {
- logger.info("PullMessageTask_Interrupted!"
+ log.info("PullMessageTask_Interrupted!"
+ Thread.currentThread().getName()
+ " QueueName is " + queueName);
}
@@ -158,7 +160,7 @@ public class DefaultAlicomMessagePuller {
if (debugLogOpen) {
SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
- logger.info("PullMessageTask_popMessage:"
+ log.info("PullMessageTask_popMessage:"
+ Thread.currentThread().getName() + "-popDone at "
+ "," + format.format(new Date()) + " msgSize="
+ (popMsg == null ? 0 : popMsg.getMessageId()));
@@ -171,7 +173,7 @@ public class DefaultAlicomMessagePuller {
else {
if (setPolling(queueName)) {
if (debugLogOpen) {
- logger.info("PullMessageTask_setPolling:"
+ log.info("PullMessageTask_setPolling:"
+ Thread.currentThread().getName() + " Polling!");
}
}
@@ -180,7 +182,7 @@ public class DefaultAlicomMessagePuller {
}
do {
if (debugLogOpen) {
- logger.info("PullMessageTask_Keep_Polling"
+ log.info("PullMessageTask_Keep_Polling"
+ Thread.currentThread().getName()
+ "KEEP Polling!");
}
@@ -189,7 +191,7 @@ public class DefaultAlicomMessagePuller {
}
catch (ClientException e) {
if (debugLogOpen) {
- logger.info(
+ log.info(
"PullMessageTask_Pop_Message:ClientException Refresh accessKey"
+ e);
}
@@ -200,7 +202,7 @@ public class DefaultAlicomMessagePuller {
}
catch (ServiceException e) {
if (debugLogOpen) {
- logger.info(
+ log.info(
"PullMessageTask_Pop_Message:ServiceException Refresh accessKey"
+ e);
}
@@ -211,7 +213,7 @@ public class DefaultAlicomMessagePuller {
}
catch (Exception e) {
if (debugLogOpen) {
- logger.info(
+ log.info(
"PullMessageTask_Pop_Message:Exception Happened when polling popMessage: "
+ e);
}
@@ -224,7 +226,7 @@ public class DefaultAlicomMessagePuller {
if (dealResult) {
// remember to delete message when consume message successfully.
if (debugLogOpen) {
- logger.info("PullMessageTask_Deal_Message:"
+ log.info("PullMessageTask_Deal_Message:"
+ Thread.currentThread().getName() + "deleteMessage "
+ popMsg.getMessageId());
}
@@ -232,19 +234,19 @@ public class DefaultAlicomMessagePuller {
}
}
catch (ClientException e) {
- logger.error("PullMessageTask_execute_error,messageType:"
- + messageType + ",queueName:" + queueName, e);
+ log.error("PullMessageTask_execute_error,messageType:" + messageType
+ + ",queueName:" + queueName, e);
break;
}
catch (ServiceException e) {
if (e.getErrorCode().equals("AccessDenied")) {
- logger.error("PullMessageTask_execute_error,messageType:"
+ log.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName
+ ",please check messageType and queueName", e);
}
else {
- logger.error("PullMessageTask_execute_error,messageType:"
+ log.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName, e);
}
break;
@@ -252,30 +254,30 @@ public class DefaultAlicomMessagePuller {
}
catch (com.aliyuncs.exceptions.ClientException e) {
if (e.getErrCode().equals("InvalidAccessKeyId.NotFound")) {
- logger.error("PullMessageTask_execute_error,messageType:"
+ log.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName
+ ",please check AccessKeyId", e);
}
if (e.getErrCode().equals("SignatureDoesNotMatch")) {
- logger.error("PullMessageTask_execute_error,messageType:"
+ log.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName
+ ",please check AccessKeySecret", e);
}
else {
- logger.error("PullMessageTask_execute_error,messageType:"
+ log.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName, e);
}
break;
}
catch (Exception e) {
- logger.error("PullMessageTask_execute_error,messageType:"
- + messageType + ",queueName:" + queueName, e);
+ log.error("PullMessageTask_execute_error,messageType:" + messageType
+ + ",queueName:" + queueName, e);
try {
Thread.sleep(sleepSecondWhenNoData);
}
catch (InterruptedException e1) {
- logger.error("PullMessageTask_execute_error,messageType:"
+ log.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName, e);
}
}
diff --git a/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/base/TokenGetterForAlicom.java b/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/base/TokenGetterForAlicom.java
index 270f9a56..e312ec36 100755
--- a/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/base/TokenGetterForAlicom.java
+++ b/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/base/TokenGetterForAlicom.java
@@ -15,6 +15,15 @@
*/
package org.springframework.cloud.alicloud.sms.base;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.TimeZone;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
@@ -27,21 +36,13 @@ import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.TimeZone;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
/**
* 获取接收云通信消息的临时token
*
*/
public class TokenGetterForAlicom {
- private Log logger = LogFactory.getLog(TokenGetterForAlicom.class);
+ private static final Logger log = LoggerFactory.getLogger(TokenGetterForAlicom.class);
private String accessKeyId;
private String accessKeySecret;
private String endpointNameForPop;
@@ -100,7 +101,7 @@ public class TokenGetterForAlicom {
return token;
}
else {
- logger.error("getTokenFromRemote_error,messageType:" + messageType + ",code:"
+ log.error("getTokenFromRemote_error,messageType:" + messageType + ",code:"
+ response.getCode() + ",message:" + response.getMessage());
throw new ServerException(response.getCode(), response.getMessage());
}
@@ -124,8 +125,6 @@ public class TokenGetterForAlicom {
CloudAccount account = new CloudAccount(token.getTempAccessKeyId(),
token.getTempAccessKeySecret(), mnsAccountEndpoint,
token.getToken());
- // logger.warn("ak:"+token.getTempAccessKey());
- // logger.warn("token:"+token.getToken());
MNSClient client = account.getMNSClient();
CloudQueue queue = client.getQueueRef(queueName);
token.setClient(client);
diff --git a/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/endpoint/SmsEndpoint.java b/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/endpoint/SmsEndpoint.java
index d254e0eb..77d8e39b 100644
--- a/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/endpoint/SmsEndpoint.java
+++ b/spring-cloud-alicloud-sms/src/main/java/org/springframework/cloud/alicloud/sms/endpoint/SmsEndpoint.java
@@ -15,12 +15,12 @@
*/
package org.springframework.cloud.alicloud.sms.endpoint;
+import java.util.Map;
+
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
-import java.util.Map;
-
-@Endpoint(id = "sms-info")
+@Endpoint(id = "sms")
public class SmsEndpoint {
@ReadOperation