diff --git a/spring-cloud-alibaba-dependencies/pom.xml b/spring-cloud-alibaba-dependencies/pom.xml
index 72c2c369..9958ae6e 100644
--- a/spring-cloud-alibaba-dependencies/pom.xml
+++ b/spring-cloud-alibaba-dependencies/pom.xml
@@ -16,9 +16,9 @@
Spring Cloud Alibaba Dependencies
- 1.4.1
+ 1.4.2
3.1.0
- 0.8.1
+ 0.8.2
0.1.3
1.0.8
1.0.1
diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/pom.xml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/pom.xml
index fd6c6875..f8e1217a 100644
--- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/pom.xml
+++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/pom.xml
@@ -44,11 +44,6 @@
org.springframework.cloud
spring-cloud-starter-alibaba-sentinel
-
-
- org.springframework.cloud
- spring-cloud-alicloud-context
-
diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/pom.xml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/pom.xml
index 0f28a7ac..9397b274 100644
--- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/pom.xml
+++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/pom.xml
@@ -29,11 +29,6 @@
org.springframework.boot
spring-boot-starter-actuator
-
-
- org.springframework.cloud
- spring-cloud-alicloud-context
-
diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/HelloController.java b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/HelloController.java
new file mode 100644
index 00000000..c11cbf98
--- /dev/null
+++ b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/HelloController.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2018 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cloud.alibaba.cloud.examples;
+
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * @author xiaolongzuo
+ */
+@RestController
+public class HelloController {
+
+ @RequestMapping("/")
+ @ResponseBody
+ public String hello() {
+ return "OK";
+ }
+
+}
diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/SimpleTask.java b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/SimpleTask.java
index 09055da1..17ced464 100644
--- a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/SimpleTask.java
+++ b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/SimpleTask.java
@@ -16,25 +16,25 @@
package org.springframework.cloud.alibaba.cloud.examples;
+import org.springframework.beans.factory.annotation.Autowired;
+
import com.alibaba.edas.schedulerx.ProcessResult;
import com.alibaba.edas.schedulerx.ScxSimpleJobContext;
import com.alibaba.edas.schedulerx.ScxSimpleJobProcessor;
-import org.springframework.beans.factory.annotation.Autowired;
/**
* @author xiaolongzuo
*/
public class SimpleTask implements ScxSimpleJobProcessor {
- @Autowired
- private TestService testService;
+ @Autowired
+ private TestService testService;
- @Override
- public ProcessResult process(ScxSimpleJobContext context) {
- System.out.println("-----------Hello world---------------");
- testService.test();
- ProcessResult processResult = new ProcessResult(true);
- return processResult;
- }
+ @Override
+ public ProcessResult process(ScxSimpleJobContext context) {
+ testService.test();
+ ProcessResult processResult = new ProcessResult(true);
+ return processResult;
+ }
}
diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestController.java b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestController.java
new file mode 100644
index 00000000..b237b279
--- /dev/null
+++ b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestController.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2018 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cloud.alibaba.cloud.examples;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * @author xiaolongzuo
+ */
+@RestController
+public class TestController {
+
+ static AtomicInteger atomicInteger = new AtomicInteger(0);
+
+ @RequestMapping("/test")
+ @ResponseBody
+ public String test() {
+ return String.valueOf(atomicInteger.get());
+ }
+
+}
diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestService.java b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestService.java
index 1786d197..3352c05a 100644
--- a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestService.java
+++ b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/org/springframework/cloud/alibaba/cloud/examples/TestService.java
@@ -24,7 +24,7 @@ import org.springframework.stereotype.Service;
@Service
public class TestService {
- public void test() {
- System.out.println("---------IOC Success--------");
- }
+ public void test() {
+ TestController.atomicInteger.incrementAndGet();
+ }
}
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 076d884f..94933a4d 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
@@ -17,6 +17,7 @@
package org.springframework.cloud.alibaba.nacos;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -27,15 +28,17 @@ import org.springframework.context.annotation.Configuration;
@Configuration
public class NacosConfigBootstrapConfiguration {
- @Bean
- public NacosPropertySourceLocator nacosPropertySourceLocator() {
- return new NacosPropertySourceLocator();
- }
-
@Bean
@ConditionalOnMissingBean
public NacosConfigProperties nacosConfigProperties() {
return new NacosConfigProperties();
}
+ @Bean
+ @ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
+ public NacosPropertySourceLocator nacosPropertySourceLocator(
+ NacosConfigProperties nacosConfigProperties) {
+ return new NacosPropertySourceLocator(nacosConfigProperties);
+ }
+
}
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 abeec2d7..c0e45492 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
@@ -44,9 +44,14 @@ public class NacosConfigProperties {
public static final String PREFIX = "spring.cloud.nacos.config";
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger log = LoggerFactory
.getLogger(NacosConfigProperties.class);
+ /**
+ * whether to enable nacos config.
+ */
+ private boolean enabled = true;
+
/**
* nacos config server address
*/
@@ -137,11 +142,15 @@ public class NacosConfigProperties {
this.activeProfiles = environment.getActiveProfiles();
}
- public void setActiveProfiles(String[] activeProfiles) {
- this.activeProfiles = activeProfiles;
+ // todo sts support
+
+ public boolean isEnabled() {
+ return enabled;
}
- // todo sts support
+ public void setEnabled(boolean enabled) {
+ this.enabled = enabled;
+ }
public String getServerAddr() {
return serverAddr;
@@ -243,10 +252,6 @@ public class NacosConfigProperties {
return name;
}
- public void setName(String name) {
- this.name = name;
- }
-
public String[] getActiveProfiles() {
return activeProfiles;
}
@@ -275,6 +280,14 @@ public class NacosConfigProperties {
this.extConfig = extConfig;
}
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setActiveProfiles(String[] activeProfiles) {
+ this.activeProfiles = activeProfiles;
+ }
+
public static class Config {
/**
* the data id of extended configuration
@@ -316,16 +329,17 @@ public class NacosConfigProperties {
@Override
public String toString() {
- return "NacosConfigProperties{" + "serverAddr='" + serverAddr + '\''
- + ", encode='" + encode + '\'' + ", group='" + group + '\''
- + ", sharedDataids='" + this.sharedDataids + '\''
- + ", refreshableDataids='" + this.refreshableDataids + '\'' + ", prefix='"
- + prefix + '\'' + ", fileExtension='" + fileExtension + '\''
- + ", timeout=" + timeout + ", endpoint='" + endpoint + '\''
- + ", namespace='" + namespace + '\'' + ", accessKey='" + accessKey + '\''
- + ", secretKey='" + secretKey + '\'' + ", contextPath='" + contextPath
- + '\'' + ", clusterName='" + clusterName + '\'' + ", name='" + name + '\''
- + ", activeProfiles=" + Arrays.toString(activeProfiles) + '}';
+ return "NacosConfigProperties{" + "enabled=" + enabled + ", serverAddr='"
+ + serverAddr + '\'' + ", encode='" + encode + '\'' + ", group='" + group
+ + '\'' + ", prefix='" + prefix + '\'' + ", fileExtension='"
+ + fileExtension + '\'' + ", timeout=" + timeout + ", endpoint='"
+ + endpoint + '\'' + ", namespace='" + namespace + '\'' + ", accessKey='"
+ + accessKey + '\'' + ", secretKey='" + secretKey + '\''
+ + ", contextPath='" + contextPath + '\'' + ", clusterName='" + clusterName
+ + '\'' + ", name='" + name + '\'' + ", activeProfiles="
+ + Arrays.toString(activeProfiles) + ", sharedDataids='" + sharedDataids
+ + '\'' + ", refreshableDataids='" + refreshableDataids + '\''
+ + ", extConfig=" + extConfig + '}';
}
public ConfigService configServiceInstance() {
@@ -348,7 +362,7 @@ public class NacosConfigProperties {
return configService;
}
catch (Exception e) {
- LOGGER.error("create config service error!properties={},e=,", this, e);
+ log.error("create config service error!properties={},e=,", this, e);
return null;
}
}
diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceBuilder.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceBuilder.java
index d7e0766f..d5369007 100644
--- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceBuilder.java
+++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/client/NacosPropertySourceBuilder.java
@@ -33,7 +33,7 @@ import java.util.*;
* @author pbting
*/
public class NacosPropertySourceBuilder {
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger log = LoggerFactory
.getLogger(NacosPropertySourceBuilder.class);
private static final Properties EMPTY_PROPERTIES = new Properties();
@@ -68,9 +68,6 @@ public class NacosPropertySourceBuilder {
NacosPropertySource build(String dataId, String group, String fileExtension,
boolean isRefreshable) {
Properties p = loadNacosData(dataId, group, fileExtension);
- if (p == null) {
- p = EMPTY_PROPERTIES;
- }
NacosPropertySource nacosPropertySource = new NacosPropertySource(group, dataId,
propertiesToMap(p), new Date(), isRefreshable);
NacosPropertySourceRepository.collectNacosPropertySources(nacosPropertySource);
@@ -82,7 +79,7 @@ public class NacosPropertySourceBuilder {
try {
data = configService.getConfig(dataId, group, timeout);
if (!StringUtils.isEmpty(data)) {
- LOGGER.info(String.format("Loading nacos data, dataId: '%s', group: '%s'",
+ log.info(String.format("Loading nacos data, dataId: '%s', group: '%s'",
dataId, group));
if (fileExtension.equalsIgnoreCase("properties")) {
@@ -101,21 +98,20 @@ public class NacosPropertySourceBuilder {
}
}
catch (NacosException e) {
- LOGGER.error("get data from Nacos error,dataId:{}, ", dataId, e);
+ log.error("get data from Nacos error,dataId:{}, ", dataId, e);
}
catch (Exception e) {
- LOGGER.error("parse data from Nacos error,dataId:{},data:{},", dataId, data,
- e);
+ log.error("parse data from Nacos error,dataId:{},data:{},", dataId, data, e);
}
- return null;
+ return EMPTY_PROPERTIES;
}
@SuppressWarnings("unchecked")
private Map propertiesToMap(Properties properties) {
Map result = new HashMap<>(16);
- Enumeration tmpKeys = (Enumeration) properties.propertyNames();
- while (tmpKeys.hasMoreElements()) {
- String key = tmpKeys.nextElement();
+ Enumeration keys = (Enumeration) properties.propertyNames();
+ while (keys.hasMoreElements()) {
+ String key = keys.nextElement();
Object value = properties.getProperty(key);
if (value != null) {
result.put(key, ((String) value).trim());
@@ -126,4 +122,5 @@ public class NacosPropertySourceBuilder {
}
return result;
}
+
}
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 647856b1..7a665d2b 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
@@ -19,7 +19,6 @@ package org.springframework.cloud.alibaba.nacos.client;
import com.alibaba.nacos.api.config.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosConfigProperties;
import org.springframework.cloud.alibaba.nacos.NacosPropertySourceRepository;
import org.springframework.cloud.alibaba.nacos.refresh.NacosContextRefresher;
@@ -40,7 +39,7 @@ import java.util.List;
@Order(0)
public class NacosPropertySourceLocator implements PropertySourceLocator {
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger log = LoggerFactory
.getLogger(NacosPropertySourceLocator.class);
private static final String NACOS_PROPERTY_SOURCE_NAME = "NACOS";
private static final String SEP1 = "-";
@@ -49,22 +48,21 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
private static final List SUPPORT_FILE_EXTENSION = Arrays.asList("properties",
"yaml", "yml");
- @Autowired
+ private NacosPropertySourceBuilder nacosPropertySourceBuilder;
+
private NacosConfigProperties nacosConfigProperties;
- public NacosPropertySourceLocator() {
+ public NacosPropertySourceLocator(NacosConfigProperties nacosConfigProperties) {
+ this.nacosConfigProperties = nacosConfigProperties;
}
- private NacosPropertySourceBuilder nacosPropertySourceBuilder;
-
@Override
public PropertySource> locate(Environment env) {
ConfigService configService = nacosConfigProperties.configServiceInstance();
if (null == configService) {
- LOGGER.warn(
- "no instance of config service found, can't load config from nacos");
+ log.warn("no instance of config service found, can't load config from nacos");
return null;
}
long timeout = nacosConfigProperties.getTimeout();
@@ -167,8 +165,7 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
private void loadNacosDataIfPresent(final CompositePropertySource composite,
final String dataId, final String group, String fileExtension,
boolean isRefreshable) {
-
- if (NacosContextRefresher.loadCount.get() != 0) {
+ if (NacosContextRefresher.getRefreshCount() != 0) {
NacosPropertySource ps;
if (!isRefreshable) {
ps = NacosPropertySourceRepository.getNacosPropertySource(dataId);
@@ -184,18 +181,22 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
fileExtension, isRefreshable);
composite.addFirstPropertySource(ps);
}
-
}
- private static void checkDataIdFileExtension(String[] sharedDataIdArry) {
+ private static void checkDataIdFileExtension(String[] dataIdArray) {
StringBuilder stringBuilder = new StringBuilder();
- outline: for (int i = 0; i < sharedDataIdArry.length; i++) {
+ for (int i = 0; i < dataIdArray.length; i++) {
+ boolean isLegal = false;
for (String fileExtension : SUPPORT_FILE_EXTENSION) {
- if (sharedDataIdArry[i].indexOf(fileExtension) > 0) {
- continue outline;
+ if (dataIdArray[i].indexOf(fileExtension) > 0) {
+ isLegal = true;
+ break;
}
}
- stringBuilder.append(sharedDataIdArry[i] + ",");
+ // add tips
+ if (!isLegal) {
+ stringBuilder.append(dataIdArray[i] + ",");
+ }
}
if (stringBuilder.length() > 0) {
diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/refresh/NacosContextRefresher.java b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/refresh/NacosContextRefresher.java
index 28a1d47e..1fc7e8b0 100644
--- a/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/refresh/NacosContextRefresher.java
+++ b/spring-cloud-alibaba-nacos-config/src/main/java/org/springframework/cloud/alibaba/nacos/refresh/NacosContextRefresher.java
@@ -19,6 +19,7 @@ package org.springframework.cloud.alibaba.nacos.refresh;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
@@ -51,10 +52,10 @@ import java.util.concurrent.atomic.AtomicLong;
public class NacosContextRefresher
implements ApplicationListener, ApplicationContextAware {
- private final static Logger LOGGER = LoggerFactory
+ private final static Logger log = LoggerFactory
.getLogger(NacosContextRefresher.class);
- public static final AtomicLong loadCount = new AtomicLong(0);
+ private static final AtomicLong REFRESH_COUNT = new AtomicLong(0);
private final NacosRefreshProperties refreshProperties;
@@ -110,7 +111,7 @@ public class NacosContextRefresher
listener = new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
- loadCount.incrementAndGet();
+ refreshCountIncrement();
String md5 = "";
if (!StringUtils.isEmpty(configInfo)) {
try {
@@ -120,16 +121,15 @@ public class NacosContextRefresher
}
catch (NoSuchAlgorithmException
| UnsupportedEncodingException e) {
- LOGGER.warn("[Nacos] unable to get md5 for dataId: " + dataId,
+ log.warn("[Nacos] unable to get md5 for dataId: " + dataId,
e);
}
}
refreshHistory.add(dataId, md5);
applicationContext.publishEvent(
new RefreshEvent(this, null, "Refresh Nacos config"));
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Refresh Nacos config group{},dataId{}", group,
- dataId);
+ if (log.isDebugEnabled()) {
+ log.debug("Refresh Nacos config group{},dataId{}", group, dataId);
}
}
@@ -149,4 +149,11 @@ public class NacosContextRefresher
}
}
+ public static long getRefreshCount() {
+ return REFRESH_COUNT.get();
+ }
+
+ public static void refreshCountIncrement() {
+ REFRESH_COUNT.incrementAndGet();
+ }
}
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 6e087422..f53a0562 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
@@ -16,16 +16,23 @@
package org.springframework.cloud.alibaba.nacos;
+import org.springframework.boot.ApplicationArguments;
+import org.springframework.boot.ApplicationRunner;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.registry.NacosAutoServiceRegistration;
import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration;
import org.springframework.cloud.alibaba.nacos.registry.NacosServiceRegistry;
-import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration;
+import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
+import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -38,19 +45,28 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnNacosDiscoveryEnabled
@ConditionalOnClass(name = "org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent")
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
-@AutoConfigureBefore({ AutoServiceRegistrationAutoConfiguration.class,
- NacosDiscoveryClientAutoConfiguration.class })
+@AutoConfigureBefore(NacosDiscoveryClientAutoConfiguration.class)
+@AutoConfigureAfter(AutoServiceRegistrationConfiguration.class)
public class NacosDiscoveryAutoConfiguration {
@Bean
- public NacosServiceRegistry nacosServiceRegistry() {
- return new NacosServiceRegistry();
+ @ConditionalOnMissingBean
+ public NacosDiscoveryProperties nacosProperties() {
+ return new NacosDiscoveryProperties();
+ }
+
+ @Bean
+ public NacosServiceRegistry nacosServiceRegistry(
+ NacosDiscoveryProperties nacosDiscoveryProperties) {
+ return new NacosServiceRegistry(nacosDiscoveryProperties);
}
@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
- public NacosRegistration nacosRegistration() {
- return new NacosRegistration();
+ public NacosRegistration nacosRegistration(
+ NacosDiscoveryProperties nacosDiscoveryProperties,
+ ApplicationContext context) {
+ return new NacosRegistration(nacosDiscoveryProperties, context);
}
@Bean
@@ -62,4 +78,31 @@ public class NacosDiscoveryAutoConfiguration {
return new NacosAutoServiceRegistration(registry,
autoServiceRegistrationProperties, registration);
}
+
+ @Bean
+ @ConditionalOnBean(NacosAutoServiceRegistration.class) // NacosAutoServiceRegistration
+ // should be present
+ @ConditionalOnNotWebApplication // Not Web Application
+ public ApplicationRunner applicationRunner(
+ final NacosAutoServiceRegistration nacosAutoServiceRegistration) {
+
+ return new ApplicationRunner() {
+ @Override
+ public void run(ApplicationArguments args) throws Exception {
+ if (!nacosAutoServiceRegistration.isRunning()) { // If it's not running,
+ // let
+ // it start.
+ // FIXME: Please make sure "spring.cloud.nacos.discovery.port" must be
+ // configured on an available port,
+ // or the startup or Nacos health check will be failed.
+ nacosAutoServiceRegistration.start();
+ // NacosAutoServiceRegistration will be stopped after its destroy()
+ // method
+ // is invoked.
+ // @PreDestroy destroy() -> stop()
+ }
+ }
+ };
+ }
+
}
\ No newline at end of file
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 11fb1290..ecb0b136 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
@@ -27,7 +27,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
-
import javax.annotation.PostConstruct;
import java.net.Inet4Address;
import java.net.InetAddress;
@@ -40,7 +39,7 @@ import static com.alibaba.nacos.api.PropertyKeyConst.*;
/**
* @author dungu.zpf
* @author xiaojing
- * @author pbting
+ * @author Mercy
*/
@ConfigurationProperties("spring.cloud.nacos.discovery")
@@ -65,6 +64,11 @@ public class NacosDiscoveryProperties {
*/
private String namespace;
+ /**
+ * watch delay,duration to pull new service from nacos server.
+ */
+ private long watchDelay = 5000;
+
/**
* nacos naming log file name
*/
@@ -145,7 +149,14 @@ public class NacosDiscoveryProperties {
@PostConstruct
public void init() throws SocketException {
+ if (secure) {
+ metadata.put("secure", "true");
+ }
+
serverAddr = Objects.toString(serverAddr, "");
+ if (serverAddr.lastIndexOf("/") != -1) {
+ serverAddr.substring(0, serverAddr.length() - 1);
+ }
endpoint = Objects.toString(endpoint, "");
namespace = Objects.toString(namespace, "");
logName = Objects.toString(logName, "");
@@ -158,7 +169,7 @@ public class NacosDiscoveryProperties {
else {
NetworkInterface netInterface = NetworkInterface
.getByName(networkInterface);
- if (null == networkInterface) {
+ if (null == netInterface) {
throw new IllegalArgumentException(
"no such interface " + networkInterface);
}
@@ -316,16 +327,25 @@ public class NacosDiscoveryProperties {
this.namingLoadCacheAtStart = namingLoadCacheAtStart;
}
+ public long getWatchDelay() {
+ return watchDelay;
+ }
+
+ public void setWatchDelay(long watchDelay) {
+ this.watchDelay = watchDelay;
+ }
+
@Override
public String toString() {
return "NacosDiscoveryProperties{" + "serverAddr='" + serverAddr + '\''
+ ", endpoint='" + endpoint + '\'' + ", namespace='" + namespace + '\''
- + ", logName='" + logName + '\'' + ", service='" + service + '\''
- + ", weight=" + weight + ", clusterName='" + clusterName + '\''
- + ", metadata=" + metadata + ", registerEnabled=" + registerEnabled
- + ", ip='" + ip + '\'' + ", networkInterface='" + networkInterface + '\''
- + ", port=" + port + ", secure=" + secure + ", accessKey='" + accessKey
- + ", namingLoadCacheAtStart=" + namingLoadCacheAtStart + '\''
+ + ", watchDelay=" + watchDelay + ", logName='" + logName + '\''
+ + ", service='" + service + '\'' + ", weight=" + weight
+ + ", clusterName='" + clusterName + '\'' + ", namingLoadCacheAtStart='"
+ + namingLoadCacheAtStart + '\'' + ", metadata=" + metadata
+ + ", registerEnabled=" + registerEnabled + ", ip='" + ip + '\''
+ + ", networkInterface='" + networkInterface + '\'' + ", port=" + port
+ + ", secure=" + secure + ", accessKey='" + accessKey + '\''
+ ", secretKey='" + secretKey + '\'' + '}';
}
@@ -353,7 +373,7 @@ public class NacosDiscoveryProperties {
}
if (StringUtils.isEmpty(this.getClusterName())) {
this.setClusterName(env.resolvePlaceholders(
- "${spring.cloud.nacos.discovery.clusterName-name:}"));
+ "${spring.cloud.nacos.discovery.cluster-name:}"));
}
if (StringUtils.isEmpty(this.getEndpoint())) {
this.setEndpoint(
@@ -379,12 +399,12 @@ public class NacosDiscoveryProperties {
try {
namingService = NacosFactory.createNamingService(properties);
- return namingService;
}
catch (Exception e) {
LOGGER.error("create naming service error!properties={},e=,", this, e);
return null;
}
+ return namingService;
}
}
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClient.java
similarity index 85%
rename from spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java
rename to spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClient.java
index eedc2ffe..1bc25ea5 100644
--- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java
+++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClient.java
@@ -14,13 +14,14 @@
* limitations under the License.
*/
-package org.springframework.cloud.alibaba.nacos;
+package org.springframework.cloud.alibaba.nacos.discovery;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
+import org.springframework.cloud.alibaba.nacos.NacosServiceInstance;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
@@ -30,7 +31,6 @@ import java.util.*;
/**
* @author xiaojing
* @author renhaojun
- * @author pbting
*/
public class NacosDiscoveryClient implements DiscoveryClient {
@@ -38,9 +38,12 @@ public class NacosDiscoveryClient implements DiscoveryClient {
.getLogger(NacosDiscoveryClient.class);
public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client";
- @Autowired
private NacosDiscoveryProperties discoveryProperties;
+ public NacosDiscoveryClient(NacosDiscoveryProperties discoveryProperties) {
+ this.discoveryProperties = discoveryProperties;
+ }
+
@Override
public String description() {
return DESCRIPTION;
@@ -75,19 +78,24 @@ public class NacosDiscoveryClient implements DiscoveryClient {
nacosServiceInstance.setHost(instance.getIp());
nacosServiceInstance.setPort(instance.getPort());
nacosServiceInstance.setServiceId(serviceId);
- Map metadata = new HashMap();
+ 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);
+
+ if (metadata.containsKey("secure")) {
+ boolean secure = Boolean.parseBoolean(metadata.get("secure"));
+ nacosServiceInstance.setSecure(secure);
+ }
return nacosServiceInstance;
}
private static List hostToServiceInstanceList(
List instances, String serviceId) {
- List result = new ArrayList(instances.size());
+ List result = new ArrayList<>(instances.size());
for (Instance instance : instances) {
result.add(hostToServiceInstance(instance, serviceId));
}
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java
similarity index 58%
rename from spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java
rename to spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java
index 05049f4b..5fe818b3 100644
--- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java
+++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java
@@ -14,11 +14,16 @@
* limitations under the License.
*/
-package org.springframework.cloud.alibaba.nacos;
+package org.springframework.cloud.alibaba.nacos.discovery;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.cloud.alibaba.nacos.ConditionalOnNacosDiscoveryEnabled;
+import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
+import org.springframework.cloud.client.CommonsClientAutoConfiguration;
import org.springframework.cloud.client.discovery.DiscoveryClient;
+import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -26,20 +31,21 @@ import org.springframework.context.annotation.Configuration;
* @author xiaojing
*/
@Configuration
-@ConditionalOnMissingBean(DiscoveryClient.class)
@ConditionalOnNacosDiscoveryEnabled
@EnableConfigurationProperties
+@AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class,
+ CommonsClientAutoConfiguration.class })
public class NacosDiscoveryClientAutoConfiguration {
@Bean
- public DiscoveryClient nacosDiscoveryClient() {
- return new NacosDiscoveryClient();
+ public DiscoveryClient nacosDiscoveryClient(
+ NacosDiscoveryProperties discoveryProperties) {
+ return new NacosDiscoveryClient(discoveryProperties);
}
@Bean
@ConditionalOnMissingBean
- public NacosDiscoveryProperties nacosProperties() {
- return new NacosDiscoveryProperties();
+ public NacosWatch nacosWatch(NacosDiscoveryProperties nacosDiscoveryProperties) {
+ return new NacosWatch(nacosDiscoveryProperties);
}
-
}
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosWatch.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosWatch.java
new file mode 100644
index 00000000..05e92fbc
--- /dev/null
+++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/discovery/NacosWatch.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cloud.alibaba.nacos.discovery;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.alibaba.nacos.api.naming.NamingService;
+import com.alibaba.nacos.api.naming.listener.Event;
+import com.alibaba.nacos.api.naming.listener.EventListener;
+import com.alibaba.nacos.api.naming.pojo.ListView;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
+import org.springframework.cloud.client.discovery.event.HeartbeatEvent;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.context.ApplicationEventPublisherAware;
+import org.springframework.context.SmartLifecycle;
+import org.springframework.scheduling.TaskScheduler;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
+
+/**
+ * @author xiaojing
+ */
+public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycle {
+
+ private static final Logger log = LoggerFactory.getLogger(NacosWatch.class);
+
+ private final NacosDiscoveryProperties properties;
+
+ private final TaskScheduler taskScheduler;
+
+ private final AtomicLong nacosWatchIndex = new AtomicLong(0);
+
+ private final AtomicBoolean running = new AtomicBoolean(false);
+
+ private ApplicationEventPublisher publisher;
+
+ private ScheduledFuture> watchFuture;
+
+ private Set cacheServices = new HashSet<>();
+
+ private HashMap subscribeListeners = new HashMap<>();
+
+ public NacosWatch(NacosDiscoveryProperties properties) {
+ this(properties, getTaskScheduler());
+ }
+
+ public NacosWatch(NacosDiscoveryProperties properties, TaskScheduler taskScheduler) {
+ this.properties = properties;
+ this.taskScheduler = taskScheduler;
+ }
+
+ private static ThreadPoolTaskScheduler getTaskScheduler() {
+ ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
+ taskScheduler.initialize();
+ return taskScheduler;
+ }
+
+ @Override
+ public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
+ this.publisher = publisher;
+ }
+
+ @Override
+ public boolean isAutoStartup() {
+ return true;
+ }
+
+ @Override
+ public void stop(Runnable callback) {
+ this.stop();
+ callback.run();
+ }
+
+ @Override
+ public void start() {
+ if (this.running.compareAndSet(false, true)) {
+ this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(new Runnable() {
+ @Override
+ public void run() {
+ NacosWatch.this.nacosServicesWatch();
+ }
+ }, this.properties.getWatchDelay());
+ }
+ }
+
+ @Override
+ public void stop() {
+ if (this.running.compareAndSet(true, false) && this.watchFuture != null) {
+ this.watchFuture.cancel(true);
+ }
+ }
+
+ @Override
+ public boolean isRunning() {
+ return false;
+ }
+
+ @Override
+ public int getPhase() {
+ return 0;
+ }
+
+ public void nacosServicesWatch() {
+ try {
+
+ boolean changed = false;
+ NamingService namingService = properties.namingServiceInstance();
+
+ ListView listView = properties.namingServiceInstance()
+ .getServicesOfServer(1, Integer.MAX_VALUE);
+
+ List serviceList = listView.getData();
+
+ // if there are new services found, publish event
+ Set currentServices = new HashSet<>(serviceList);
+ currentServices.removeAll(cacheServices);
+ if (currentServices.size() > 0) {
+ changed = true;
+ }
+
+ // if some services disappear, publish event
+ if (cacheServices.removeAll(new HashSet<>(serviceList))
+ && cacheServices.size() > 0) {
+ changed = true;
+
+ for (String serviceName : cacheServices) {
+ namingService.unsubscribe(serviceName,
+ subscribeListeners.get(serviceName));
+ subscribeListeners.remove(serviceName);
+ }
+ }
+
+ cacheServices = new HashSet<>(serviceList);
+
+ // subscribe services's node change, publish event if nodes changed
+ for (String serviceName : cacheServices) {
+ if (!subscribeListeners.containsKey(serviceName)) {
+ EventListener eventListener = new EventListener() {
+ @Override
+ public void onEvent(Event event) {
+ NacosWatch.this.publisher.publishEvent(new HeartbeatEvent(
+ NacosWatch.this, nacosWatchIndex.getAndIncrement()));
+ }
+ };
+ subscribeListeners.put(serviceName, eventListener);
+ namingService.subscribe(serviceName, eventListener);
+
+ }
+ }
+
+ if (changed) {
+ this.publisher.publishEvent(
+ new HeartbeatEvent(this, nacosWatchIndex.getAndIncrement()));
+ }
+
+ }
+ catch (Exception e) {
+ log.error("Error watching Nacos Service change", e);
+ }
+ }
+}
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 ef29eae1..be0907c6 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
@@ -26,7 +26,6 @@ import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
@@ -39,11 +38,11 @@ public class NacosDiscoveryEndpoint extends AbstractEndpoint