Merge branch 'master' of github.com:alibaba/spring-cloud-alibaba into rocketmq

pull/2217/head
zkzlx 4 years ago
commit d17a38d495

@ -48,15 +48,16 @@ Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。
更多组件请参考 [Roadmap](https://github.com/alibaba/spring-cloud-alibaba/blob/master/Roadmap-zh.md)。 更多组件请参考 [Roadmap](https://github.com/alibaba/spring-cloud-alibaba/blob/master/Roadmap-zh.md)。
## 如何构建 ## 如何构建
* 2020.0 分支对应的是 Spring Cloud 2020最低支持 JDK 1.8。
* master 分支对应的是 Spring Cloud Greenwich最低支持 JDK 1.8。 * master 分支对应的是 Spring Cloud Hoxton最低支持 JDK 1.8。
* greenwich 分支对应的是 Spring Cloud Greenwich最低支持 JDK 1.8。
* finchley 分支对应的是 Spring Cloud Finchley最低支持 JDK 1.8。 * finchley 分支对应的是 Spring Cloud Finchley最低支持 JDK 1.8。
* 1.x 分支对应的是 Spring Cloud Edgware最低支持 JDK 1.7。 * 1.x 分支对应的是 Spring Cloud Edgware最低支持 JDK 1.7。
Spring Cloud 使用 Maven 来构建,最快的使用方式是将本项目 clone 到本地,然后执行以下命令: Spring Cloud 使用 Maven 来构建,最快的使用方式是将本项目 clone 到本地,然后执行以下命令:
```bash
./mvnw install ./mvnw install
```
执行完毕后,项目将被安装到本地 Maven 仓库。 执行完毕后,项目将被安装到本地 Maven 仓库。
## 如何使用 ## 如何使用
@ -64,7 +65,7 @@ Spring Cloud 使用 Maven 来构建,最快的使用方式是将本项目 clone
### 如何引入依赖 ### 如何引入依赖
如果需要使用已发布的版本,在 `dependencyManagement` 中添加如下配置。 如果需要使用已发布的版本,在 `dependencyManagement` 中添加如下配置。
```xml
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
@ -76,7 +77,7 @@ Spring Cloud 使用 Maven 来构建,最快的使用方式是将本项目 clone
</dependency> </dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
```
然后在 `dependencies` 中添加自己所需使用的依赖即可使用。 然后在 `dependencies` 中添加自己所需使用的依赖即可使用。
## 演示 Demo ## 演示 Demo
@ -111,7 +112,7 @@ Example 列表:
* 2.0.x 版本适用于 Spring Boot 2.0.x * 2.0.x 版本适用于 Spring Boot 2.0.x
* 2.1.x 版本适用于 Spring Boot 2.1.x * 2.1.x 版本适用于 Spring Boot 2.1.x
* 2.2.x 版本适用于 Spring Boot 2.2.x * 2.2.x 版本适用于 Spring Boot 2.2.x
* 2021.x 版本适用于 Spring Boot 2.4.x
## 社区交流 ## 社区交流

@ -51,22 +51,23 @@ For more features, please refer to [Roadmap](https://github.com/alibaba/spring-c
For more features please refer to [Roadmap](https://github.com/alibaba/spring-cloud-alibaba/blob/master/Roadmap.md). For more features please refer to [Roadmap](https://github.com/alibaba/spring-cloud-alibaba/blob/master/Roadmap.md).
## How to build ## How to build
* **2020.0 branch**: Corresponds to Spring Cloud 2020 & Spring Boot 2.4.x. JDK 1.8 or later versions are supported.
* **master branch**: Corresponds to Spring Cloud Greenwich & Spring Boot 2.x. JDK 1.8 or later versions are supported. * **master branch**: Corresponds to Spring Cloud Hoxton & Spring Boot 2.2.x. JDK 1.8 or later versions are supported.
* **finchley branch**: Corresponds to Spring Cloud Finchley & Spring Boot 2.x. JDK 1.8 or later versions are supported. * **greenwich branch**: Corresponds to Spring Cloud Greenwich & Spring Boot 2.1.x. JDK 1.8 or later versions are supported.
* **finchley branch**: Corresponds to Spring Cloud Finchley & Spring Boot 2.0.x. JDK 1.8 or later versions are supported.
* **1.x branch**: Corresponds to Spring Cloud Edgware & Spring Boot 1.x, JDK 1.7 or later versions are supported. * **1.x branch**: Corresponds to Spring Cloud Edgware & Spring Boot 1.x, JDK 1.7 or later versions are supported.
Spring Cloud uses Maven for most build-related activities, and you should be able to get off the ground quite quickly by cloning the project you are interested in and typing: Spring Cloud uses Maven for most build-related activities, and you should be able to get off the ground quite quickly by cloning the project you are interested in and typing:
```bash
./mvnw install ./mvnw install
```
## How to Use ## How to Use
### Add maven dependency ### Add maven dependency
These artifacts are available from Maven Central and Spring Release repository via BOM: These artifacts are available from Maven Central and Spring Release repository via BOM:
```xml
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
@ -78,7 +79,7 @@ These artifacts are available from Maven Central and Spring Release repository v
</dependency> </dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
```
add the module in `dependencies`. add the module in `dependencies`.
@ -118,6 +119,7 @@ As the interfaces and annotations of Spring Boot 1 and Spring Boot 2 have been c
* 2.0.x for Spring Boot 2.0.x * 2.0.x for Spring Boot 2.0.x
* 2.1.x for Spring Boot 2.1.x * 2.1.x for Spring Boot 2.1.x
* 2.2.x for Spring Boot 2.2.x * 2.2.x for Spring Boot 2.2.x
* 2020.x for Spring Boot 2.4.x
## Code of Conduct ## Code of Conduct
This project is a sub-project of Spring Cloud, it adheres to the Contributor Covenant [code of conduct](https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io. This project is a sub-project of Spring Cloud, it adheres to the Contributor Covenant [code of conduct](https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io.

@ -19,7 +19,7 @@
<properties> <properties>
<revision>2.2.6-SNAPSHOT</revision> <revision>2.2.6-SNAPSHOT</revision>
<sentinel.version>1.8.0</sentinel.version> <sentinel.version>1.8.1</sentinel.version>
<seata.version>1.3.0</seata.version> <seata.version>1.3.0</seata.version>
<nacos.client.version>1.4.1</nacos.client.version> <nacos.client.version>1.4.1</nacos.client.version>
<nacos.config.version>0.8.0</nacos.config.version> <nacos.config.version>0.8.0</nacos.config.version>

@ -114,6 +114,8 @@ public class EchoController {
- 启动nacos 注册中心 - 启动nacos 注册中心
- 启动sentinel
- 启动服务提供方: - 启动服务提供方:
1. IDE直接启动找到主类 `ProviderApplication`,执行 main 方法启动应用。 1. IDE直接启动找到主类 `ProviderApplication`,执行 main 方法启动应用。
@ -123,3 +125,5 @@ public class EchoController {
1. IDE直接启动找到主类 `ConsumerApplication`,执行 main 方法启动应用。 1. IDE直接启动找到主类 `ConsumerApplication`,执行 main 方法启动应用。
2. 打包编译后启动:首先执行 `mvn clean package` 将工程编译打包,然后执行 `java -jar sentinel-feign-consumer-example.jar`启动应用。 2. 打包编译后启动:首先执行 `mvn clean package` 将工程编译打包,然后执行 `java -jar sentinel-feign-consumer-example.jar`启动应用。
- 启动之后Sentinel Dashboard可能看不见service-consumer服务的详细信息多请求几次接口即可。

@ -8,6 +8,9 @@ spring:
nacos: nacos:
discovery: discovery:
server-addr: 127.0.0.1:8848 server-addr: 127.0.0.1:8848
sentinel:
transport:
dashboard: 127.0.0.1:8081
feign: feign:
sentinel: sentinel:

@ -25,7 +25,7 @@ import com.alibaba.csp.sentinel.datasource.AbstractDataSource;
import com.alibaba.csp.sentinel.heartbeat.HeartbeatSenderProvider; import com.alibaba.csp.sentinel.heartbeat.HeartbeatSenderProvider;
import com.alibaba.csp.sentinel.transport.HeartbeatSender; import com.alibaba.csp.sentinel.transport.HeartbeatSender;
import com.alibaba.csp.sentinel.transport.config.TransportConfig; import com.alibaba.csp.sentinel.transport.config.TransportConfig;
import com.alibaba.csp.sentinel.util.function.Tuple2; import com.alibaba.csp.sentinel.transport.endpoint.Endpoint;
import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.AbstractHealthIndicator;
@ -84,8 +84,7 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
// Check health of Dashboard // Check health of Dashboard
boolean dashboardUp = true; boolean dashboardUp = true;
List<Tuple2<String, Integer>> consoleServerList = TransportConfig List<Endpoint> consoleServerList = TransportConfig.getConsoleServerList();
.getConsoleServerList();
if (CollectionUtils.isEmpty(consoleServerList)) { if (CollectionUtils.isEmpty(consoleServerList)) {
// If Dashboard isn't configured, it's OK and mark the status of Dashboard // If Dashboard isn't configured, it's OK and mark the status of Dashboard
// with UNKNOWN. // with UNKNOWN.

@ -31,7 +31,8 @@ import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.transport.config.TransportConfig; import com.alibaba.csp.sentinel.transport.config.TransportConfig;
import com.alibaba.csp.sentinel.util.function.Tuple2; import com.alibaba.csp.sentinel.transport.endpoint.Endpoint;
import com.alibaba.csp.sentinel.transport.endpoint.Protocol;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -134,8 +135,10 @@ public class SentinelAutoConfigurationTests {
Map<String, Object> map = sentinelEndpoint.invoke(); Map<String, Object> map = sentinelEndpoint.invoke();
assertThat(map.get("logUsePid")).isEqualTo(Boolean.TRUE); assertThat(map.get("logUsePid")).isEqualTo(Boolean.TRUE);
assertThat(map.get("consoleServer").toString()).isEqualTo( assertThat(map.get("consoleServer").toString())
Arrays.asList(Tuple2.of("localhost", 8080), Tuple2.of("localhost", 8081)) .isEqualTo(Arrays
.asList(new Endpoint(Protocol.HTTP, "localhost", 8080),
new Endpoint(Protocol.HTTP, "localhost", 8081))
.toString()); .toString());
assertThat(map.get("clientPort")).isEqualTo("9999"); assertThat(map.get("clientPort")).isEqualTo("9999");
assertThat(map.get("heartbeatIntervalMs")).isEqualTo(20000L); assertThat(map.get("heartbeatIntervalMs")).isEqualTo(20000L);
@ -185,8 +188,10 @@ public class SentinelAutoConfigurationTests {
@Test @Test
public void testSentinelSystemProperties() { public void testSentinelSystemProperties() {
assertThat(LogBase.isLogNameUsePid()).isEqualTo(true); assertThat(LogBase.isLogNameUsePid()).isEqualTo(true);
assertThat(TransportConfig.getConsoleServerList().toString()).isEqualTo( assertThat(TransportConfig.getConsoleServerList().toString())
Arrays.asList(Tuple2.of("localhost", 8080), Tuple2.of("localhost", 8081)) .isEqualTo(Arrays
.asList(new Endpoint(Protocol.HTTP, "localhost", 8080),
new Endpoint(Protocol.HTTP, "localhost", 8081))
.toString()); .toString());
assertThat(TransportConfig.getPort()).isEqualTo("9999"); assertThat(TransportConfig.getPort()).isEqualTo("9999");
assertThat(TransportConfig.getHeartbeatIntervalMs().longValue()) assertThat(TransportConfig.getHeartbeatIntervalMs().longValue())

@ -51,6 +51,10 @@ public class DubboCloudProperties {
private String registryType = DUBBO_CLOUD_REGISTRY_PROPERTY_VALUE; private String registryType = DUBBO_CLOUD_REGISTRY_PROPERTY_VALUE;
private int maxReSubscribeMetadataTimes = 1000;
private int reSubscribeMetadataIntervial = 5;
public String getSubscribedServices() { public String getSubscribedServices() {
return subscribedServices; return subscribedServices;
} }
@ -91,4 +95,20 @@ public class DubboCloudProperties {
this.registryType = registryType; this.registryType = registryType;
} }
public int getMaxReSubscribeMetadataTimes() {
return maxReSubscribeMetadataTimes;
}
public void setMaxReSubscribeMetadataTimes(int maxReSubscribeMetadataTimes) {
this.maxReSubscribeMetadataTimes = maxReSubscribeMetadataTimes;
}
public int getReSubscribeMetadataIntervial() {
return reSubscribeMetadataIntervial;
}
public void setReSubscribeMetadataIntervial(int reSubscribeMetadataIntervial) {
this.reSubscribeMetadataIntervial = reSubscribeMetadataIntervial;
}
} }

@ -237,9 +237,6 @@ public class DubboServiceMetadataRepository
dispatchEvent(new SubscribedServicesChangedEvent(this, oldSubscribedServices, dispatchEvent(new SubscribedServicesChangedEvent(this, oldSubscribedServices,
newSubscribedServices)); newSubscribedServices));
// clear old one, help GC
oldSubscribedServices.clear();
return newSubscribedServices.stream(); return newSubscribedServices.stream();
} }

@ -23,6 +23,9 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -45,12 +48,10 @@ import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered; import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import static java.lang.String.format; import static java.lang.String.format;
import static java.util.Collections.emptyList; import static java.util.Collections.emptyList;
import static java.util.stream.StreamSupport.stream;
import static org.apache.dubbo.common.URLBuilder.from; import static org.apache.dubbo.common.URLBuilder.from;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY;
@ -110,11 +111,23 @@ public class DubboCloudRegistry extends FailbackRegistry {
private final String currentApplicationName; private final String currentApplicationName;
private final Map<URL, NotifyListener> urlNotifyListenerMap = new ConcurrentHashMap<>();
private final Map<String, ReSubscribeMetadataJob> reConnectJobMap = new ConcurrentHashMap<>();
private final ScheduledThreadPoolExecutor reConnectPool = new ScheduledThreadPoolExecutor(
2);
private final int maxReSubscribeMetadataTimes;
private final int reSubscribeMetadataIntervial;
public DubboCloudRegistry(URL url, DiscoveryClient discoveryClient, public DubboCloudRegistry(URL url, DiscoveryClient discoveryClient,
DubboServiceMetadataRepository repository, DubboServiceMetadataRepository repository,
DubboMetadataServiceProxy dubboMetadataConfigServiceProxy, DubboMetadataServiceProxy dubboMetadataConfigServiceProxy,
JSONUtils jsonUtils, DubboGenericServiceFactory dubboGenericServiceFactory, JSONUtils jsonUtils, DubboGenericServiceFactory dubboGenericServiceFactory,
ConfigurableApplicationContext applicationContext) { ConfigurableApplicationContext applicationContext,
int maxReSubscribeMetadataTimes, int reSubscribeMetadataIntervial) {
super(url); super(url);
this.servicesLookupInterval = url this.servicesLookupInterval = url
@ -127,6 +140,11 @@ public class DubboCloudRegistry extends FailbackRegistry {
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
this.dubboMetadataUtils = getBean(DubboMetadataUtils.class); this.dubboMetadataUtils = getBean(DubboMetadataUtils.class);
this.currentApplicationName = dubboMetadataUtils.getCurrentApplicationName(); this.currentApplicationName = dubboMetadataUtils.getCurrentApplicationName();
this.maxReSubscribeMetadataTimes = maxReSubscribeMetadataTimes;
this.reSubscribeMetadataIntervial = reSubscribeMetadataIntervial;
reConnectPool.setKeepAliveTime(10, TimeUnit.MINUTES);
reConnectPool.allowCoreThreadTimeOut(true);
} }
private <T> T getBean(Class<T> beanClass) { private <T> T getBean(Class<T> beanClass) {
@ -177,6 +195,7 @@ public class DubboCloudRegistry extends FailbackRegistry {
} }
else { // for general Dubbo Services else { // for general Dubbo Services
subscribeURLs(url, listener); subscribeURLs(url, listener);
urlNotifyListenerMap.put(url, listener);
} }
} }
@ -188,19 +207,34 @@ public class DubboCloudRegistry extends FailbackRegistry {
// Async subscription // Async subscription
registerServiceInstancesChangedListener(url, registerServiceInstancesChangedListener(url,
new ApplicationListener<ServiceInstancesChangedEvent>() { new ServiceInstanceChangeListener() {
private final URL url2subscribe = url; @Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override @Override
@Order
public void onApplicationEvent(ServiceInstancesChangedEvent event) { public void onApplicationEvent(ServiceInstancesChangedEvent event) {
Set<String> serviceNames = getServices(url); Set<String> serviceNames = getServices(url);
String serviceName = event.getServiceName(); String serviceName = event.getServiceName();
if (serviceNames.contains(serviceName)) { if (serviceNames.contains(serviceName)) {
subscribeURLs(url, serviceNames, listener); logger.debug(
"handle serviceInstanceChange of general service, serviceName = {}, subscribeUrl={}",
event.getServiceName(), url.getServiceKey());
try {
subscribeURLs(url, serviceNames, listener);
reConnectJobMap.remove(serviceName);
}
catch (Exception e) {
logger.warn(String.format(
"subscribeURLs failed, serviceName = %s, try reSubscribe again",
serviceName), e);
addReSubscribeMetadataJob(serviceName, 0);
}
} }
} }
@ -212,8 +246,19 @@ public class DubboCloudRegistry extends FailbackRegistry {
}); });
} }
private void subscribeURLs(URL url, Set<String> serviceNames, void addReSubscribeMetadataJob(String serviceName, int count) {
NotifyListener listener) { if (count > maxReSubscribeMetadataTimes) {
logger.error(
"reSubscribe failed too many times, serviceName = {}, count = {}",
serviceName, count);
return;
}
ReSubscribeMetadataJob job = new ReSubscribeMetadataJob(serviceName, this, count);
reConnectJobMap.put(serviceName, job);
reConnectPool.schedule(job, reSubscribeMetadataIntervial, TimeUnit.SECONDS);
}
void subscribeURLs(URL url, Set<String> serviceNames, NotifyListener listener) {
List<URL> subscribedURLs = new LinkedList<>(); List<URL> subscribedURLs = new LinkedList<>();
@ -252,6 +297,10 @@ public class DubboCloudRegistry extends FailbackRegistry {
serviceName)); serviceName));
} }
} }
else {
logger.debug("subscribe from serviceName = {}, size = {}", serviceName,
serviceInstances.size());
}
List<URL> exportedURLs = getExportedURLs(subscribedURL, serviceName, List<URL> exportedURLs = getExportedURLs(subscribedURL, serviceName,
serviceInstances); serviceInstances);
@ -308,6 +357,16 @@ public class DubboCloudRegistry extends FailbackRegistry {
String protocol = templateURL.getProtocol(); String protocol = templateURL.getProtocol();
Integer port = repository.getDubboProtocolPort(serviceInstance, Integer port = repository.getDubboProtocolPort(serviceInstance,
protocol); protocol);
// reserve tag
String tag = null;
List<URL> urls = jsonUtils.toURLs(serviceInstance.getMetadata()
.get("dubbo.metadata-service.urls"));
if (urls != null && urls.size() > 0) {
Map<String, String> parameters = urls.get(0).getParameters();
tag = parameters.get("dubbo.tag");
}
if (Objects.equals(templateURL.getHost(), host) if (Objects.equals(templateURL.getHost(), host)
&& Objects.equals(templateURL.getPort(), port)) { // use && Objects.equals(templateURL.getPort(), port)) { // use
// templateURL // templateURL
@ -331,7 +390,8 @@ public class DubboCloudRegistry extends FailbackRegistry {
// the template // the template
// URL // URL
.setHost(host) // reset the host .setHost(host) // reset the host
.setPort(port); // reset the port .setPort(port) // reset the port
.addParameter("dubbo.tag", tag); // reset the tag
return clonedURLBuilder.build(); return clonedURLBuilder.build();
} }
@ -378,7 +438,7 @@ public class DubboCloudRegistry extends FailbackRegistry {
return metadata.containsKey(METADATA_SERVICE_URLS_PROPERTY_NAME); return metadata.containsKey(METADATA_SERVICE_URLS_PROPERTY_NAME);
} }
private Set<String> getServices(URL url) { Set<String> getServices(URL url) {
Set<String> subscribedServices = repository.getSubscribedServices(); Set<String> subscribedServices = repository.getSubscribedServices();
// TODO Add the filter feature // TODO Add the filter feature
return subscribedServices; return subscribedServices;
@ -408,11 +468,6 @@ public class DubboCloudRegistry extends FailbackRegistry {
listener.notify(subscribedURLs); listener.notify(subscribedURLs);
} }
private List<ServiceInstance> getServiceInstances(Iterable<String> serviceNames) {
return stream(serviceNames.spliterator(), false).map(this::getServiceInstances)
.flatMap(Collection::stream).collect(Collectors.toList());
}
private List<ServiceInstance> getServiceInstances(String serviceName) { private List<ServiceInstance> getServiceInstances(String serviceName) {
return hasText(serviceName) ? doGetServiceInstances(serviceName) : emptyList(); return hasText(serviceName) ? doGetServiceInstances(serviceName) : emptyList();
} }
@ -460,27 +515,38 @@ public class DubboCloudRegistry extends FailbackRegistry {
private void subscribeDubboMetadataServiceURLs(URL subscribedURL, private void subscribeDubboMetadataServiceURLs(URL subscribedURL,
NotifyListener listener) { NotifyListener listener) {
// Sync subscription
subscribeDubboMetadataServiceURLs(subscribedURL, listener, subscribeDubboMetadataServiceURLs(subscribedURL, listener,
getServiceName(subscribedURL)); getServiceName(subscribedURL));
// Sync subscription // Sync subscription
if (containsProviderCategory(subscribedURL)) { if (containsProviderCategory(subscribedURL)) {
registerServiceInstancesChangedListener(subscribedURL, registerServiceInstancesChangedListener(subscribedURL,
new ApplicationListener<ServiceInstancesChangedEvent>() { new ServiceInstanceChangeListener() {
private final URL url2subscribe = subscribedURL; @Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE - 1;
}
@Override @Override
@Order(Ordered.LOWEST_PRECEDENCE - 1)
public void onApplicationEvent( public void onApplicationEvent(
ServiceInstancesChangedEvent event) { ServiceInstancesChangedEvent event) {
String sourceServiceName = event.getServiceName(); String sourceServiceName = event.getServiceName();
List<ServiceInstance> serviceInstances = event
.getServiceInstances();
String serviceName = getServiceName(subscribedURL); String serviceName = getServiceName(subscribedURL);
if (Objects.equals(sourceServiceName, serviceName)) { if (Objects.equals(sourceServiceName, serviceName)) {
logger.debug(
"handle serviceInstanceChange of metadata service, serviceName = {}, subscribeUrl={}",
event.getServiceName(),
subscribedURL.getServiceKey());
// only update serviceInstances of the specified
// serviceName
subscribeDubboMetadataServiceURLs(subscribedURL, listener, subscribeDubboMetadataServiceURLs(subscribedURL, listener,
sourceServiceName); sourceServiceName, serviceInstances);
} }
} }
@ -498,34 +564,25 @@ public class DubboCloudRegistry extends FailbackRegistry {
} }
private void subscribeDubboMetadataServiceURLs(URL subscribedURL, private void subscribeDubboMetadataServiceURLs(URL subscribedURL,
NotifyListener listener, String serviceName) { NotifyListener listener, String serviceName,
List<ServiceInstance> serviceInstances) {
String serviceInterface = subscribedURL.getServiceInterface(); String serviceInterface = subscribedURL.getServiceInterface();
String version = subscribedURL.getParameter(VERSION_KEY); String version = subscribedURL.getParameter(VERSION_KEY);
String protocol = subscribedURL.getParameter(PROTOCOL_KEY); String protocol = subscribedURL.getParameter(PROTOCOL_KEY);
List<ServiceInstance> serviceInstances = getServiceInstances(serviceName);
List<URL> urls = dubboMetadataUtils.getDubboMetadataServiceURLs(serviceInstances, List<URL> urls = dubboMetadataUtils.getDubboMetadataServiceURLs(serviceInstances,
serviceInterface, version, protocol); serviceInterface, version, protocol);
notifyAllSubscribedURLs(subscribedURL, urls, listener); notifyAllSubscribedURLs(subscribedURL, urls, listener);
} }
// private void subscribeDubboMetadataServiceURLs(URL subscribedURL, private void subscribeDubboMetadataServiceURLs(URL subscribedURL,
// NotifyListener listener, Set<String> serviceNames) { NotifyListener listener, String serviceName) {
// List<ServiceInstance> serviceInstances = getServiceInstances(serviceName);
// String serviceInterface = subscribedURL.getServiceInterface(); subscribeDubboMetadataServiceURLs(subscribedURL, listener, serviceName,
// String version = subscribedURL.getParameter(VERSION_KEY); serviceInstances);
// String protocol = subscribedURL.getParameter(PROTOCOL_KEY); }
//
// List<ServiceInstance> serviceInstances = getServiceInstances(serviceNames);
//
// List<URL> urls = dubboMetadataUtils.getDubboMetadataServiceURLs(serviceInstances,
// serviceInterface, version, protocol);
//
// notifyAllSubscribedURLs(subscribedURL, urls, listener);
// }
private boolean containsProviderCategory(URL subscribedURL) { private boolean containsProviderCategory(URL subscribedURL) {
String category = subscribedURL.getParameter(CATEGORY_KEY); String category = subscribedURL.getParameter(CATEGORY_KEY);
@ -546,6 +603,14 @@ public class DubboCloudRegistry extends FailbackRegistry {
return ADMIN_PROTOCOL.equals(url.getProtocol()); return ADMIN_PROTOCOL.equals(url.getProtocol());
} }
public Map<URL, NotifyListener> getUrlNotifyListenerMap() {
return urlNotifyListenerMap;
}
public Map<String, ReSubscribeMetadataJob> getReConnectJobMap() {
return reConnectJobMap;
}
protected boolean isDubboMetadataServiceURL(URL url) { protected boolean isDubboMetadataServiceURL(URL url) {
return DUBBO_METADATA_SERVICE_CLASS_NAME.equals(url.getServiceInterface()); return DUBBO_METADATA_SERVICE_CLASS_NAME.equals(url.getServiceInterface());
} }

@ -0,0 +1,84 @@
/*
* Copyright 2013-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
*
* https://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 com.alibaba.cloud.dubbo.registry;
import java.util.Map;
import java.util.Set;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.NotifyListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* For re subscribe URL from provider.
*
* @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
*/
public class ReSubscribeMetadataJob implements Runnable {
protected final Logger logger = LoggerFactory.getLogger(ReSubscribeMetadataJob.class);
private final String serviceName;
private final DubboCloudRegistry dubboCloudRegistry;
private final int errorCounts;
public ReSubscribeMetadataJob(String serviceName,
DubboCloudRegistry dubboCloudRegistry, int errorCounts) {
this.errorCounts = errorCounts;
this.serviceName = serviceName;
this.dubboCloudRegistry = dubboCloudRegistry;
}
public ReSubscribeMetadataJob(String serviceName,
DubboCloudRegistry dubboCloudRegistry) {
this(serviceName, dubboCloudRegistry, 0);
}
@Override
public void run() {
if (dubboCloudRegistry.getReConnectJobMap().get(serviceName) != this) {
return;
}
try {
logger.info("reSubscribe, serviceName = {}, count = {}", serviceName,
errorCounts);
for (Map.Entry<URL, NotifyListener> entry : dubboCloudRegistry
.getUrlNotifyListenerMap().entrySet()) {
doRun(entry.getKey(), entry.getValue());
}
dubboCloudRegistry.getReConnectJobMap().remove(serviceName);
}
catch (Exception e) {
logger.warn(String.format(
"reSubscribe failed, serviceName = %s, try refresh again",
serviceName), e);
dubboCloudRegistry.addReSubscribeMetadataJob(serviceName, errorCounts + 1);
}
}
private void doRun(URL url, NotifyListener listener) {
Set<String> serviceNames = dubboCloudRegistry.getServices(url);
if (serviceNames.contains(serviceName)) {
dubboCloudRegistry.subscribeURLs(url, serviceNames, listener);
}
}
}

@ -0,0 +1,35 @@
/*
* Copyright 2013-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
*
* https://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 com.alibaba.cloud.dubbo.registry;
import com.alibaba.cloud.dubbo.registry.event.ServiceInstancesChangedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
/**
* The interface of ServiceInstanceChange event Listener.
*
* @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
* @see ServiceInstancesChangedEvent
* @see Ordered
* @see ApplicationListener
*/
public interface ServiceInstanceChangeListener
extends ApplicationListener<ServiceInstancesChangedEvent>, Ordered {
}

@ -100,7 +100,9 @@ public class SpringCloudRegistryFactory extends AbstractRegistryFactory {
default: default:
registry = new DubboCloudRegistry(url, discoveryClient, registry = new DubboCloudRegistry(url, discoveryClient,
dubboServiceMetadataRepository, dubboMetadataConfigServiceProxy, dubboServiceMetadataRepository, dubboMetadataConfigServiceProxy,
jsonUtils, dubboGenericServiceFactory, applicationContext); jsonUtils, dubboGenericServiceFactory, applicationContext,
dubboCloudProperties.getMaxReSubscribeMetadataTimes(),
dubboCloudProperties.getReSubscribeMetadataIntervial());
break; break;
} }

Loading…
Cancel
Save