You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dubbo.apache.org by li...@apache.org on 2020/08/31 06:38:47 UTC
[dubbo] branch master updated: Backport service discovery related
changes on 3.0 to master (#6618)
This is an automated email from the ASF dual-hosted git repository.
liujun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/dubbo.git
The following commit(s) were added to refs/heads/master by this push:
new 13868b9 Backport service discovery related changes on 3.0 to master (#6618)
13868b9 is described below
commit 13868b920d647d032d4c6bb70ddac069934fa47e
Author: ken.lj <ke...@gmail.com>
AuthorDate: Mon Aug 31 14:38:25 2020 +0800
Backport service discovery related changes on 3.0 to master (#6618)
---
.../apache/dubbo/rpc/cluster/ClusterInvoker.java | 2 +
.../org/apache/dubbo/rpc/cluster/Directory.java | 2 +
.../rpc/cluster/directory/AbstractDirectory.java | 16 +-
.../cluster/support/AbstractClusterInvoker.java | 5 +
.../support/wrapper/MockClusterInvoker.java | 5 +
.../rpc/cluster/directory/MockDirInvocation.java | 5 +
.../router/condition/ConditionRouterTest.java | 2 +-
.../support/AbstractClusterInvokerTest.java | 17 +-
.../support/wrapper/MockClusterInvokerTest.java | 42 +-
.../wrapper/MockProviderRpcExceptionTest.java | 8 +-
.../org/apache/dubbo/common/ConfigurationURL.java} | 7 +-
.../src/main/java/org/apache/dubbo/common/URL.java | 412 ++++-
.../dubbo/common/config/ConfigurationUtils.java | 6 +-
.../dubbo/common/constants/CommonConstants.java | 6 +
.../dubbo/common/constants/RegistryConstants.java | 10 +
.../manager/DefaultExecutorRepository.java | 8 +-
.../dubbo/config/AbstractInterfaceConfig.java | 2 +
.../org/apache/dubbo/config/ApplicationConfig.java | 22 +-
.../apache/dubbo/config/MetadataReportConfig.java | 13 +
.../org/apache/dubbo/config/RegistryConfig.java | 5 +
.../apache/dubbo/config/context/ConfigManager.java | 8 +
.../org/apache/dubbo/rpc/model/ConsumerModel.java | 6 +
.../java/com/alibaba/dubbo/rpc/Invocation.java | 5 +
.../java/com/alibaba/dubbo/rpc/RpcInvocation.java | 5 +
.../java/org/apache/dubbo/cache/CacheTest.java | 5 +
.../org/apache/dubbo/filter/LegacyInvocation.java | 5 +
.../org/apache/dubbo/service/MockInvocation.java | 5 +
.../org/apache/dubbo/config/ReferenceConfig.java | 23 +-
.../org/apache/dubbo/config/ServiceConfig.java | 24 +-
.../dubbo/config/bootstrap/DubboBootstrap.java | 128 +-
.../bootstrap/builders/ApplicationBuilder.java | 7 +
.../event/listener/ServiceNameMappingListener.java | 49 -
.../metadata/AbstractMetadataServiceExporter.java | 150 --
.../ConfigurableMetadataServiceExporter.java | 122 +-
.../metadata/RemoteMetadataServiceExporter.java | 79 -
.../dubbo/config/utils/ConfigValidationUtils.java | 30 +-
.../dubbo/config/AbstractInterfaceConfigTest.java | 3 +
.../dubbo/config/bootstrap/DubboBootstrapTest.java | 4 +-
.../bootstrap/builders/ApplicationBuilderTest.java | 10 +-
.../org/apache/dubbo/config/cache/CacheTest.java | 2 +-
.../PublishingServiceDefinitionListenerTest.java | 24 +-
.../RemoteMetadataServiceExporterTest.java | 106 --
.../dubbo/config/mock/MockServiceDiscovery.java | 69 +
.../metadata/MetadataServiceExporterTest.java | 32 +-
...g.apache.dubbo.registry.client.ServiceDiscovery | 1 +
.../src/main/resources/META-INF/compat/dubbo.xsd | 5 +
.../src/main/resources/META-INF/dubbo.xsd | 5 +
.../spring/registry/MockServiceDiscovery.java | 69 +
...g.apache.dubbo.registry.client.ServiceDiscovery | 1 +
.../support/etcd/EtcdDynamicConfigurationTest.java | 2 +-
.../apache/dubbo/demo/consumer/Application.java | 26 +-
.../src/main/resources/spring/dubbo-consumer.xml | 13 +-
.../dubbo/demo/provider/GreetingServiceImpl.java | 10 +-
.../src/main/resources/spring/dubbo-provider.xml | 16 +-
dubbo-dependencies-bom/pom.xml | 29 +-
.../metadata/CompositeServiceNameMapping.java | 96 --
.../metadata/DefaultMetadataParamsFilter.java | 55 +
.../DynamicConfigurationServiceNameMapping.java | 60 +-
.../dubbo/metadata/MappingChangedEvent.java} | 29 +-
.../org/apache/dubbo/metadata/MappingListener.java | 8 +-
.../dubbo/metadata/MetadataChangeListener.java} | 28 +-
.../apache/dubbo/metadata/MetadataConstants.java | 29 +-
.../org/apache/dubbo/metadata/MetadataInfo.java | 449 ++++++
.../dubbo/metadata/MetadataParamsFilter.java} | 28 +-
.../org/apache/dubbo/metadata/MetadataService.java | 47 +
.../metadata/PropertiesFileServiceNameMapping.java | 148 --
.../dubbo/metadata/ReadOnlyServiceNameMapping.java | 45 -
.../apache/dubbo/metadata/RevisionResolver.java | 59 +
.../apache/dubbo/metadata/ServiceNameMapping.java | 62 +-
.../apache/dubbo/metadata/URLRevisionResolver.java | 152 --
.../dubbo/metadata/WritableMetadataService.java | 27 +-
.../dubbo/metadata/report/MetadataReport.java | 143 +-
.../metadata/report/MetadataReportInstance.java | 36 +-
.../report/support/AbstractMetadataReport.java | 133 +-
.../support/ConfigCenterBasedMetadataReport.java | 162 --
.../ConfigCenterBasedMetadataReportFactory.java | 90 --
.../file/FileSystemMetadataReportFactory.java | 33 -
.../store/RemoteWritableMetadataService.java | 122 --
.../org.apache.dubbo.metadata.MetadataParamsFilter | 1 +
.../org.apache.dubbo.metadata.ServiceNameMapping | 10 +-
...g.apache.dubbo.metadata.WritableMetadataService | 2 -
...che.dubbo.metadata.report.MetadataReportFactory | 1 -
.../metadata/CompositeServiceNameMappingTest.java | 107 --
...MetadataConstantsTest.java => DemoService.java} | 28 +-
...DynamicConfigurationServiceNameMappingTest.java | 109 --
.../InMemoryWritableMetadataServiceTest.java | 157 --
...adataServiceTest.java => MetadataInfoTest.java} | 22 +-
.../ParameterizedServiceNameMappingTest.java | 67 -
.../PropertiesFileServiceNameMappingTest.java | 60 -
.../dubbo/metadata/ServiceNameMappingTest.java | 8 +-
.../dubbo/metadata/URLRevisionResolverTest.java | 50 -
.../support/AbstractMetadataReportFactoryTest.java | 270 ++--
.../report/support/AbstractMetadataReportTest.java | 58 +-
.../ConfigCenterBasedMetadataReportTest.java | 155 --
.../store/InMemoryWritableMetadataServiceTest.java | 111 --
.../store/RemoteWritableMetadataServiceTest.java | 188 ---
.../store/consul/ConsulMetadataReport.java | 4 -
.../store/consul/ConsulMetadataReportFactory.java | 13 +-
.../store/etcd/EtcdMetadataReportTest.java | 2 +-
.../metadata/store/nacos/NacosMetadataReport.java | 131 +-
.../store/nacos/NacosMetadataReportFactory.java | 13 +-
.../store/zookeeper/ZookeeperMetadataReport.java | 71 +-
.../zookeeper/ZookeeperMetadataReportFactory.java | 22 +-
.../dubbo/monitor/support/MonitorFilterTest.java | 8 +-
.../dubbo/monitor/dubbo/MetricsFilterTest.java | 20 +-
.../dubbo/qos/command/impl/PublishMetadata.java | 63 +
.../org.apache.dubbo.qos.command.BaseCommand | 1 +
.../dubbo/qos/command/util/CommandHelperTest.java | 4 +-
.../org/apache/dubbo/registry/NotifyListener.java | 4 +
.../registry/client/AbstractServiceDiscovery.java} | 21 +-
.../client/DefaultRegistryClusterIdentifier.java} | 18 +-
.../registry/client/DefaultServiceInstance.java | 72 +-
.../client/EventPublishingServiceDiscovery.java | 10 +
.../client/FileSystemServiceDiscovery.java | 13 +
.../dubbo/registry/client/InstanceAddressURL.java | 376 +++++
.../registry/client/RegistryClusterIdentifier.java | 35 +-
.../{integration => client}/RegistryProtocol.java | 1650 ++++++++++----------
.../dubbo/registry/client/ServiceDiscovery.java | 11 +-
.../registry/client/ServiceDiscoveryRegistry.java | 718 ++-------
.../client/ServiceDiscoveryRegistryDirectory.java | 291 ++++
.../client/ServiceDiscoveryRegistryProtocol.java | 47 -
.../ServiceDiscoveryRegistryProtocolListener.java} | 23 +-
.../dubbo/registry/client/ServiceInstance.java | 8 +
.../registry/client/ServiceInstanceCustomizer.java | 3 -
.../client/ServiceInstanceMetadataCustomizer.java | 73 -
.../client/event/ServiceInstancesChangedEvent.java | 12 +-
.../CustomizableServiceInstanceListener.java | 44 -
.../listener/ServiceInstancesChangedListener.java | 183 ++-
...ExportedServicesRevisionMetadataCustomizer.java | 57 -
.../metadata/MetadataServiceNameMapping.java | 89 ++
...MetadataServiceURLParamsMetadataCustomizer.java | 39 +-
.../registry/client/metadata/MetadataUtils.java | 102 ++
.../metadata/ProtocolPortsMetadataCustomizer.java | 7 +-
.../ServiceInstanceMetadataCustomizer.java | 88 ++
.../metadata/ServiceInstanceMetadataUtils.java | 67 +-
.../StandardMetadataServiceURLBuilder.java | 87 +-
...bscribedServicesRevisionMetadataCustomizer.java | 58 -
.../proxy/BaseMetadataServiceProxyFactory.java | 58 -
.../CompositeMetadataServiceProxyFactory.java | 133 --
.../proxy/DefaultMetadataServiceProxyFactory.java | 85 -
.../proxy/MetadataServiceProxyFactory.java | 56 -
.../metadata/proxy/RemoteMetadataServiceProxy.java | 111 --
.../proxy/RemoteMetadataServiceProxyFactory.java | 34 -
.../store/InMemoryWritableMetadataService.java | 134 +-
.../metadata/store/RemoteMetadataServiceImpl.java | 139 ++
.../registry/integration/DynamicDirectory.java | 250 +++
.../InterfaceCompatibleRegistryProtocol.java | 181 +++
.../registry/integration/RegistryDirectory.java | 150 +-
.../integration/RegistryInvokerWrapper.java | 79 -
.../integration/RegistryProtocolListener.java | 1 +
.../registry/support/AbstractRegistryFactory.java | 12 +
.../internal/org.apache.dubbo.event.EventListener | 5 +-
.../org.apache.dubbo.metadata.ServiceNameMapping | 1 +
...g.apache.dubbo.metadata.WritableMetadataService | 1 +
...dubbo.registry.client.RegistryClusterIdentifier | 1 +
...dubbo.registry.client.ServiceInstanceCustomizer | 1 +
...ient.metadata.proxy.MetadataServiceProxyFactory | 3 -
...o.registry.integration.RegistryProtocolListener | 1 +
.../dubbo/internal/org.apache.dubbo.rpc.Protocol | 4 +-
.../registry/client/InMemoryServiceDiscovery.java | 17 +-
.../CustomizableServiceInstanceListenerTest.java | 39 -
.../event/listener/LoggingEventListenerTest.java | 5 +-
.../ServiceInstancesChangedListenerTest.java | 27 -
.../proxy/BaseMetadataServiceProxyFactoryTest.java | 78 -
.../CompositeMetadataServiceProxyFactoryTest.java | 96 --
.../proxy/MetadataServiceProxyFactoryTest.java | 49 -
.../support/ServiceOrientedRegistryTest.java | 5 +
.../registry/consul/ConsulServiceDiscovery.java | 54 +-
.../consul/ConsulServiceDiscoveryFactory.java | 19 +-
...g.apache.dubbo.registry.client.ServiceDiscovery | 1 -
...e.dubbo.registry.client.ServiceDiscoveryFactory | 1 +
.../registry/dubbo/RegistryDirectoryTest.java | 31 +-
.../dubbo/registry/dubbo/RegistryProtocolTest.java | 6 +-
.../registry/dubbo/RegistryStatusCheckerTest.java | 6 +-
.../dubbo/registry/etcd/EtcdServiceDiscovery.java | 8 +-
.../registry/eureka/EurekaServiceDiscovery.java | 9 +-
.../multicast/MulticastServiceDiscovery.java | 72 +
.../MulticastServiceDiscoveryFactory.java | 19 +-
...g.apache.dubbo.registry.client.ServiceDiscovery | 1 +
...e.dubbo.registry.client.ServiceDiscoveryFactory | 1 +
.../registry/multicast/MulticastRegistryTest.java | 20 +-
.../registry/nacos/NacosServiceDiscovery.java | 36 +-
.../nacos/NacosServiceDiscoveryFactory.java | 18 +-
...e.dubbo.registry.client.ServiceDiscoveryFactory | 1 +
.../dubbo/registry/sofa/SofaRegistryInstance.java | 90 ++
.../sofa/SofaRegistryServiceDiscovery.java | 257 +++
.../sofa/SofaRegistryServiceDiscoveryFactory.java | 19 +-
...g.apache.dubbo.registry.client.ServiceDiscovery | 1 +
.../zookeeper/ZookeeperServiceDiscovery.java | 45 +-
.../ZookeeperServiceDiscoveryChangeWatcher.java | 8 +-
.../ZookeeperServiceDiscoveryFactory.java | 18 +-
dubbo-registry/pom.xml | 3 +-
.../apache/dubbo/remoting/exchange/Exchangers.java | 2 +-
.../dubbo/remoting/transport/AbstractEndpoint.java | 2 +-
.../remoting/etcd/jetcd/JEtcdClientWrapper.java | 4 +-
.../dubbo/remoting/etcd/jetcd/LeaseTest.java | 4 +-
.../remoting/transport/grizzly/GrizzlyServer.java | 12 +-
.../transport/grizzly/GrizzlyTransporterTest.java | 2 +-
.../support/header/HeartbeatHandlerTest.java | 45 +-
.../transport/netty/ClientReconnectTest.java | 5 +-
.../remoting/transport/netty/ThreadNameTest.java | 4 +-
.../transport/netty4/NettyTransporterTest.java | 4 +-
.../transport/netty4/ReplierDispatcherTest.java | 13 +-
.../support/MulticastExchangeNetworkerTest.java | 12 +-
.../remoting/p2p/support/FileNetworkerTest.java | 4 +-
.../p2p/support/MulticastNetworkerTest.java | 5 +-
.../main/java/org/apache/dubbo/rpc/Invocation.java | 2 +
.../main/java/org/apache/dubbo/rpc/RpcContext.java | 61 +
.../java/org/apache/dubbo/rpc/RpcInvocation.java | 32 +-
.../org/apache/dubbo/rpc/filter/GenericFilter.java | 2 +-
.../apache/dubbo/rpc/protocol/AbstractInvoker.java | 2 +-
.../dubbo/rpc/proxy/AbstractProxyInvoker.java | 2 +-
.../dubbo/rpc/proxy/InvokerInvocationHandler.java | 15 +-
.../dubbo/rpc/filter/ExceptionFilterTest.java | 8 +-
.../apache/dubbo/rpc/filter/GenericFilterTest.java | 8 +-
.../dubbo/rpc/filter/GenericImplFilterTest.java | 8 +-
.../apache/dubbo/rpc/proxy/AbstractProxyTest.java | 4 +-
.../apache/dubbo/rpc/support/MockInvocation.java | 5 +
.../org/apache/dubbo/rpc/support/RpcUtilsTest.java | 48 +-
.../rpc/protocol/dubbo/CallbackServiceCodec.java | 10 +-
.../dubbo/rpc/protocol/dubbo/DubboProtocol.java | 2 +-
.../dubbo/ReferenceCountExchangeClient.java | 9 +-
.../dubbo/rpc/protocol/rest/RestProtocolTest.java | 2 +-
.../dubbo/rpc/protocol/thrift/ThriftProtocol.java | 2 +-
pom.xml | 2 +
225 files changed, 6298 insertions(+), 6220 deletions(-)
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ClusterInvoker.java
index 4b9199e..a89bdf4 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ClusterInvoker.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ClusterInvoker.java
@@ -35,4 +35,6 @@ public interface ClusterInvoker<T> extends Invoker<T> {
URL getRegistryUrl();
Directory<T> getDirectory();
+
+ boolean isDestroyed();
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Directory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Directory.java
index 2940bf6..5d48264 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Directory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Directory.java
@@ -51,4 +51,6 @@ public interface Directory<T> extends Node {
URL getConsumerUrl();
+ boolean isDestroyed();
+
}
\ No newline at end of file
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java
index 7984d7d..c663552 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java
@@ -29,8 +29,13 @@ import org.apache.dubbo.rpc.cluster.RouterChain;
import java.util.Collections;
import java.util.List;
+import java.util.Map;
+import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
+import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
/**
@@ -48,6 +53,9 @@ public abstract class AbstractDirectory<T> implements Directory<T> {
private volatile URL consumerUrl;
+ protected final Map<String, String> queryMap; // Initialization at construction time, assertion not null
+ protected final String consumedProtocol;
+
protected RouterChain<T> routerChain;
public AbstractDirectory(URL url) {
@@ -59,8 +67,13 @@ public abstract class AbstractDirectory<T> implements Directory<T> {
throw new IllegalArgumentException("url == null");
}
+ queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY));
+ String path = queryMap.get(PATH_KEY);
+ this.consumedProtocol = this.queryMap.get(PROTOCOL_KEY) == null ? DUBBO : this.queryMap.get(PROTOCOL_KEY);
this.url = url.removeParameter(REFER_KEY).removeParameter(MONITOR_KEY);
- this.consumerUrl = this.url.addParameters(StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY)));
+
+ this.consumerUrl = this.url.setProtocol(consumedProtocol).setPath(path == null ? queryMap.get(INTERFACE_KEY) : path).addParameters(queryMap)
+ .removeParameter(MONITOR_KEY);
setRouterChain(routerChain);
}
@@ -100,6 +113,7 @@ public abstract class AbstractDirectory<T> implements Directory<T> {
this.consumerUrl = consumerUrl;
}
+ @Override
public boolean isDestroyed() {
return destroyed;
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java
index b1e8a95..4464763 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java
@@ -113,6 +113,11 @@ public abstract class AbstractClusterInvoker<T> implements ClusterInvoker<T> {
}
}
+ @Override
+ public boolean isDestroyed() {
+ return destroyed.get();
+ }
+
/**
* Select a invoker using loadbalance policy.</br>
* a) Firstly, select an invoker using loadbalance. If this invoker is in previously selected list, or,
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java
index 90c43bd..a682297 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java
@@ -64,6 +64,11 @@ public class MockClusterInvoker<T> implements ClusterInvoker<T> {
}
@Override
+ public boolean isDestroyed() {
+ return directory.isDestroyed();
+ }
+
+ @Override
public boolean isAvailable() {
return directory.isAvailable();
}
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java
index 7a4ffb9..bc237b9 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java
@@ -52,6 +52,11 @@ public class MockDirInvocation implements Invocation {
return null;
}
+ @Override
+ public String getProtocolServiceKey() {
+ return null;
+ }
+
public String getMethodName() {
return "echo";
}
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java
index 00fdf53..204ce9a 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java
@@ -137,7 +137,7 @@ public class ConditionRouterTest {
@Test
public void testRoute_methodRoute() {
- Invocation invocation = new RpcInvocation("getFoo", "com.foo.BarService", new Class<?>[0], new Object[0]);
+ Invocation invocation = new RpcInvocation("getFoo", "com.foo.BarService", "", new Class<?>[0], new Object[0]);
// More than one methods, mismatch
Router router = new ConditionRouterFactory().getRouter(getRouteUrl("methods=getFoo => host = 1.2.3.4"));
boolean matchWhen = ((ConditionRouter) router).matchWhen(
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java
index a6ec35b..33e863b 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java
@@ -19,7 +19,6 @@ package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.NetUtils;
-import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
@@ -47,10 +46,8 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
-import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_AVAILABLE_CHECK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK;
-import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -66,6 +63,7 @@ public class AbstractClusterInvokerTest {
StaticDirectory<IHelloService> dic;
RpcInvocation invocation = new RpcInvocation();
URL url = URL.valueOf("registry://localhost:9090/org.apache.dubbo.rpc.cluster.support.AbstractClusterInvokerTest.IHelloService?refer=" + URL.encode("application=abstractClusterInvokerTest"));
+ URL consumerUrl = URL.valueOf("dubbo://localhost:9090?application=abstractClusterInvokerTest");
Invoker<IHelloService> invoker1;
Invoker<IHelloService> invoker2;
@@ -123,7 +121,8 @@ public class AbstractClusterInvokerTest {
given(mockedInvoker1.getUrl()).willReturn(turl.setPort(999).setProtocol("mock"));
invokers.add(invoker1);
- dic = new StaticDirectory<IHelloService>(url, invokers, null);
+ dic = new StaticDirectory<>(url, invokers, null);
+ dic.setConsumerUrl(consumerUrl);
cluster = new AbstractClusterInvoker(dic) {
@Override
protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance)
@@ -226,9 +225,7 @@ public class AbstractClusterInvokerTest {
@Test
public void testCloseAvailablecheck() {
LoadBalance lb = mock(LoadBalance.class);
- Map<String, String> queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY));
- URL tmpUrl = url.addParameters(queryMap).removeParameter(REFER_KEY).removeParameter(MONITOR_KEY);
- given(lb.select(invokers, tmpUrl, invocation)).willReturn(invoker1);
+ given(lb.select(invokers, consumerUrl, invocation)).willReturn(invoker1);
initlistsize5();
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
@@ -494,21 +491,21 @@ public class AbstractClusterInvokerTest {
Directory<DemoService> directory = new StaticDirectory<DemoService>(invokers);
FailoverClusterInvoker<DemoService> failoverClusterInvoker = new FailoverClusterInvoker<DemoService>(directory);
try {
- failoverClusterInvoker.invoke(new RpcInvocation("sayHello", DemoService.class.getName(), new Class<?>[0], new Object[0]));
+ failoverClusterInvoker.invoke(new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class<?>[0], new Object[0]));
Assertions.fail();
} catch (RpcException e) {
Assertions.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode());
}
ForkingClusterInvoker<DemoService> forkingClusterInvoker = new ForkingClusterInvoker<DemoService>(directory);
try {
- forkingClusterInvoker.invoke(new RpcInvocation("sayHello", DemoService.class.getName(), new Class<?>[0], new Object[0]));
+ forkingClusterInvoker.invoke(new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class<?>[0], new Object[0]));
Assertions.fail();
} catch (RpcException e) {
Assertions.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode());
}
FailfastClusterInvoker<DemoService> failfastClusterInvoker = new FailfastClusterInvoker<DemoService>(directory);
try {
- failfastClusterInvoker.invoke(new RpcInvocation("sayHello", DemoService.class.getName(), new Class<?>[0], new Object[0]));
+ failfastClusterInvoker.invoke(new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class<?>[0], new Object[0]));
Assertions.fail();
} catch (RpcException e) {
Assertions.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode());
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java
index feff78e..df1240c 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java
@@ -38,7 +38,9 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
+import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
public class MockClusterInvokerTest {
@@ -55,7 +57,8 @@ public class MockClusterInvokerTest {
@Test
public void testMockInvokerInvoke_normal() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName());
- url = url.addParameter(MOCK_KEY, "fail");
+ url = url.addParameter(MOCK_KEY, "fail")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()));
Invoker<IHelloService> cluster = getClusterInvoker(url);
URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName()
+ "?getSomething.mock=return aa");
@@ -84,6 +87,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerInvoke_failmock() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(MOCK_KEY, "fail:return null")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName()
+ "?getSomething.mock=return aa").addParameters(url.getParameters());
@@ -118,7 +122,8 @@ public class MockClusterInvokerTest {
@Test
public void testMockInvokerInvoke_forcemock() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName());
- url = url.addParameter(MOCK_KEY, "force:return null");
+ url = url.addParameter(MOCK_KEY, "force:return null")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()));
URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName()
+ "?getSomething.mock=return aa&getSomething3xx.mock=return xx")
@@ -150,7 +155,9 @@ public class MockClusterInvokerTest {
@Test
public void testMockInvokerInvoke_forcemock_defaultreturn() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName());
- url = url.addParameter(MOCK_KEY, "force");
+ url = url.addParameter(MOCK_KEY, "force")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()));
+
Invoker<IHelloService> cluster = getClusterInvoker(url);
URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName()
+ "?getSomething.mock=return aa&getSomething3xx.mock=return xx&sayHello.mock=return ")
@@ -173,7 +180,8 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_Fock_someMethods() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getSomething.mock", "fail:return x")
- .addParameter("getSomething2.mock", "force:return y");
+ .addParameter("getSomething2.mock", "force:return y")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()));
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
RpcInvocation invocation = new RpcInvocation();
@@ -208,6 +216,7 @@ public class MockClusterInvokerTest {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getSomething.mock", "fail:return x")
.addParameter("getSomething2.mock", "force:return y")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -242,6 +251,7 @@ public class MockClusterInvokerTest {
.addParameter("mock", "fail:return null")
.addParameter("getSomething.mock", "fail:return x")
.addParameter("getSomething2.mock", "force:return y")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -278,6 +288,7 @@ public class MockClusterInvokerTest {
.addParameter("mock", "fail:return z")
.addParameter("getSomething.mock", "fail:return x")
.addParameter("getSomething2.mock", "force:return y")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -314,6 +325,7 @@ public class MockClusterInvokerTest {
.addParameter("mock", "force:return z")
.addParameter("getSomething.mock", "fail:return x")
.addParameter("getSomething2.mock", "force:return y")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -348,6 +360,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_Fock_Default() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("mock", "fail:return x")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -376,6 +389,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_checkCompatible_return() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getSomething.mock", "return x")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -402,6 +416,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("mock", "true")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -418,6 +433,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock2() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("mock", "fail")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -433,6 +449,7 @@ public class MockClusterInvokerTest {
@Test
public void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock3() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("mock", "force");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -446,6 +463,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_check_String() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getSomething.mock", "force:return 1688")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -459,6 +477,7 @@ public class MockClusterInvokerTest {
@Test
public void testMockInvokerFromOverride_Invoke_check_int() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("getInt1.mock", "force:return 1688")
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
@@ -473,6 +492,7 @@ public class MockClusterInvokerTest {
@Test
public void testMockInvokerFromOverride_Invoke_check_boolean() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("getBoolean1.mock", "force:return true")
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
@@ -487,6 +507,7 @@ public class MockClusterInvokerTest {
@Test
public void testMockInvokerFromOverride_Invoke_check_Boolean() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("getBoolean2.mock", "force:return true")
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
@@ -502,6 +523,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_check_ListString_empty() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getListString.mock", "force:return empty")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -516,6 +538,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_check_ListString() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getListString.mock", "force:return [\"hi\",\"hi2\"]")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -532,6 +555,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_check_ListPojo_empty() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getUsers.mock", "force:return empty")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -546,6 +570,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_check_ListPojo() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getUsers.mock", "force:return [{id:1, name:\"hi1\"}, {id:2, name:\"hi2\"}]")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -562,6 +587,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_check_ListPojo_error() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getUsers.mock", "force:return [{id:x, name:\"hi1\"}]")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -577,6 +603,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_force_throw() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getBoolean2.mock", "force:throw ")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -594,6 +621,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_force_throwCustemException() throws Throwable {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getBoolean2.mock", "force:throw org.apache.dubbo.rpc.cluster.support.wrapper.MyMockException")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -611,6 +639,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_force_throwCustemExceptionNotFound() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getBoolean2.mock", "force:throw java.lang.RuntimeException2")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -628,6 +657,7 @@ public class MockClusterInvokerTest {
public void testMockInvokerFromOverride_Invoke_mock_false() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("mock", "false")
+ .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
@@ -708,7 +738,7 @@ public class MockClusterInvokerTest {
return "something3";
}
- public String getSomething4(){
+ public String getSomething4() {
throw new RpcException("getSomething4|RpcException");
}
@@ -754,7 +784,7 @@ public class MockClusterInvokerTest {
return "something3mock";
}
- public String getSomething4(){
+ public String getSomething4() {
return "something4mock";
}
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java
index 39459fb..6a46312 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java
@@ -37,6 +37,7 @@ import java.util.Arrays;
import java.util.List;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
+import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
public class MockProviderRpcExceptionTest {
@@ -53,7 +54,8 @@ public class MockProviderRpcExceptionTest {
@Test
public void testMockInvokerProviderRpcException() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloRpcService.class.getName());
- url = url.addParameter(MOCK_KEY, "true").addParameter("invoke_return_error", "true");
+ url = url.addParameter(MOCK_KEY, "true").addParameter("invoke_return_error", "true")
+ .addParameter(REFER_KEY, "path%3dorg.apache.dubbo.rpc.cluster.support.wrapper.MockProviderRpcExceptionTest%24IHelloRpcService");
Invoker<IHelloRpcService> cluster = getClusterInvoker(url);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething4");
@@ -130,7 +132,7 @@ public class MockProviderRpcExceptionTest {
return "something3";
}
- public String getSomething4(){
+ public String getSomething4() {
throw new RpcException("getSomething4|RpcException");
}
@@ -176,7 +178,7 @@ public class MockProviderRpcExceptionTest {
return "something3mock";
}
- public String getSomething4(){
+ public String getSomething4() {
return "something4mock";
}
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/AbstractPrefixConfigurationTest.java b/dubbo-common/src/main/java/org/apache/dubbo/common/ConfigurationURL.java
similarity index 89%
copy from dubbo-common/src/test/java/org/apache/dubbo/common/config/AbstractPrefixConfigurationTest.java
copy to dubbo-common/src/main/java/org/apache/dubbo/common/ConfigurationURL.java
index ba4b5b8..2042277 100644
--- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/AbstractPrefixConfigurationTest.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/ConfigurationURL.java
@@ -14,10 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.common.config;
+package org.apache.dubbo.common;
-/**
- *
- */
-public class AbstractPrefixConfigurationTest {
+public class ConfigurationURL extends URL {
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java
index c38ad58..02cd142 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java
@@ -97,19 +97,19 @@ class URL implements Serializable {
private static final long serialVersionUID = -1985165475234910535L;
- private final String protocol;
+ protected String protocol;
- private final String username;
+ protected String username;
- private final String password;
+ protected String password;
// by default, host to registry
- private final String host;
+ protected String host;
// by default, port to registry
- private final int port;
+ protected int port;
- private final String path;
+ protected String path;
private final Map<String, String> parameters;
@@ -134,6 +134,7 @@ class URL implements Serializable {
private volatile transient String string;
private transient String serviceKey;
+ private transient String protocolServiceKey;
private transient String address;
@@ -444,7 +445,7 @@ class URL implements Serializable {
}
public URL setUsername(String username) {
- return new URL(protocol, username, password, host, port, path, getParameters());
+ return new URL(getProtocol(), username, password, host, port, path, getParameters());
}
public String getPassword() {
@@ -452,7 +453,7 @@ class URL implements Serializable {
}
public URL setPassword(String password) {
- return new URL(protocol, username, password, host, port, path, getParameters());
+ return new URL(getProtocol(), username, password, host, port, path, getParameters());
}
public String getAuthority() {
@@ -469,7 +470,7 @@ class URL implements Serializable {
}
public URL setHost(String host) {
- return new URL(protocol, username, password, host, port, path, getParameters());
+ return new URL(getProtocol(), username, password, host, port, path, getParameters());
}
/**
@@ -492,7 +493,7 @@ class URL implements Serializable {
}
public URL setPort(int port) {
- return new URL(protocol, username, password, host, port, path, getParameters());
+ return new URL(getProtocol(), username, password, host, port, path, getParameters());
}
public int getPort(int defaultPort) {
@@ -516,7 +517,7 @@ class URL implements Serializable {
} else {
host = address;
}
- return new URL(protocol, username, password, host, port, path, getParameters());
+ return new URL(getProtocol(), username, password, host, port, path, getParameters());
}
public String getBackupAddress() {
@@ -552,7 +553,7 @@ class URL implements Serializable {
}
public URL setPath(String path) {
- return new URL(protocol, username, password, host, port, path, getParameters());
+ return new URL(getProtocol(), username, password, host, port, path, getParameters());
}
public String getAbsolutePath() {
@@ -584,41 +585,6 @@ class URL implements Serializable {
return Collections.unmodifiableMap(selectedParameters);
}
- public Map<String, Map<String, String>> getMethodParameters() {
- return methodParameters;
- }
-
- public String getParameterAndDecoded(String key) {
- return getParameterAndDecoded(key, null);
- }
-
- public String getParameterAndDecoded(String key, String defaultValue) {
- return decode(getParameter(key, defaultValue));
- }
-
- public String getParameter(String key) {
- return parameters.get(key);
- }
-
- public String getParameter(String key, String defaultValue) {
- String value = getParameter(key);
- return StringUtils.isEmpty(value) ? defaultValue : value;
- }
-
- public String[] getParameter(String key, String[] defaultValue) {
- String value = getParameter(key);
- return StringUtils.isEmpty(value) ? defaultValue : COMMA_SPLIT_PATTERN.split(value);
- }
-
- public List<String> getParameter(String key, List<String> defaultValue) {
- String value = getParameter(key);
- if (StringUtils.isEmpty(value)) {
- return defaultValue;
- }
- String[] strArray = COMMA_SPLIT_PATTERN.split(value);
- return Arrays.asList(strArray);
- }
-
/**
* Get parameter
*
@@ -654,7 +620,43 @@ class URL implements Serializable {
return result;
}
- private Map<String, Number> getNumbers() {
+
+ public Map<String, Map<String, String>> getMethodParameters() {
+ return methodParameters;
+ }
+
+ public String getParameterAndDecoded(String key) {
+ return getParameterAndDecoded(key, null);
+ }
+
+ public String getParameterAndDecoded(String key, String defaultValue) {
+ return decode(getParameter(key, defaultValue));
+ }
+
+ public String getParameter(String key) {
+ return parameters.get(key);
+ }
+
+ public String getParameter(String key, String defaultValue) {
+ String value = getParameter(key);
+ return StringUtils.isEmpty(value) ? defaultValue : value;
+ }
+
+ public String[] getParameter(String key, String[] defaultValue) {
+ String value = getParameter(key);
+ return StringUtils.isEmpty(value) ? defaultValue : COMMA_SPLIT_PATTERN.split(value);
+ }
+
+ public List<String> getParameter(String key, List<String> defaultValue) {
+ String value = getParameter(key);
+ if (StringUtils.isEmpty(value)) {
+ return defaultValue;
+ }
+ String[] strArray = COMMA_SPLIT_PATTERN.split(value);
+ return Arrays.asList(strArray);
+ }
+
+ protected Map<String, Number> getNumbers() {
// concurrent initialization is tolerant
if (numbers == null) {
numbers = new ConcurrentHashMap<>();
@@ -662,7 +664,7 @@ class URL implements Serializable {
return numbers;
}
- private Map<String, Map<String, Number>> getMethodNumbers() {
+ protected Map<String, Map<String, Number>> getMethodNumbers() {
if (methodNumbers == null) { // concurrent initialization is tolerant
methodNumbers = new ConcurrentHashMap<>();
}
@@ -846,8 +848,17 @@ class URL implements Serializable {
return URL.decode(getMethodParameter(method, key, defaultValue));
}
+ public String getMethodParameterStrict(String method, String key) {
+ Map<String, String> keyMap = getMethodParameters().get(method);
+ String value = null;
+ if (keyMap != null) {
+ value = keyMap.get(key);
+ }
+ return value;
+ }
+
public String getMethodParameter(String method, String key) {
- Map<String, String> keyMap = methodParameters.get(method);
+ Map<String, String> keyMap = getMethodParameters().get(method);
String value = null;
if (keyMap != null) {
value = keyMap.get(key);
@@ -1037,7 +1048,7 @@ class URL implements Serializable {
}
return false;
}
- String value = getMethodParameter(method, key);
+ String value = getMethodParameterStrict(method, key);
return StringUtils.isNotEmpty(value);
}
@@ -1129,7 +1140,7 @@ class URL implements Serializable {
Map<String, String> map = new HashMap<>(getParameters());
map.put(key, value);
- return new URL(protocol, username, password, host, port, path, map);
+ return new URL(getProtocol(), username, password, host, port, path, map);
}
public URL addParameterIfAbsent(String key, String value) {
@@ -1143,7 +1154,7 @@ class URL implements Serializable {
Map<String, String> map = new HashMap<>(getParameters());
map.put(key, value);
- return new URL(protocol, username, password, host, port, path, map);
+ return new URL(getProtocol(), username, password, host, port, path, map);
}
public URL addMethodParameter(String method, String key, String value) {
@@ -1158,7 +1169,7 @@ class URL implements Serializable {
Map<String, Map<String, String>> methodMap = toMethodParameters(map);
URL.putMethodParameter(method, key, value, methodMap);
- return new URL(protocol, username, password, host, port, path, map, methodMap);
+ return new URL(getProtocol(), username, password, host, port, path, map, methodMap);
}
public URL addMethodParameterIfAbsent(String method, String key, String value) {
@@ -1176,7 +1187,7 @@ class URL implements Serializable {
Map<String, Map<String, String>> methodMap = toMethodParameters(map);
URL.putMethodParameter(method, key, value, methodMap);
- return new URL(protocol, username, password, host, port, path, map, methodMap);
+ return new URL(getProtocol(), username, password, host, port, path, map, methodMap);
}
/**
@@ -1212,7 +1223,7 @@ class URL implements Serializable {
Map<String, String> map = new HashMap<>(getParameters());
map.putAll(parameters);
- return new URL(protocol, username, password, host, port, path, map);
+ return new URL(getProtocol(), username, password, host, port, path, map);
}
public URL addParametersIfAbsent(Map<String, String> parameters) {
@@ -1221,7 +1232,7 @@ class URL implements Serializable {
}
Map<String, String> map = new HashMap<>(parameters);
map.putAll(getParameters());
- return new URL(protocol, username, password, host, port, path, map);
+ return new URL(getProtocol(), username, password, host, port, path, map);
}
public URL addParameters(String... pairs) {
@@ -1271,11 +1282,11 @@ class URL implements Serializable {
if (map.size() == getParameters().size()) {
return this;
}
- return new URL(protocol, username, password, host, port, path, map);
+ return new URL(getProtocol(), username, password, host, port, path, map);
}
public URL clearParameters() {
- return new URL(protocol, username, password, host, port, path, new HashMap<>());
+ return new URL(getProtocol(), username, password, host, port, path, new HashMap<>());
}
public String getRawParameter(String key) {
@@ -1301,7 +1312,8 @@ class URL implements Serializable {
}
public Map<String, String> toMap() {
- Map<String, String> map = new HashMap<>(parameters);
+ Map<String, String> map = null == parameters ? new HashMap<>() : new HashMap<>(parameters);
+
if (protocol != null) {
map.put(PROTOCOL_KEY, protocol);
}
@@ -1512,6 +1524,14 @@ class URL implements Serializable {
return BaseServiceMetadata.buildServiceKey(path, group, version);
}
+ public String getProtocolServiceKey() {
+ if (protocolServiceKey != null) {
+ return protocolServiceKey;
+ }
+ this.protocolServiceKey = getServiceKey() + ":" + getProtocol();
+ return protocolServiceKey;
+ }
+
public String toServiceStringWithoutResolving() {
return buildString(true, false, false, true);
}
@@ -1688,4 +1708,276 @@ class URL implements Serializable {
subParameter.put(key, value);
}
+ /* add service scope operations, see InstanceAddressURL */
+ public Map<String, String> getServiceParameters(String service) {
+ return getParameters();
+ }
+
+ public String getServiceParameter(String service, String key) {
+ return getParameter(key);
+ }
+
+ public String getServiceParameter(String service, String key, String defaultValue) {
+ String value = getServiceParameter(service, key);
+ return StringUtils.isEmpty(value) ? defaultValue : value;
+ }
+
+ public int getServiceParameter(String service, String key, int defaultValue) {
+ return getParameter(key, defaultValue);
+ }
+
+ public double getServiceParameter(String service, String key, double defaultValue) {
+ Number n = getServiceNumbers(service).get(key);
+ if (n != null) {
+ return n.doubleValue();
+ }
+ String value = getServiceParameter(service, key);
+ if (StringUtils.isEmpty(value)) {
+ return defaultValue;
+ }
+ double d = Double.parseDouble(value);
+ getNumbers().put(key, d);
+ return d;
+ }
+
+ public float getServiceParameter(String service, String key, float defaultValue) {
+ Number n = getNumbers().get(key);
+ if (n != null) {
+ return n.floatValue();
+ }
+ String value = getServiceParameter(service, key);
+ if (StringUtils.isEmpty(value)) {
+ return defaultValue;
+ }
+ float f = Float.parseFloat(value);
+ getNumbers().put(key, f);
+ return f;
+ }
+
+ public long getServiceParameter(String service, String key, long defaultValue) {
+ Number n = getNumbers().get(key);
+ if (n != null) {
+ return n.longValue();
+ }
+ String value = getServiceParameter(service, key);
+ if (StringUtils.isEmpty(value)) {
+ return defaultValue;
+ }
+ long l = Long.parseLong(value);
+ getNumbers().put(key, l);
+ return l;
+ }
+
+ public short getServiceParameter(String service, String key, short defaultValue) {
+ Number n = getNumbers().get(key);
+ if (n != null) {
+ return n.shortValue();
+ }
+ String value = getServiceParameter(service, key);
+ if (StringUtils.isEmpty(value)) {
+ return defaultValue;
+ }
+ short s = Short.parseShort(value);
+ getNumbers().put(key, s);
+ return s;
+ }
+
+ public byte getServiceParameter(String service, String key, byte defaultValue) {
+ Number n = getNumbers().get(key);
+ if (n != null) {
+ return n.byteValue();
+ }
+ String value = getServiceParameter(service, key);
+ if (StringUtils.isEmpty(value)) {
+ return defaultValue;
+ }
+ byte b = Byte.parseByte(value);
+ getNumbers().put(key, b);
+ return b;
+ }
+
+ public char getServiceParameter(String service, String key, char defaultValue) {
+ String value = getServiceParameter(service, key);
+ return StringUtils.isEmpty(value) ? defaultValue : value.charAt(0);
+ }
+
+ public boolean getServiceParameter(String service, String key, boolean defaultValue) {
+ String value = getServiceParameter(service, key);
+ return StringUtils.isEmpty(value) ? defaultValue : Boolean.parseBoolean(value);
+ }
+
+ public boolean hasServiceParameter(String service, String key) {
+ String value = getServiceParameter(service, key);
+ return value != null && value.length() > 0;
+ }
+
+ public float getPositiveServiceParameter(String service, String key, float defaultValue) {
+ if (defaultValue <= 0) {
+ throw new IllegalArgumentException("defaultValue <= 0");
+ }
+ float value = getServiceParameter(service, key, defaultValue);
+ return value <= 0 ? defaultValue : value;
+ }
+
+ public double getPositiveServiceParameter(String service, String key, double defaultValue) {
+ if (defaultValue <= 0) {
+ throw new IllegalArgumentException("defaultValue <= 0");
+ }
+ double value = getServiceParameter(service, key, defaultValue);
+ return value <= 0 ? defaultValue : value;
+ }
+
+ public long getPositiveServiceParameter(String service, String key, long defaultValue) {
+ if (defaultValue <= 0) {
+ throw new IllegalArgumentException("defaultValue <= 0");
+ }
+ long value = getServiceParameter(service, key, defaultValue);
+ return value <= 0 ? defaultValue : value;
+ }
+
+ public int getPositiveServiceParameter(String service, String key, int defaultValue) {
+ if (defaultValue <= 0) {
+ throw new IllegalArgumentException("defaultValue <= 0");
+ }
+ int value = getServiceParameter(service, key, defaultValue);
+ return value <= 0 ? defaultValue : value;
+ }
+
+ public short getPositiveServiceParameter(String service, String key, short defaultValue) {
+ if (defaultValue <= 0) {
+ throw new IllegalArgumentException("defaultValue <= 0");
+ }
+ short value = getServiceParameter(service, key, defaultValue);
+ return value <= 0 ? defaultValue : value;
+ }
+
+ public byte getPositiveServiceParameter(String service, String key, byte defaultValue) {
+ if (defaultValue <= 0) {
+ throw new IllegalArgumentException("defaultValue <= 0");
+ }
+ byte value = getServiceParameter(service, key, defaultValue);
+ return value <= 0 ? defaultValue : value;
+ }
+
+ public String getServiceMethodParameterAndDecoded(String service, String method, String key) {
+ return URL.decode(getServiceMethodParameter(service, method, key));
+ }
+
+ public String getServiceMethodParameterAndDecoded(String service, String method, String key, String defaultValue) {
+ return URL.decode(getServiceMethodParameter(service, method, key, defaultValue));
+ }
+
+ public String getServiceMethodParameterStrict(String service, String method, String key) {
+ return getMethodParameterStrict(method, key);
+ }
+
+ public String getServiceMethodParameter(String service, String method, String key) {
+ return getMethodParameter(method, key);
+ }
+
+ public String getServiceMethodParameter(String service, String method, String key, String defaultValue) {
+ String value = getServiceMethodParameter(service, method, key);
+ return StringUtils.isEmpty(value) ? defaultValue : value;
+ }
+
+ public double getServiceMethodParameter(String service, String method, String key, double defaultValue) {
+ Number n = getCachedNumber(method, key);
+ if (n != null) {
+ return n.doubleValue();
+ }
+ String value = getServiceMethodParameter(service, method, key);
+ if (StringUtils.isEmpty(value)) {
+ return defaultValue;
+ }
+ double d = Double.parseDouble(value);
+ updateCachedNumber(method, key, d);
+ return d;
+ }
+
+ public float getServiceMethodParameter(String service, String method, String key, float defaultValue) {
+ Number n = getCachedNumber(method, key);
+ if (n != null) {
+ return n.floatValue();
+ }
+ String value = getServiceMethodParameter(service, method, key);
+ if (StringUtils.isEmpty(value)) {
+ return defaultValue;
+ }
+ float f = Float.parseFloat(value);
+ updateCachedNumber(method, key, f);
+ return f;
+ }
+
+ public long getServiceMethodParameter(String service, String method, String key, long defaultValue) {
+ Number n = getCachedNumber(method, key);
+ if (n != null) {
+ return n.longValue();
+ }
+ String value = getServiceMethodParameter(service, method, key);
+ if (StringUtils.isEmpty(value)) {
+ return defaultValue;
+ }
+ long l = Long.parseLong(value);
+ updateCachedNumber(method, key, l);
+ return l;
+ }
+
+ public int getServiceMethodParameter(String service, String method, String key, int defaultValue) {
+ Number n = getCachedNumber(method, key);
+ if (n != null) {
+ return n.intValue();
+ }
+ String value = getServiceMethodParameter(service, method, key);
+ if (StringUtils.isEmpty(value)) {
+ return defaultValue;
+ }
+ int i = Integer.parseInt(value);
+ updateCachedNumber(method, key, i);
+ return i;
+ }
+
+ public short getMethodParameter(String service, String method, String key, short defaultValue) {
+ Number n = getCachedNumber(method, key);
+ if (n != null) {
+ return n.shortValue();
+ }
+ String value = getServiceMethodParameter(service, method, key);
+ if (StringUtils.isEmpty(value)) {
+ return defaultValue;
+ }
+ short s = Short.parseShort(value);
+ updateCachedNumber(method, key, s);
+ return s;
+ }
+
+ public byte getServiceMethodParameter(String service, String method, String key, byte defaultValue) {
+ Number n = getCachedNumber(method, key);
+ if (n != null) {
+ return n.byteValue();
+ }
+ String value = getServiceMethodParameter(service, method, key);
+ if (StringUtils.isEmpty(value)) {
+ return defaultValue;
+ }
+ byte b = Byte.parseByte(value);
+ updateCachedNumber(method, key, b);
+ return b;
+ }
+
+ public boolean hasServiceMethodParameter(String service, String method, String key) {
+ return hasMethodParameter(method, key);
+ }
+
+ public boolean hasServiceMethodParameter(String service, String method) {
+ return hasMethodParameter(method);
+ }
+
+ protected Map<String, Number> getServiceNumbers(String service) {
+ return getNumbers();
+ }
+
+ protected Map<String, Map<String, Number>> getServiceMethodNumbers(String service) {
+ return getMethodNumbers();
+ }
+
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java
index b0447c8..a7c0693 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java
@@ -97,7 +97,11 @@ public class ConfigurationUtils {
}
public static String getProperty(String property, String defaultValue) {
- return StringUtils.trim(ApplicationModel.getEnvironment().getConfiguration().getString(property, defaultValue));
+ return StringUtils.trim(getGlobalConfiguration().getString(property, defaultValue));
+ }
+
+ public static int get(String property, int defaultValue) {
+ return getGlobalConfiguration().getInt(property, defaultValue);
}
public static Map<String, String> parseProperties(String content) throws IOException {
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java
index 1266d92..8ff7338 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java
@@ -191,6 +191,12 @@ public interface CommonConstants {
String METADATA_KEY = "metadata-type";
+ String MAPPING_KEY = "mapping-type";
+
+ String CONFIG_MAPPING_TYPE = "config";
+
+ String METADATA_MAPPING_TYPE = "metadata";
+
String DEFAULT_METADATA_STORAGE_TYPE = "local";
String REMOTE_METADATA_STORAGE_TYPE = "remote";
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java
index ce83136..3feeeb2 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java
@@ -21,6 +21,12 @@ public interface RegistryConstants {
String REGISTRY_KEY = "registry";
+ String REGISTRY_CLUSTER_KEY = "REGISTRY_CLUSTER";
+
+ String REGISTRY_CLUSTER = "REGISTRY_CLUSTER";
+
+ String REGISTRY_CLUSTER_TYPE_KEY = "registry-cluster-type";
+
String REGISTRY_PROTOCOL = "registry";
String DYNAMIC_KEY = "dynamic";
@@ -53,6 +59,10 @@ public interface RegistryConstants {
String COMPATIBLE_CONFIG_KEY = "compatible_config";
+ String REGISTRY_DUPLICATE_KEY = "duplicate";
+
+ String ENABLE_REGISTRY_DIRECTORY_AUTO_MIGRATION = "enable-auto-migration";
+
/**
* The parameter key of Dubbo Registry type
*
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java
index dd37bff..1669089 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java
@@ -55,10 +55,10 @@ public class DefaultExecutorRepository implements ExecutorRepository {
private ConcurrentMap<String, ConcurrentMap<Integer, ExecutorService>> data = new ConcurrentHashMap<>();
public DefaultExecutorRepository() {
-// for (int i = 0; i < DEFAULT_SCHEDULER_SIZE; i++) {
-// ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-framework-scheduler"));
-// scheduledExecutors.addItem(scheduler);
-// }
+ for (int i = 0; i < DEFAULT_SCHEDULER_SIZE; i++) {
+ ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-framework-scheduler"));
+ scheduledExecutors.addItem(scheduler);
+ }
//
// reconnectScheduledExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-reconnect-scheduler"));
serviceExporterExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Dubbo-exporter-scheduler"));
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java
index 82b5636..970a6ae 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java
@@ -280,6 +280,8 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.refresh();
registryConfigs.add(registryConfig);
+ } else {
+ registryConfigs = new ArrayList<>(registryConfigs);
}
setRegistries(registryConfigs);
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java
index 460dbc6..e482e35 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java
@@ -159,6 +159,11 @@ public class ApplicationConfig extends AbstractConfig {
private String repository;
+ /**
+ * Metadata Service, used in Service Discovery
+ */
+ private Integer metadataServicePort;
+
public ApplicationConfig() {
}
@@ -445,6 +450,15 @@ public class ApplicationConfig extends AbstractConfig {
this.repository = repository;
}
+ @Parameter(key = "metadata-service-port")
+ public Integer getMetadataServicePort() {
+ return metadataServicePort;
+ }
+
+ public void setMetadataServicePort(Integer metadataServicePort) {
+ this.metadataServicePort = metadataServicePort;
+ }
+
@Override
public void refresh() {
super.refresh();
@@ -464,7 +478,13 @@ public class ApplicationConfig extends AbstractConfig {
for (InfraAdapter adapter : adapters) {
Map<String, String> extraParameters = adapter.getExtraAttributes(inputParameters);
if (CollectionUtils.isNotEmptyMap(extraParameters)) {
- parameters.putAll(extraParameters);
+ extraParameters.forEach((key, value) -> {
+ String prefix = this.getPrefix() + ".";
+ if (key.startsWith(prefix)) {
+ key = key.substring(prefix.length());
+ }
+ parameters.put(key, value);
+ });
}
}
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java
index dcd43e2..c3f8c93 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java
@@ -79,6 +79,11 @@ public class MetadataReportConfig extends AbstractConfig {
*/
private Boolean cluster;
+ /**
+ * registry id
+ */
+ private String registry;
+
public MetadataReportConfig() {
}
@@ -211,4 +216,12 @@ public class MetadataReportConfig extends AbstractConfig {
public void setCluster(Boolean cluster) {
this.cluster = cluster;
}
+
+ public String getRegistry() {
+ return registry;
+ }
+
+ public void setRegistry(String registry) {
+ this.registry = registry;
+ }
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java
index 3b65b40..817bbc7 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java
@@ -194,6 +194,11 @@ public class RegistryConfig extends AbstractConfig {
setProtocol(protocol);
}
+ @Override
+ public String getId() {
+ return super.getId();
+ }
+
public String getProtocol() {
return protocol;
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigManager.java b/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigManager.java
index 868fadc..218fef0 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigManager.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigManager.java
@@ -164,6 +164,14 @@ public class ConfigManager extends LifecycleAdapter implements FrameworkExt {
return getConfigs(getTagName(MetadataReportConfig.class));
}
+ public Collection<MetadataReportConfig> getDefaultMetadataConfigs() {
+ Collection<MetadataReportConfig> defaults = getDefaultConfigs(getConfigsMap(getTagName(MetadataReportConfig.class)));
+ if (CollectionUtils.isEmpty(defaults)) {
+ return getMetadataConfigs();
+ }
+ return defaults;
+ }
+
// MetadataReportConfig correlative methods
public void addProvider(ProviderConfig providerConfig) {
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java
index e49888d..34fe276 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java
@@ -28,6 +28,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
+import java.util.TreeSet;
/**
* This model is bound to your reference's configuration, for example, group, version or method level configuration.
@@ -36,6 +37,7 @@ public class ConsumerModel {
private String serviceKey;
private final ServiceDescriptor serviceModel;
private final ReferenceConfigBase<?> referenceConfig;
+ private final Set<String> apps = new TreeSet<>();
private Object proxyObject;
@@ -110,6 +112,10 @@ public class ConsumerModel {
return referenceConfig;
}
+ public Set<String> getApps() {
+ return apps;
+ }
+
public AsyncMethodInfo getAsyncInfo(String methodName) {
return methodConfigs.get(methodName);
}
diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java
index 3710afd..f53e159 100644
--- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java
+++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java
@@ -118,6 +118,11 @@ public interface Invocation extends org.apache.dubbo.rpc.Invocation {
}
@Override
+ public String getProtocolServiceKey() {
+ return delegate.getProtocolServiceKey();
+ }
+
+ @Override
public String getMethodName() {
return delegate.getMethodName();
}
diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java
index c02c8b7..514dc97 100644
--- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java
+++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java
@@ -108,6 +108,11 @@ public class RpcInvocation implements Invocation, Serializable {
this.invoker = invoker;
}
+ @Override
+ public String getProtocolServiceKey() {
+ return null;
+ }
+
public String getMethodName() {
return methodName;
}
diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/cache/CacheTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/cache/CacheTest.java
index df85265..5f5b7ad 100644
--- a/dubbo-compatible/src/test/java/org/apache/dubbo/cache/CacheTest.java
+++ b/dubbo-compatible/src/test/java/org/apache/dubbo/cache/CacheTest.java
@@ -54,6 +54,11 @@ public class CacheTest {
}
@Override
+ public String getProtocolServiceKey() {
+ return null;
+ }
+
+ @Override
public String getMethodName() {
return null;
}
diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java
index cab2c53..a2f5d8e 100644
--- a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java
+++ b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java
@@ -45,6 +45,11 @@ public class LegacyInvocation implements Invocation {
return null;
}
+ @Override
+ public String getProtocolServiceKey() {
+ return null;
+ }
+
public String getMethodName() {
return "echo";
}
diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java
index 9b3856e..a2cb52e 100644
--- a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java
+++ b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java
@@ -56,6 +56,11 @@ public class MockInvocation implements Invocation {
return null;
}
+ @Override
+ public String getProtocolServiceKey() {
+ return null;
+ }
+
public String getMethodName() {
return "echo";
}
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
index da90597..f38b80b 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
@@ -36,7 +36,7 @@ import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.config.utils.ConfigValidationUtils;
import org.apache.dubbo.event.Event;
import org.apache.dubbo.event.EventDispatcher;
-import org.apache.dubbo.metadata.WritableMetadataService;
+import org.apache.dubbo.registry.client.metadata.MetadataUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
@@ -66,7 +66,6 @@ import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR_CHAR;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
-import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_KEY;
@@ -391,16 +390,10 @@ public class ReferenceConfig<T> extends ReferenceConfigBase<T> {
if (logger.isInfoEnabled()) {
logger.info("Refer dubbo service " + interfaceClass.getName() + " from url " + invoker.getUrl());
}
- /**
- * @since 2.7.0
- * ServiceData Store
- */
- String metadata = map.get(METADATA_KEY);
- WritableMetadataService metadataService = WritableMetadataService.getExtension(metadata == null ? DEFAULT_METADATA_STORAGE_TYPE : metadata);
- if (metadataService != null) {
- URL consumerURL = new URL(CONSUMER_PROTOCOL, map.remove(REGISTER_IP_KEY), 0, map.get(INTERFACE_KEY), map);
- metadataService.publishServiceDefinition(consumerURL);
- }
+
+ URL consumerURL = new URL(CONSUMER_PROTOCOL, map.remove(REGISTER_IP_KEY), 0, map.get(INTERFACE_KEY), map);
+ MetadataUtils.publishServiceDefinition(consumerURL);
+
// create service proxy
return (T) PROXY_FACTORY.getProxy(invoker, ProtocolUtils.isGeneric(generic));
}
@@ -437,6 +430,12 @@ public class ReferenceConfig<T> extends ReferenceConfigBase<T> {
}
// get consumer's global configuration
checkDefault();
+
+ // init some null configuration.
+ List<ConfigInitializer> configInitializers = ExtensionLoader.getExtensionLoader(ConfigInitializer.class)
+ .getActivateExtension(URL.valueOf("configInitializer://"), (String[]) null);
+ configInitializers.forEach(e -> e.initReferConfig(this));
+
this.refresh();
if (getGeneric() == null && getConsumer() != null) {
setGeneric(getConsumer().getGeneric());
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
index cf5af44..356a897 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
@@ -37,7 +37,8 @@ import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.config.utils.ConfigValidationUtils;
import org.apache.dubbo.event.Event;
import org.apache.dubbo.event.EventDispatcher;
-import org.apache.dubbo.metadata.WritableMetadataService;
+import org.apache.dubbo.metadata.ServiceNameMapping;
+import org.apache.dubbo.registry.client.metadata.MetadataUtils;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
@@ -68,10 +69,10 @@ import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
-import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_IP_TO_BIND;
import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE;
+import static org.apache.dubbo.common.constants.CommonConstants.MAPPING_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
@@ -210,6 +211,11 @@ public class ServiceConfig<T> extends ServiceConfigBase<T> {
}
public void exported() {
+ List<URL> exportedURLs = this.getExportedUrls();
+ exportedURLs.forEach(url -> {
+ Map<String, String> parameters = getApplication().getParameters();
+ ServiceNameMapping.getExtension(parameters != null ? parameters.get(MAPPING_KEY) : null).map(url);
+ });
// dispatch a ServiceConfigExportedEvent since 2.7.4
dispatch(new ServiceConfigExportedEvent(this));
}
@@ -425,7 +431,7 @@ public class ServiceConfig<T> extends ServiceConfigBase<T> {
/**
* Here the token value configured by the provider is used to assign the value to ServiceConfig#token
*/
- if(ConfigUtils.isEmpty(token) && provider != null) {
+ if (ConfigUtils.isEmpty(token) && provider != null) {
token = provider.getToken();
}
@@ -502,14 +508,8 @@ public class ServiceConfig<T> extends ServiceConfigBase<T> {
Exporter<?> exporter = PROTOCOL.export(wrapperInvoker);
exporters.add(exporter);
}
- /**
- * @since 2.7.0
- * ServiceData Store
- */
- WritableMetadataService metadataService = WritableMetadataService.getExtension(url.getParameter(METADATA_KEY, DEFAULT_METADATA_STORAGE_TYPE));
- if (metadataService != null) {
- metadataService.publishServiceDefinition(url);
- }
+
+ MetadataUtils.publishServiceDefinition(url);
}
}
this.urls.add(url);
@@ -706,7 +706,7 @@ public class ServiceConfig<T> extends ServiceConfigBase<T> {
}
private void postProcessConfig() {
- List<ConfigPostProcessor> configPostProcessors =ExtensionLoader.getExtensionLoader(ConfigPostProcessor.class)
+ List<ConfigPostProcessor> configPostProcessors = ExtensionLoader.getExtensionLoader(ConfigPostProcessor.class)
.getActivateExtension(URL.valueOf("configPostProcessor://"), (String[]) null);
configPostProcessors.forEach(component -> component.postProcessServiceConfig(this));
}
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrap.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrap.java
index 1ef096b..34977b3 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrap.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrap.java
@@ -17,6 +17,7 @@
package org.apache.dubbo.config.bootstrap;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory;
@@ -54,6 +55,7 @@ import org.apache.dubbo.config.bootstrap.builders.ReferenceBuilder;
import org.apache.dubbo.config.bootstrap.builders.RegistryBuilder;
import org.apache.dubbo.config.bootstrap.builders.ServiceBuilder;
import org.apache.dubbo.config.context.ConfigManager;
+import org.apache.dubbo.config.metadata.ConfigurableMetadataServiceExporter;
import org.apache.dubbo.config.utils.ConfigValidationUtils;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.apache.dubbo.event.EventDispatcher;
@@ -65,10 +67,12 @@ import org.apache.dubbo.metadata.WritableMetadataService;
import org.apache.dubbo.metadata.report.MetadataReportFactory;
import org.apache.dubbo.metadata.report.MetadataReportInstance;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
-import org.apache.dubbo.registry.client.ServiceDiscovery;
-import org.apache.dubbo.registry.client.ServiceDiscoveryRegistry;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
+import org.apache.dubbo.registry.client.metadata.MetadataUtils;
+import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils;
+import org.apache.dubbo.registry.client.metadata.store.InMemoryWritableMetadataService;
+import org.apache.dubbo.registry.client.metadata.store.RemoteMetadataServiceImpl;
import org.apache.dubbo.registry.support.AbstractRegistryFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
@@ -77,19 +81,18 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
-import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Supplier;
-import java.util.stream.Collectors;
import static java.lang.String.format;
import static java.util.Arrays.asList;
@@ -103,7 +106,12 @@ import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoad
import static org.apache.dubbo.common.function.ThrowableAction.execute;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
+import static org.apache.dubbo.metadata.MetadataConstants.DEFAULT_METADATA_PUBLISH_DELAY;
+import static org.apache.dubbo.metadata.MetadataConstants.METADATA_PUBLISH_DELAY_KEY;
+import static org.apache.dubbo.metadata.WritableMetadataService.getDefaultExtension;
+import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.calInstanceRevision;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.setMetadataStorageType;
+import static org.apache.dubbo.registry.support.AbstractRegistryFactory.getServiceDiscoveries;
import static org.apache.dubbo.remoting.Constants.CLIENT_KEY;
/**
@@ -172,7 +180,7 @@ public class DubboBootstrap extends GenericEventListener {
private volatile MetadataService metadataService;
- private volatile Set<MetadataServiceExporter> metadataServiceExporters;
+ private volatile MetadataServiceExporter metadataServiceExporter;
private List<ServiceConfigBase<?>> exportedServices = new ArrayList<>();
@@ -529,8 +537,6 @@ public class DubboBootstrap extends GenericEventListener {
initMetadataService();
- initMetadataServiceExports();
-
initEventListener();
if (logger.isInfoEnabled()) {
@@ -638,17 +644,18 @@ public class DubboBootstrap extends GenericEventListener {
Collection<MetadataReportConfig> metadataReportConfigs = configManager.getMetadataConfigs();
if (CollectionUtils.isEmpty(metadataReportConfigs)) {
if (REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) {
- throw new IllegalStateException("No MetadataConfig found, you must specify the remote Metadata Center address when 'metadata=remote' is enabled.");
+ throw new IllegalStateException("No MetadataConfig found, Metadata Center address is required when 'metadata=remote' is enabled.");
}
return;
}
- MetadataReportConfig metadataReportConfig = metadataReportConfigs.iterator().next();
- ConfigValidationUtils.validateMetadataConfig(metadataReportConfig);
- if (!metadataReportConfig.isValid()) {
- return;
- }
- MetadataReportInstance.init(metadataReportConfig.toUrl());
+ for (MetadataReportConfig metadataReportConfig : metadataReportConfigs) {
+ ConfigValidationUtils.validateMetadataConfig(metadataReportConfig);
+ if (!metadataReportConfig.isValid()) {
+ return;
+ }
+ MetadataReportInstance.init(metadataReportConfig);
+ }
}
/**
@@ -857,17 +864,12 @@ public class DubboBootstrap extends GenericEventListener {
/**
- * Initialize {@link #metadataService WritableMetadataService} from {@link WritableMetadataService}'s extension
+ * Initialize {@link MetadataService} from {@link WritableMetadataService}'s extension
*/
private void initMetadataService() {
- this.metadataService = WritableMetadataService.getExtension(getMetadataType());
- }
-
- /**
- * Initialize {@link #metadataServiceExporters MetadataServiceExporter}
- */
- private void initMetadataServiceExports() {
- this.metadataServiceExporters = getExtensionLoader(MetadataServiceExporter.class).getSupportedExtensionInstances();
+ startMetadataCenter();
+ this.metadataService = getDefaultExtension();
+ this.metadataServiceExporter = new ConfigurableMetadataServiceExporter(metadataService);
}
/**
@@ -878,15 +880,6 @@ public class DubboBootstrap extends GenericEventListener {
addEventListener(this);
}
- private List<ServiceDiscovery> getServiceDiscoveries() {
- return AbstractRegistryFactory.getRegistries()
- .stream()
- .filter(registry -> registry instanceof ServiceDiscoveryRegistry)
- .map(registry -> (ServiceDiscoveryRegistry) registry)
- .map(ServiceDiscoveryRegistry::getServiceDiscovery)
- .collect(Collectors.toList());
- }
-
/**
* Start the bootstrap
*/
@@ -1069,21 +1062,13 @@ public class DubboBootstrap extends GenericEventListener {
* export {@link MetadataService}
*/
private void exportMetadataService() {
- metadataServiceExporters
- .stream()
- .filter(this::supports)
- .forEach(MetadataServiceExporter::export);
+ metadataServiceExporter.export();
}
private void unexportMetadataService() {
- Optional.ofNullable(metadataServiceExporters)
- .ifPresent(set -> set.stream()
- .filter(this::supports)
- .forEach(MetadataServiceExporter::unexport));
- }
-
- private boolean supports(MetadataServiceExporter exporter) {
- return exporter.supports(getMetadataType());
+ if (metadataServiceExporter != null && metadataServiceExporter.isExported()) {
+ metadataServiceExporter.unexport();
+ }
}
private void exportServices() {
@@ -1176,37 +1161,35 @@ public class DubboBootstrap extends GenericEventListener {
ServiceInstance serviceInstance = createServiceInstance(serviceName, host, port);
- preRegisterServiceInstance(serviceInstance);
+ doRegisterServiceInstance(serviceInstance);
- getServiceDiscoveries().forEach(serviceDiscovery -> serviceDiscovery.register(serviceInstance));
+ // scheduled task for updating Metadata and ServiceInstance
+ executorRepository.nextScheduledExecutor().scheduleAtFixedRate(() -> {
+ InMemoryWritableMetadataService localMetadataService = (InMemoryWritableMetadataService) WritableMetadataService.getDefaultExtension();
+ localMetadataService.blockUntilUpdated();
+ ServiceInstanceMetadataUtils.refreshMetadataAndInstance();
+ }, 0, ConfigurationUtils.get(METADATA_PUBLISH_DELAY_KEY, DEFAULT_METADATA_PUBLISH_DELAY), TimeUnit.MICROSECONDS);
}
- /**
- * Pre-register {@link ServiceInstance the service instance}
- *
- * @param serviceInstance {@link ServiceInstance the service instance}
- * @since 2.7.8
- */
- private void preRegisterServiceInstance(ServiceInstance serviceInstance) {
- customizeServiceInstance(serviceInstance);
- }
+ private void doRegisterServiceInstance(ServiceInstance serviceInstance) {
+ //FIXME
+ publishMetadataToRemote(serviceInstance);
- /**
- * Customize {@link ServiceInstance the service instance}
- *
- * @param serviceInstance {@link ServiceInstance the service instance}
- * @since 2.7.8
- */
- private void customizeServiceInstance(ServiceInstance serviceInstance) {
- ExtensionLoader<ServiceInstanceCustomizer> loader =
- getExtensionLoader(ServiceInstanceCustomizer.class);
- // FIXME, sort customizer before apply
- loader.getSupportedExtensionInstances().forEach(customizer -> {
- // customizes
- customizer.customize(serviceInstance);
+ getServiceDiscoveries().forEach(serviceDiscovery ->
+ {
+ calInstanceRevision(serviceDiscovery, serviceInstance);
+ // register metadata
+ serviceDiscovery.register(serviceInstance);
});
}
+ private void publishMetadataToRemote(ServiceInstance serviceInstance) {
+// InMemoryWritableMetadataService localMetadataService = (InMemoryWritableMetadataService)WritableMetadataService.getDefaultExtension();
+// localMetadataService.blockUntilUpdated();
+ RemoteMetadataServiceImpl remoteMetadataService = MetadataUtils.getRemoteMetadataService();
+ remoteMetadataService.publishMetadata(serviceInstance.getServiceName());
+ }
+
private URL selectMetadataServiceExportedURL() {
URL selectedURL = null;
@@ -1244,6 +1227,15 @@ public class DubboBootstrap extends GenericEventListener {
private ServiceInstance createServiceInstance(String serviceName, String host, int port) {
this.serviceInstance = new DefaultServiceInstance(serviceName, host, port);
setMetadataStorageType(serviceInstance, getMetadataType());
+
+ ExtensionLoader<ServiceInstanceCustomizer> loader =
+ ExtensionLoader.getExtensionLoader(ServiceInstanceCustomizer.class);
+ // FIXME, sort customizer before apply
+ loader.getSupportedExtensionInstances().forEach(customizer -> {
+ // customizes
+ customizer.customize(this.serviceInstance);
+ });
+
return this.serviceInstance;
}
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilder.java
index 33e6f54..c226ac6 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilder.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilder.java
@@ -51,6 +51,7 @@ public class ApplicationBuilder extends AbstractBuilder<ApplicationConfig, Appli
private Boolean qosAcceptForeignIp;
private Map<String, String> parameters;
private String shutwait;
+ private Integer metadataServicePort;
public static ApplicationBuilder newBuilder() {
return new ApplicationBuilder();
@@ -172,6 +173,11 @@ public class ApplicationBuilder extends AbstractBuilder<ApplicationConfig, Appli
return getThis();
}
+ public ApplicationBuilder metadataServicePort(Integer metadataServicePort) {
+ this.metadataServicePort = metadataServicePort;
+ return getThis();
+ }
+
public ApplicationConfig build() {
ApplicationConfig config = new ApplicationConfig();
super.build(config);
@@ -193,6 +199,7 @@ public class ApplicationBuilder extends AbstractBuilder<ApplicationConfig, Appli
config.setQosEnable(this.qosEnable);
config.setQosPort(this.qosPort);
config.setQosAcceptForeignIp(this.qosAcceptForeignIp);
+ config.setMetadataServicePort(this.metadataServicePort);
config.setParameters(this.parameters);
if (!StringUtils.isEmpty(shutwait)) {
config.setShutwait(shutwait);
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListener.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListener.java
deleted file mode 100644
index 8607b51..0000000
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListener.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.apache.dubbo.config.event.listener;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.config.ServiceConfig;
-import org.apache.dubbo.config.event.ServiceConfigExportedEvent;
-import org.apache.dubbo.event.EventListener;
-import org.apache.dubbo.metadata.ServiceNameMapping;
-
-import java.util.List;
-
-import static org.apache.dubbo.metadata.ServiceNameMapping.getDefaultExtension;
-
-/**
- * An {@link EventListener event listener} for mapping {@link ServiceConfig#getExportedUrls() the exported Dubbo
- * service inerface} to its service name
- *
- * @see ServiceNameMapping
- * @see ServiceConfig#getExportedUrls()
- * @since 2.7.5
- */
-public class ServiceNameMappingListener implements EventListener<ServiceConfigExportedEvent> {
-
- private final ServiceNameMapping serviceNameMapping = getDefaultExtension();
-
- @Override
- public void onEvent(ServiceConfigExportedEvent event) {
- ServiceConfig serviceConfig = event.getServiceConfig();
- List<URL> exportedURLs = serviceConfig.getExportedUrls();
- exportedURLs.forEach(url -> {
- serviceNameMapping.map(url);
- });
- }
-}
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/AbstractMetadataServiceExporter.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/AbstractMetadataServiceExporter.java
deleted file mode 100644
index ce2b389..0000000
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/AbstractMetadataServiceExporter.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * 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.apache.dubbo.config.metadata;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.logger.Logger;
-import org.apache.dubbo.common.logger.LoggerFactory;
-import org.apache.dubbo.metadata.MetadataService;
-import org.apache.dubbo.metadata.MetadataServiceExporter;
-import org.apache.dubbo.metadata.MetadataServiceType;
-import org.apache.dubbo.metadata.WritableMetadataService;
-
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-import static java.util.EnumSet.of;
-import static org.apache.dubbo.metadata.MetadataServiceType.getOrDefault;
-
-/**
- * The abstract implementation of {@link MetadataServiceExporter} to provider the commons features for sub-types
- *
- * @see MetadataServiceExporter
- * @see MetadataService
- * @since 2.7.8
- */
-public abstract class AbstractMetadataServiceExporter implements MetadataServiceExporter {
-
- protected final Logger logger = LoggerFactory.getLogger(getClass());
-
- protected final WritableMetadataService metadataService;
-
- private final int priority;
-
- private final Set<MetadataServiceType> supportedMetadataServiceTypes;
-
- private volatile boolean exported = false;
-
- public AbstractMetadataServiceExporter(String metadataType,
- int priority,
- MetadataServiceType supportMetadataServiceType,
- MetadataServiceType... otherSupportMetadataServiceTypes) {
- this(metadataType, priority, of(supportMetadataServiceType, otherSupportMetadataServiceTypes));
- }
-
- public AbstractMetadataServiceExporter(String metadataType,
- int priority,
- Set<MetadataServiceType> supportedMetadataServiceTypes) {
- this.metadataService = WritableMetadataService.getExtension(metadataType);
- this.priority = priority;
- this.supportedMetadataServiceTypes = supportedMetadataServiceTypes;
- }
-
- @Override
- public final MetadataServiceExporter export() {
- if (!isExported()) {
- try {
- doExport();
- exported = true;
- } catch (Exception e) {
- if (logger.isErrorEnabled()) {
- logger.error("Exporting the MetadataService fails", e);
- }
- exported = false;
- }
- } else {
- if (logger.isWarnEnabled()) {
- logger.warn("The MetadataService has been exported : " + getExportedURLs());
- }
- }
- return this;
- }
-
- @Override
- public final MetadataServiceExporter unexport() {
- if (isExported()) {
- try {
- doUnexport();
- exported = false;
- } catch (Exception e) {
- if (logger.isErrorEnabled()) {
- logger.error("UnExporting the MetadataService fails", e);
- }
- }
- }
- return this;
- }
-
- @Override
- public List<URL> getExportedURLs() {
- return metadataService
- .getExportedURLs()
- .stream()
- .map(URL::valueOf)
- .collect(Collectors.toList());
- }
-
- @Override
- public boolean isExported() {
- return exported;
- }
-
- @Override
- public final boolean supports(String metadataType) {
- MetadataServiceType metadataServiceType = getOrDefault(metadataType);
- return supportedMetadataServiceTypes.contains(metadataServiceType);
- }
-
- @Override
- public int getPriority() {
- return priority;
- }
-
- /**
- * Exports the {@link MetadataService}
- *
- * @throws Exception If some exception occurs
- */
- protected abstract void doExport() throws Exception;
-
- /**
- * Unexports the {@link MetadataService}
- *
- * @throws Exception If some exception occurs
- */
- protected abstract void doUnexport() throws Exception;
-
- /**
- * Get the underlying of {@link MetadataService}
- *
- * @return non-null
- */
- public WritableMetadataService getMetadataService() {
- return metadataService;
- }
-}
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java
index d89fb77..d7d60fc 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java
@@ -17,23 +17,25 @@
package org.apache.dubbo.config.metadata;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.ArgumentConfig;
+import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metadata.MetadataServiceExporter;
-import org.apache.dubbo.metadata.MetadataServiceType;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import static java.util.Collections.emptyList;
-import static java.util.EnumSet.allOf;
-import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
-import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
+import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
/**
* {@link MetadataServiceExporter} implementation based on {@link ConfigManager Dubbo configurations}, the clients
@@ -50,41 +52,79 @@ import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
* @see ConfigManager
* @since 2.7.5
*/
-public class ConfigurableMetadataServiceExporter extends AbstractMetadataServiceExporter {
+public class ConfigurableMetadataServiceExporter implements MetadataServiceExporter {
+
+ private final Logger logger = LoggerFactory.getLogger(getClass());
+
+ private final MetadataService metadataService;
private volatile ServiceConfig<MetadataService> serviceConfig;
- public ConfigurableMetadataServiceExporter() {
- super(DEFAULT_METADATA_STORAGE_TYPE, MAX_PRIORITY, allOf(MetadataServiceType.class));
+ public ConfigurableMetadataServiceExporter(MetadataService metadataService) {
+ this.metadataService = metadataService;
}
@Override
- protected void doExport() throws Exception {
-
- ServiceConfig<MetadataService> serviceConfig = new ServiceConfig<>();
- serviceConfig.setApplication(getApplicationConfig());
- serviceConfig.setRegistries(getRegistries());
- serviceConfig.setProtocol(generateMetadataProtocol());
- serviceConfig.setInterface(MetadataService.class);
- serviceConfig.setRef(metadataService);
- serviceConfig.setGroup(getApplicationConfig().getName());
- serviceConfig.setVersion(metadataService.version());
-
- // export
- serviceConfig.export();
-
- if (logger.isInfoEnabled()) {
- logger.info("The MetadataService exports urls : " + serviceConfig.getExportedUrls());
+ public ConfigurableMetadataServiceExporter export() {
+
+ if (!isExported()) {
+
+ ServiceConfig<MetadataService> serviceConfig = new ServiceConfig<>();
+ serviceConfig.setApplication(getApplicationConfig());
+ serviceConfig.setRegistries(getRegistries());
+ serviceConfig.setProtocol(generateMetadataProtocol());
+ serviceConfig.setInterface(MetadataService.class);
+ serviceConfig.setRef(metadataService);
+ serviceConfig.setGroup(getApplicationConfig().getName());
+ serviceConfig.setVersion(metadataService.version());
+ serviceConfig.setMethods(generateMethodConfig());
+
+ // export
+ serviceConfig.export();
+
+ if (logger.isInfoEnabled()) {
+ logger.info("The MetadataService exports urls : " + serviceConfig.getExportedUrls());
+ }
+
+ this.serviceConfig = serviceConfig;
+
+ } else {
+ if (logger.isWarnEnabled()) {
+ logger.warn("The MetadataService has been exported : " + serviceConfig.getExportedUrls());
+ }
}
- this.serviceConfig = serviceConfig;
+ return this;
+ }
+
+ /**
+ * Generate Method Config for Service Discovery Metadata <p/>
+ * <p>
+ * Make {@link MetadataService} support argument callback,
+ * used to notify {@link org.apache.dubbo.registry.client.ServiceInstance}'s
+ * metadata change event
+ *
+ * @since 3.0
+ */
+ private List<MethodConfig> generateMethodConfig() {
+ MethodConfig methodConfig = new MethodConfig();
+ methodConfig.setName("getAndListenServiceDiscoveryMetadata");
+
+ ArgumentConfig argumentConfig = new ArgumentConfig();
+ argumentConfig.setIndex(1);
+ argumentConfig.setCallback(true);
+
+ methodConfig.setArguments(Collections.singletonList(argumentConfig));
+
+ return Collections.singletonList(methodConfig);
}
@Override
- protected void doUnexport() throws Exception {
- if (serviceConfig != null) {
+ public ConfigurableMetadataServiceExporter unexport() {
+ if (isExported()) {
serviceConfig.unexport();
}
+ return this;
}
@Override
@@ -96,11 +136,6 @@ public class ConfigurableMetadataServiceExporter extends AbstractMetadataService
return serviceConfig != null && serviceConfig.isExported();
}
- @Override
- public int getPriority() {
- return MAX_PRIORITY;
- }
-
private ApplicationConfig getApplicationConfig() {
return ApplicationModel.getConfigManager().getApplication().get();
}
@@ -111,10 +146,27 @@ public class ConfigurableMetadataServiceExporter extends AbstractMetadataService
private ProtocolConfig generateMetadataProtocol() {
ProtocolConfig defaultProtocol = new ProtocolConfig();
- defaultProtocol.setName(DUBBO);
- // defaultProtocol.setHost() ?
- // auto-increment port
- defaultProtocol.setPort(-1);
+ Integer port = getApplicationConfig().getMetadataServicePort();
+
+ if (port == null || port < -1) {
+ if (logger.isInfoEnabled()) {
+ logger.info("Metadata Service Port hasn't been set. " +
+ "Use default protocol defined in protocols.");
+ }
+ List<ProtocolConfig> defaultProtocols = ApplicationModel.getConfigManager().getDefaultProtocols();
+
+ if (defaultProtocols.isEmpty()) {
+ defaultProtocol.setName(DUBBO_PROTOCOL);
+ defaultProtocol.setPort(-1);
+ } else {
+ return defaultProtocols.get(0);
+ }
+
+ } else {
+ defaultProtocol.setName(DUBBO_PROTOCOL);
+ defaultProtocol.setPort(port);
+ }
+
return defaultProtocol;
}
}
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/RemoteMetadataServiceExporter.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/RemoteMetadataServiceExporter.java
deleted file mode 100644
index 6d48921..0000000
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/RemoteMetadataServiceExporter.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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.apache.dubbo.config.metadata;
-
-import org.apache.dubbo.common.constants.CommonConstants;
-import org.apache.dubbo.metadata.MetadataServiceExporter;
-import org.apache.dubbo.metadata.MetadataServiceType;
-import org.apache.dubbo.metadata.URLRevisionResolver;
-import org.apache.dubbo.metadata.WritableMetadataService;
-import org.apache.dubbo.metadata.report.MetadataReport;
-import org.apache.dubbo.metadata.report.MetadataReportInstance;
-import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
-
-import java.util.SortedSet;
-
-import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE;
-
-/**
- * The implementation of {@link MetadataServiceExporter} for
- * {@link CommonConstants#REMOTE_METADATA_STORAGE_TYPE "remote" metadata storage type}
- *
- * @see MetadataServiceExporter
- * @since 2.7.8
- */
-public class RemoteMetadataServiceExporter extends AbstractMetadataServiceExporter {
-
- private final URLRevisionResolver urlRevisionResolver;
-
- public RemoteMetadataServiceExporter() {
- super(REMOTE_METADATA_STORAGE_TYPE, MIN_PRIORITY, MetadataServiceType.REMOTE, MetadataServiceType.COMPOSITE);
- this.urlRevisionResolver = URLRevisionResolver.INSTANCE;
- }
-
- @Override
- protected void doExport() throws Exception {
- WritableMetadataService metadataServiceDelegate = WritableMetadataService.getDefaultExtension();
- if (publishServiceMetadata(metadataServiceDelegate)) {
- publicConsumerMetadata(metadataServiceDelegate);
- }
- }
-
- private boolean publishServiceMetadata(WritableMetadataService metadataServiceDelegate) {
- String serviceName = metadataServiceDelegate.serviceName();
- SortedSet<String> exportedURLs = metadataServiceDelegate.getExportedURLs();
- String revision = urlRevisionResolver.resolve(exportedURLs);
- return getMetadataReport().saveExportedURLs(serviceName, revision, exportedURLs);
- }
-
- private boolean publicConsumerMetadata(WritableMetadataService metadataServiceDelegate) {
- String serviceName = metadataServiceDelegate.serviceName();
- SortedSet<String> subscribedURLs = metadataServiceDelegate.getSubscribedURLs();
- String revision = urlRevisionResolver.resolve(subscribedURLs);
- getMetadataReport().saveSubscribedData(new SubscriberMetadataIdentifier(serviceName, revision), subscribedURLs);
- return true;
- }
-
- private MetadataReport getMetadataReport() {
- return MetadataReportInstance.getMetadataReport(true);
- }
-
- @Override
- protected void doUnexport() throws Exception {
- // DOES NOTHING
- }
-}
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java
index 8a91d1c..4658157 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java
@@ -86,8 +86,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_SE
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.USERNAME_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
+import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_DUPLICATE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL;
+import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_PROTOCOL;
import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
@@ -202,7 +204,33 @@ public class ConfigValidationUtils {
}
}
}
- return registryList;
+ return genCompatibleRegistries(registryList, provider);
+ }
+
+ private static List<URL> genCompatibleRegistries(List<URL> registryList, boolean provider) {
+ List<URL> result = new ArrayList<>(registryList.size());
+ registryList.forEach(registryURL -> {
+ result.add(registryURL);
+ if (provider) {
+ // for registries enabled service discovery, automatically register interface compatible addresses.
+ if (SERVICE_REGISTRY_PROTOCOL.equals(registryURL.getProtocol())
+ && registryURL.getParameter(REGISTRY_DUPLICATE_KEY, false)
+ && registryNotExists(registryURL, registryList, REGISTRY_PROTOCOL)) {
+ URL interfaceCompatibleRegistryURL = URLBuilder.from(registryURL)
+ .setProtocol(REGISTRY_PROTOCOL)
+ .removeParameter(REGISTRY_TYPE_KEY)
+ .build();
+ result.add(interfaceCompatibleRegistryURL);
+ }
+ }
+ });
+ return result;
+ }
+
+ private static boolean registryNotExists(URL registryURL, List<URL> registryList, String registryType) {
+ return registryList.stream().noneMatch(
+ url -> registryType.equals(url.getProtocol()) && registryURL.getBackupAddress().equals(url.getBackupAddress())
+ );
}
public static URL loadMonitor(AbstractInterfaceConfig interfaceConfig, URL registryURL) {
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java
index 2bcd960..3a4a83c 100644
--- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java
+++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java
@@ -24,6 +24,7 @@ import org.apache.dubbo.config.mock.GreetingLocal3;
import org.apache.dubbo.config.mock.GreetingMock1;
import org.apache.dubbo.config.mock.GreetingMock2;
import org.apache.dubbo.config.utils.ConfigValidationUtils;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
@@ -41,12 +42,14 @@ public class AbstractInterfaceConfigTest {
@BeforeAll
public static void setUp(@TempDir Path folder) {
+ ApplicationModel.reset();
dubboProperties = folder.resolve(CommonConstants.DUBBO_PROPERTIES_KEY).toFile();
System.setProperty(CommonConstants.DUBBO_PROPERTIES_KEY, dubboProperties.getAbsolutePath());
}
@AfterAll
public static void tearDown() {
+ ApplicationModel.reset();
System.clearProperty(CommonConstants.DUBBO_PROPERTIES_KEY);
}
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java
index 6136dd4..e329f23 100644
--- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java
+++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java
@@ -25,6 +25,7 @@ import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.utils.ConfigValidationUtils;
import org.apache.dubbo.monitor.MonitorService;
import org.apache.dubbo.registry.RegistryService;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
@@ -55,13 +56,14 @@ public class DubboBootstrapTest {
@BeforeAll
public static void setUp(@TempDir Path folder) {
+ ApplicationModel.reset();
dubboProperties = folder.resolve(CommonConstants.DUBBO_PROPERTIES_KEY).toFile();
System.setProperty(CommonConstants.DUBBO_PROPERTIES_KEY, dubboProperties.getAbsolutePath());
}
@AfterEach
public void tearDown() throws IOException {
-
+ ApplicationModel.reset();
}
@Test
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilderTest.java
index 6c37eae..f6da86a 100644
--- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilderTest.java
+++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilderTest.java
@@ -214,6 +214,13 @@ class ApplicationBuilderTest {
}
@Test
+ void metadataServicePort() {
+ ApplicationBuilder builder = new ApplicationBuilder();
+ builder.metadataServicePort(12345);
+ Assertions.assertEquals(12345, builder.build().getMetadataServicePort());
+ }
+
+ @Test
void build() {
MonitorConfig monitor = new MonitorConfig("monitor-addr");
RegistryConfig registry = new RegistryConfig();
@@ -223,7 +230,7 @@ class ApplicationBuilderTest {
.environment("develop").compiler("compiler").logger("log4j").monitor(monitor).isDefault(false)
.dumpDirectory("dumpDirectory").qosEnable(true).qosPort(8080).qosAcceptForeignIp(false)
.shutwait("shutwait").registryIds("registryIds").addRegistry(registry)
- .appendParameter("default.num", "one");
+ .appendParameter("default.num", "one").metadataServicePort(12345);
ApplicationConfig config = builder.build();
ApplicationConfig config2 = builder.build();
@@ -249,6 +256,7 @@ class ApplicationBuilderTest {
Assertions.assertSame(registry, config.getRegistry());
Assertions.assertTrue(config.getParameters().containsKey("default.num"));
Assertions.assertEquals("one", config.getParameters().get("default.num"));
+ Assertions.assertEquals(12345, config.getMetadataServicePort());
Assertions.assertNotSame(config, config2);
}
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheTest.java
index 5cb18c0..ed7cb5e 100644
--- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheTest.java
+++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheTest.java
@@ -131,7 +131,7 @@ public class CacheTest {
parameters.put("findCache.cache", "threadlocal");
URL url = new URL("dubbo", "127.0.0.1", 29582, "org.apache.dubbo.config.cache.CacheService", parameters);
- Invocation invocation = new RpcInvocation("findCache", CacheService.class.getName(), new Class[]{String.class}, new String[]{"0"}, null, null, null);
+ Invocation invocation = new RpcInvocation("findCache", CacheService.class.getName(), "", new Class[]{String.class}, new String[]{"0"}, null, null, null);
Cache cache = cacheFactory.getCache(url, invocation);
assertTrue(cache instanceof ThreadLocalCache);
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/event/listener/PublishingServiceDefinitionListenerTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/event/listener/PublishingServiceDefinitionListenerTest.java
index 67a562d..3190f34 100644
--- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/event/listener/PublishingServiceDefinitionListenerTest.java
+++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/event/listener/PublishingServiceDefinitionListenerTest.java
@@ -16,7 +16,6 @@
*/
package org.apache.dubbo.config.event.listener;
-import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
@@ -25,7 +24,8 @@ import org.apache.dubbo.config.bootstrap.EchoServiceImpl;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.event.ServiceConfigExportedEvent;
import org.apache.dubbo.metadata.WritableMetadataService;
-import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
+import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder;
+import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.rpc.model.ApplicationModel;
import com.google.gson.Gson;
@@ -33,14 +33,7 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import java.util.List;
-
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
-import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
-import static org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder.buildFullDefinition;
-import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY;
-import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -59,7 +52,7 @@ public class PublishingServiceDefinitionListenerTest {
ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-demo-provider");
applicationConfig.setMetadataType(metadataType);
configManager.setApplication(applicationConfig);
- this.writableMetadataService = WritableMetadataService.getExtension(metadataType);
+ this.writableMetadataService = WritableMetadataService.getDefaultExtension();
}
@AfterEach
@@ -80,15 +73,8 @@ public class PublishingServiceDefinitionListenerTest {
String serviceDefinition = writableMetadataService.getServiceDefinition(EchoService.class.getName());
- List<URL> exportedUrls = serviceConfig.getExportedUrls();
-
- FullServiceDefinition fullServiceDefinition = buildFullDefinition(
- serviceConfig.getInterfaceClass(),
- exportedUrls.get(0)
- .removeParameters(PID_KEY, TIMESTAMP_KEY, BIND_IP_KEY, BIND_PORT_KEY, TIMESTAMP_KEY)
- .getParameters()
- );
+ ServiceDefinition serviceDefinitionBuild = ServiceDefinitionBuilder.build(serviceConfig.getInterfaceClass());
- assertEquals(serviceDefinition, new Gson().toJson(fullServiceDefinition));
+ assertEquals(serviceDefinition, new Gson().toJson(serviceDefinitionBuild));
}
}
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/RemoteMetadataServiceExporterTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/RemoteMetadataServiceExporterTest.java
deleted file mode 100644
index e4d13a1..0000000
--- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/RemoteMetadataServiceExporterTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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.apache.dubbo.config.metadata;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.config.ApplicationConfig;
-import org.apache.dubbo.metadata.MetadataServiceExporter;
-import org.apache.dubbo.metadata.WritableMetadataService;
-import org.apache.dubbo.metadata.report.MetadataReportInstance;
-import org.apache.dubbo.rpc.model.ApplicationModel;
-import org.apache.dubbo.rpc.service.EchoService;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import static java.util.Arrays.asList;
-import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.COMPOSITE_METADATA_STORAGE_TYPE;
-import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
-import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE;
-import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
-import static org.apache.dubbo.metadata.MetadataServiceExporter.getExtension;
-import static org.apache.dubbo.metadata.report.support.Constants.SYNC_REPORT_KEY;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-/**
- * {@link RemoteMetadataServiceExporter} Test-Cases
- *
- * @since 2.7.8
- */
-public class RemoteMetadataServiceExporterTest {
-
- private static final URL METADATA_REPORT_URL = URL.valueOf("file://")
- .addParameter(APPLICATION_KEY, "test")
- .addParameter(SYNC_REPORT_KEY, "true");
-
- private static final Class<EchoService> INTERFACE_CLASS = EchoService.class;
-
- private static final String INTERFACE_NAME = INTERFACE_CLASS.getName();
-
- private static final String APP_NAME = "test-service";
-
- private static final URL BASE_URL = URL
- .valueOf("dubbo://127.0.0.1:20880")
- .setPath(INTERFACE_NAME)
- .addParameter(APPLICATION_KEY, APP_NAME)
- .addParameter(SIDE_KEY, "provider");
-
- private final MetadataServiceExporter exporter = getExtension(REMOTE_METADATA_STORAGE_TYPE);
-
- private WritableMetadataService writableMetadataService;
-
- @BeforeEach
- public void init() {
- ApplicationModel.getConfigManager().setApplication(new ApplicationConfig(APP_NAME));
- MetadataReportInstance.init(METADATA_REPORT_URL);
- writableMetadataService = WritableMetadataService.getDefaultExtension();
- writableMetadataService.exportURL(BASE_URL);
- }
-
- @AfterEach
- public void reset() {
- ApplicationModel.reset();
- }
-
- @Test
- public void testType() {
- assertEquals(RemoteMetadataServiceExporter.class, exporter.getClass());
- }
-
- @Test
- public void testSupports() {
- assertTrue(exporter.supports(REMOTE_METADATA_STORAGE_TYPE));
- assertTrue(exporter.supports(COMPOSITE_METADATA_STORAGE_TYPE));
- assertFalse(exporter.supports(DEFAULT_METADATA_STORAGE_TYPE));
- }
-
- @Test
- public void testExportAndUnexport() {
- assertFalse(exporter.isExported());
- assertEquals(exporter, exporter.export());
- assertTrue(exporter.isExported());
-
- assertEquals(asList(BASE_URL), exporter.getExportedURLs());
-
- assertEquals(exporter, exporter.unexport());
- assertFalse(exporter.isExported());
- }
-}
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceDiscovery.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceDiscovery.java
new file mode 100644
index 0000000..33f1a16
--- /dev/null
+++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceDiscovery.java
@@ -0,0 +1,69 @@
+/*
+ * 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.apache.dubbo.config.mock;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.registry.client.ServiceDiscovery;
+import org.apache.dubbo.registry.client.ServiceInstance;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class MockServiceDiscovery implements ServiceDiscovery {
+ private URL registryURL;
+ private ServiceInstance serviceInstance;
+
+ @Override
+ public void initialize(URL registryURL) throws Exception {
+ this.registryURL = registryURL;
+ }
+
+ @Override
+ public void destroy() throws Exception {
+
+ }
+
+ @Override
+ public void register(ServiceInstance serviceInstance) throws RuntimeException {
+ this.serviceInstance = serviceInstance;
+ }
+
+ @Override
+ public void update(ServiceInstance serviceInstance) throws RuntimeException {
+ this.serviceInstance = serviceInstance;
+ }
+
+ @Override
+ public void unregister(ServiceInstance serviceInstance) throws RuntimeException {
+ this.serviceInstance = null;
+ }
+
+ @Override
+ public Set<String> getServices() {
+ return new HashSet<>();
+ }
+
+ @Override
+ public URL getUrl() {
+ return registryURL;
+ }
+
+ @Override
+ public ServiceInstance getLocalInstance() {
+ return serviceInstance;
+ }
+}
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/metadata/MetadataServiceExporterTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/metadata/MetadataServiceExporterTest.java
index 8096276..811b8a9 100644
--- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/metadata/MetadataServiceExporterTest.java
+++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/metadata/MetadataServiceExporterTest.java
@@ -16,12 +16,20 @@
*/
package org.apache.dubbo.metadata;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.ProtocolConfig;
+import org.apache.dubbo.config.RegistryConfig;
+import org.apache.dubbo.config.metadata.ConfigurableMetadataServiceExporter;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.COMPOSITE_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE;
-import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -31,10 +39,28 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
*/
public class MetadataServiceExporterTest {
+ @BeforeAll
+ public static void init() {
+ ApplicationModel.getConfigManager().setApplication(new ApplicationConfig("Test"));
+ ApplicationModel.getConfigManager().addRegistry(new RegistryConfig("test://1.2.3.4"));
+ ApplicationModel.getConfigManager().addProtocol(new ProtocolConfig("injvm"));
+ }
+
+ @AfterAll
+ public static void destroy() {
+ ApplicationModel.getConfigManager().setApplication(null);
+ ApplicationModel.reset();
+ }
+
@Test
public void test() {
- MetadataServiceExporter exporter = MetadataServiceExporter.getExtension(null);
- assertEquals(exporter, MetadataServiceExporter.getDefaultExtension());
+ MetadataService metadataService = Mockito.mock(MetadataService.class);
+ MetadataServiceExporter exporter = new ConfigurableMetadataServiceExporter(metadataService);
+
+ exporter.export();
+ assertTrue(exporter.isExported());
+ exporter.unexport();
+
assertTrue(exporter.supports(DEFAULT_METADATA_STORAGE_TYPE));
assertTrue(exporter.supports(REMOTE_METADATA_STORAGE_TYPE));
assertTrue(exporter.supports(COMPOSITE_METADATA_STORAGE_TYPE));
diff --git a/dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscovery b/dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscovery
new file mode 100644
index 0000000..22ceb16
--- /dev/null
+++ b/dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscovery
@@ -0,0 +1 @@
+mockregistry=org.apache.dubbo.config.mock.MockServiceDiscovery
\ No newline at end of file
diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd
index 1805b2a..ab229eb 100644
--- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd
+++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd
@@ -690,6 +690,11 @@
<xsd:documentation><![CDATA[ Need cluster support, default false. ]]></xsd:documentation>
</xsd:annotation>
</xsd:attribute>
+ <xsd:attribute name="registry" type="xsd:string" use="optional">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[ registry config id. ]]></xsd:documentation>
+ </xsd:annotation>
+ </xsd:attribute>
</xsd:complexType>
<xsd:complexType name="configCenterType">
diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd
index b12d815..a79ebb4 100644
--- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd
+++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd
@@ -685,6 +685,11 @@
<xsd:documentation><![CDATA[ Need cluster support, default false. ]]></xsd:documentation>
</xsd:annotation>
</xsd:attribute>
+ <xsd:attribute name="registry" type="xsd:string" use="optional">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[ registry config id. ]]></xsd:documentation>
+ </xsd:annotation>
+ </xsd:attribute>
</xsd:complexType>
<xsd:complexType name="configCenterType">
diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockServiceDiscovery.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockServiceDiscovery.java
new file mode 100644
index 0000000..1511b0e
--- /dev/null
+++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockServiceDiscovery.java
@@ -0,0 +1,69 @@
+/*
+ * 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.apache.dubbo.config.spring.registry;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.registry.client.ServiceDiscovery;
+import org.apache.dubbo.registry.client.ServiceInstance;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class MockServiceDiscovery implements ServiceDiscovery {
+ private URL registryURL;
+ private ServiceInstance serviceInstance;
+
+ @Override
+ public void initialize(URL registryURL) throws Exception {
+ this.registryURL = registryURL;
+ }
+
+ @Override
+ public void destroy() throws Exception {
+
+ }
+
+ @Override
+ public void register(ServiceInstance serviceInstance) throws RuntimeException {
+ this.serviceInstance = serviceInstance;
+ }
+
+ @Override
+ public void update(ServiceInstance serviceInstance) throws RuntimeException {
+ this.serviceInstance = serviceInstance;
+ }
+
+ @Override
+ public void unregister(ServiceInstance serviceInstance) throws RuntimeException {
+ this.serviceInstance = null;
+ }
+
+ @Override
+ public Set<String> getServices() {
+ return new HashSet<>();
+ }
+
+ @Override
+ public URL getUrl() {
+ return registryURL;
+ }
+
+ @Override
+ public ServiceInstance getLocalInstance() {
+ return serviceInstance;
+ }
+}
diff --git a/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery b/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery
new file mode 100644
index 0000000..cea6b84
--- /dev/null
+++ b/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery
@@ -0,0 +1 @@
+mock=org.apache.dubbo.config.spring.registry.MockServiceDiscovery
\ No newline at end of file
diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java
index 86dd306..e6ed4b5 100644
--- a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java
+++ b/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java
@@ -49,7 +49,7 @@ public class EtcdDynamicConfigurationTest {
private static EtcdDynamicConfiguration config;
- public EtcdCluster etcdCluster = EtcdClusterFactory.buildCluster(getClass().getSimpleName(), 3, false, false);
+ public EtcdCluster etcdCluster = EtcdClusterFactory.buildCluster(getClass().getSimpleName(), 3, false);
private static Client client;
diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java
index 955d3eb..fba18bc 100644
--- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java
+++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java
@@ -17,6 +17,7 @@
package org.apache.dubbo.demo.consumer;
import org.apache.dubbo.demo.DemoService;
+import org.apache.dubbo.demo.GreetingService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@@ -31,7 +32,28 @@ public class Application {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-consumer.xml");
context.start();
DemoService demoService = context.getBean("demoService", DemoService.class);
- CompletableFuture<String> hello = demoService.sayHelloAsync("world");
- System.out.println("result: " + hello.get());
+ GreetingService greetingService = context.getBean("greetingService", GreetingService.class);
+
+ new Thread(() -> {
+ while (true) {
+ String greetings = greetingService.hello();
+ System.out.println(greetings + " from separated thread.");
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }).start();
+
+ while (true) {
+ CompletableFuture<String> hello = demoService.sayHelloAsync("world");
+ System.out.println("result: " + hello.get());
+
+ String greetings = greetingService.hello();
+ System.out.println("result: " + greetings);
+
+ Thread.sleep(500);
+ }
}
}
diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/resources/spring/dubbo-consumer.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/resources/spring/dubbo-consumer.xml
index 742195f..9225959 100644
--- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/resources/spring/dubbo-consumer.xml
+++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/resources/spring/dubbo-consumer.xml
@@ -21,10 +21,19 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
- <dubbo:application name="demo-consumer"/>
+ <dubbo:application name="demo-consumer">
+ <dubbo:parameter key="mapping-type" value="metadata"/>
+ <dubbo:parameter key="enable-auto-migration" value="true"/>
+ </dubbo:application>
+
+ <!-- <dubbo:metadata-report address="zookeeper://127.0.0.1:2181"/>-->
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
- <dubbo:reference id="demoService" check="false" interface="org.apache.dubbo.demo.DemoService"/>
+ <dubbo:reference provided-by="demo-provider" id="demoService" check="false"
+ interface="org.apache.dubbo.demo.DemoService"/>
+
+ <dubbo:reference provided-by="demo-provider" version="1.0.0" group="greeting" id="greetingService" check="false"
+ interface="org.apache.dubbo.demo.GreetingService"/>
</beans>
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/AbstractPrefixConfigurationTest.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/GreetingServiceImpl.java
similarity index 78%
copy from dubbo-common/src/test/java/org/apache/dubbo/common/config/AbstractPrefixConfigurationTest.java
copy to dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/GreetingServiceImpl.java
index ba4b5b8..cc1b5de 100644
--- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/AbstractPrefixConfigurationTest.java
+++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/GreetingServiceImpl.java
@@ -14,10 +14,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.common.config;
+package org.apache.dubbo.demo.provider;
+
+import org.apache.dubbo.demo.GreetingService;
/**
*
*/
-public class AbstractPrefixConfigurationTest {
+public class GreetingServiceImpl implements GreetingService {
+ @Override
+ public String hello() {
+ return "Greetings!";
+ }
}
diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/resources/spring/dubbo-provider.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/resources/spring/dubbo-provider.xml
index c809ff3..856ff73 100644
--- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/resources/spring/dubbo-provider.xml
+++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/resources/spring/dubbo-provider.xml
@@ -21,15 +21,21 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
- <dubbo:application metadata-type="remote" name="demo-provider"/>
- <dubbo:metadata-report address="zookeeper://127.0.0.1:2181"/>
+ <dubbo:application name="demo-provider">
+ <dubbo:parameter key="mapping-type" value="metadata"/>
+ </dubbo:application>
- <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
+ <dubbo:config-center address="zookeeper://127.0.0.1:2181"/>
+ <dubbo:metadata-report address="zookeeper://127.0.0.1:2181"/>
+ <dubbo:registry id="registry1" address="zookeeper://127.0.0.1:2181?registry-type=service"/>
- <dubbo:protocol name="dubbo"/>
+ <dubbo:protocol name="dubbo" port="-1"/>
<bean id="demoService" class="org.apache.dubbo.demo.provider.DemoServiceImpl"/>
+ <bean id="greetingService" class="org.apache.dubbo.demo.provider.GreetingServiceImpl"/>
- <dubbo:service interface="org.apache.dubbo.demo.DemoService" ref="demoService"/>
+ <dubbo:service interface="org.apache.dubbo.demo.DemoService" timeout="3000" ref="demoService" registry="registry1"/>
+ <dubbo:service version="1.0.0" group="greeting" timeout="5000" interface="org.apache.dubbo.demo.GreetingService"
+ ref="greetingService"/>
</beans>
diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml
index ddae94e..3b232b8 100644
--- a/dubbo-dependencies-bom/pom.xml
+++ b/dubbo-dependencies-bom/pom.xml
@@ -92,9 +92,9 @@
<spring_version>4.3.16.RELEASE</spring_version>
<javassist_version>3.20.0-GA</javassist_version>
<netty_version>3.2.5.Final</netty_version>
- <netty4_version>4.1.25.Final</netty4_version>
+ <netty4_version>4.1.51.Final</netty4_version>
<mina_version>1.1.7</mina_version>
- <grizzly_version>2.1.4</grizzly_version>
+ <grizzly_version>2.4.4</grizzly_version>
<httpclient_version>4.5.3</httpclient_version>
<httpcore_version>4.4.6</httpcore_version>
<fastjson_version>1.2.70</fastjson_version>
@@ -129,9 +129,9 @@
<rs_api_version>2.0</rs_api_version>
<resteasy_version>3.0.19.Final</resteasy_version>
<tomcat_embed_version>8.5.31</tomcat_embed_version>
- <jetcd_version>0.4.1</jetcd_version>
+ <jetcd_version>0.5.3</jetcd_version>
<nacos_version>1.3.1</nacos_version>
- <grpc.version>1.22.1</grpc.version>
+ <grpc.version>1.31.1</grpc.version>
<!-- Log libs -->
<slf4j_version>1.7.25</slf4j_version>
<jcl_version>1.2</jcl_version>
@@ -145,13 +145,16 @@
<!-- Eureka -->
<eureka.version>1.9.12</eureka.version>
+ <!-- Fabric8 for Kubernetes -->
+ <fabric8_kubernetes_version>4.10.3</fabric8_kubernetes_version>
+
<!-- Alibaba -->
<alibaba_spring_context_support_version>1.0.8</alibaba_spring_context_support_version>
<jaxb_version>2.2.7</jaxb_version>
<activation_version>1.2.0</activation_version>
<test_container_version>1.11.2</test_container_version>
- <etcd_launcher_version>0.3.0</etcd_launcher_version>
+ <etcd_launcher_version>0.5.3</etcd_launcher_version>
<hessian_lite_version>3.2.8</hessian_lite_version>
<swagger_version>1.5.19</swagger_version>
<spring_test_version>4.3.16.RELEASE</spring_test_version>
@@ -468,11 +471,6 @@
</exclusion>
</exclusions>
</dependency>
- <dependency>
- <groupId>io.etcd</groupId>
- <artifactId>jetcd-launcher</artifactId>
- <version>${jetcd_version}</version>
- </dependency>
<!-- Log libs -->
<dependency>
<groupId>org.slf4j</groupId>
@@ -703,6 +701,17 @@
<artifactId>grpc-grpclb</artifactId>
<version>${grpc.version}</version>
</dependency>
+ <dependency>
+ <groupId>io.fabric8</groupId>
+ <artifactId>kubernetes-client</artifactId>
+ <version>${fabric8_kubernetes_version}</version>
+ </dependency>
+ <dependency>
+ <groupId>io.fabric8</groupId>
+ <artifactId>kubernetes-server-mock</artifactId>
+ <scope>test</scope>
+ <version>${fabric8_kubernetes_version}</version>
+ </dependency>
</dependencies>
</dependencyManagement>
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/CompositeServiceNameMapping.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/CompositeServiceNameMapping.java
deleted file mode 100644
index 9ad130b..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/CompositeServiceNameMapping.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * 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.apache.dubbo.metadata;
-
-
-import org.apache.dubbo.common.URL;
-
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-
-import static java.util.Collections.emptySet;
-import static java.util.Collections.unmodifiableSet;
-import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
-import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty;
-
-/**
- * The composite implementation of {@link ServiceNameMapping}
- *
- * @see ParameterizedServiceNameMapping
- * @see PropertiesFileServiceNameMapping
- * @see DynamicConfigurationServiceNameMapping
- * @since 2.7.8
- */
-public class CompositeServiceNameMapping implements ServiceNameMapping {
-
- private volatile List<ServiceNameMapping> serviceNameMappings;
-
- private List<ServiceNameMapping> getServiceNameMappings() {
- if (this.serviceNameMappings == null) {
- synchronized (this) {
- if (this.serviceNameMappings == null) {
- Set<ServiceNameMapping> serviceNameMappings = loadAllServiceNameMappings();
-
- removeSelf(serviceNameMappings);
-
- this.serviceNameMappings = new LinkedList<>(serviceNameMappings);
- }
- }
- }
- return this.serviceNameMappings;
- }
-
- private Set<ServiceNameMapping> loadAllServiceNameMappings() {
- return getExtensionLoader(ServiceNameMapping.class).getSupportedExtensionInstances();
- }
-
- private void removeSelf(Set<ServiceNameMapping> serviceNameMappings) {
- Iterator<ServiceNameMapping> iterator = serviceNameMappings.iterator();
- while (iterator.hasNext()) {
- ServiceNameMapping serviceNameMapping = iterator.next();
- if (this.getClass().equals(serviceNameMapping.getClass())) {
- iterator.remove(); // Remove self
- }
- }
- }
-
- @Override
- public void map(URL exportedURL) {
- List<ServiceNameMapping> serviceNameMappings = getServiceNameMappings();
- serviceNameMappings.forEach(serviceNameMapping -> serviceNameMapping.map(exportedURL));
- }
-
- @Override
- public Set<String> get(URL subscribedURL) {
- List<ServiceNameMapping> serviceNameMappings = getServiceNameMappings();
- Set<String> serviceNames = null;
- for (ServiceNameMapping serviceNameMapping : serviceNameMappings) {
- serviceNames = serviceNameMapping.get(subscribedURL);
- if (isNotEmpty(serviceNames)) {
- break;
- }
- }
- return serviceNames == null ? emptySet() : unmodifiableSet(serviceNames);
- }
-
- @Override
- public int getPriority() {
- return MIN_PRIORITY;
- }
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DefaultMetadataParamsFilter.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DefaultMetadataParamsFilter.java
new file mode 100644
index 0000000..667c7cd
--- /dev/null
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DefaultMetadataParamsFilter.java
@@ -0,0 +1,55 @@
+/*
+ * 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.apache.dubbo.metadata;
+
+import org.apache.dubbo.common.extension.Activate;
+
+import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
+import static org.apache.dubbo.remoting.Constants.CODEC_KEY;
+import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY;
+import static org.apache.dubbo.remoting.Constants.EXCHANGER_KEY;
+import static org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY;
+import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY;
+import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
+import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
+import static org.apache.dubbo.rpc.cluster.Constants.WARMUP_KEY;
+import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY;
+
+@Activate
+public class DefaultMetadataParamsFilter implements MetadataParamsFilter {
+ @Override
+ public String[] serviceParamsIncluded() {
+ return new String[]{
+ CODEC_KEY, EXCHANGER_KEY, SERIALIZATION_KEY, CLUSTER_KEY, CONNECTIONS_KEY, DEPRECATED_KEY,
+ GROUP_KEY, LOADBALANCE_KEY, MOCK_KEY, PATH_KEY, TIMEOUT_KEY, TOKEN_KEY, VERSION_KEY, WARMUP_KEY,
+ WEIGHT_KEY, DUBBO_VERSION_KEY, RELEASE_KEY
+ };
+ }
+
+
+ @Override
+ public String[] instanceParamsIncluded() {
+ return new String[0];
+ }
+}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java
index 2a04cb7..12d6665 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java
@@ -28,17 +28,12 @@ import java.util.Set;
import static java.lang.String.valueOf;
import static java.util.Arrays.asList;
-import static org.apache.dubbo.common.config.configcenter.DynamicConfiguration.getDynamicConfiguration;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
-import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty;
-import static org.apache.dubbo.common.utils.StringUtils.SLASH;
import static org.apache.dubbo.rpc.model.ApplicationModel.getName;
/**
* The {@link ServiceNameMapping} implementation based on {@link DynamicConfiguration}
- *
- * @since 2.7.5
*/
public class DynamicConfigurationServiceNameMapping implements ServiceNameMapping {
@@ -48,32 +43,27 @@ public class DynamicConfigurationServiceNameMapping implements ServiceNameMappin
private final Logger logger = LoggerFactory.getLogger(getClass());
- /**
- * The priority of {@link DynamicConfigurationServiceNameMapping} is
- * lower than {@link ParameterizedServiceNameMapping}
- */
- static final int PRIORITY = PropertiesFileServiceNameMapping.PRIORITY + 1;
-
@Override
- public void map(URL exportedURL) {
-
- String serviceInterface = exportedURL.getServiceInterface();
+ public void map(URL url) {
+ String serviceInterface = url.getServiceInterface();
+ String group = url.getParameter(GROUP_KEY);
+ String version = url.getParameter(VERSION_KEY);
+ String protocol = url.getProtocol();
if (IGNORED_SERVICE_INTERFACES.contains(serviceInterface)) {
return;
}
- String group = exportedURL.getParameter(GROUP_KEY);
- String version = exportedURL.getParameter(VERSION_KEY);
- String protocol = exportedURL.getProtocol();
+ DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration();
// the Dubbo Service Key as group
// the service(application) name as key
// It does matter whatever the content is, we just need a record
String key = getName();
String content = valueOf(System.currentTimeMillis());
+
execute(() -> {
- getDynamicConfiguration().publishConfig(key, buildGroup(serviceInterface, group, version, protocol), content);
+ dynamicConfiguration.publishConfig(key, ServiceNameMapping.buildGroup(serviceInterface, group, version, protocol), content);
if (logger.isInfoEnabled()) {
logger.info(String.format("Dubbo service[%s] mapped to interface name[%s].",
group, serviceInterface, group));
@@ -82,33 +72,22 @@ public class DynamicConfigurationServiceNameMapping implements ServiceNameMappin
}
@Override
- public Set<String> get(URL subscribedURL) {
-
- String serviceInterface = subscribedURL.getServiceInterface();
- String group = subscribedURL.getParameter(GROUP_KEY);
- String version = subscribedURL.getParameter(VERSION_KEY);
- String protocol = subscribedURL.getProtocol();
+ public Set<String> getAndListen(URL url, MappingListener mappingListener) {
+ String serviceInterface = url.getServiceInterface();
+ String group = url.getParameter(GROUP_KEY);
+ String version = url.getParameter(VERSION_KEY);
+ String protocol = url.getProtocol();
+ DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration();
Set<String> serviceNames = new LinkedHashSet<>();
execute(() -> {
- Set<String> keys = getDynamicConfiguration().getConfigKeys(buildGroup(serviceInterface, group, version, protocol));
- if (isNotEmpty(keys)) {
- serviceNames.addAll(keys);
- }
+ Set<String> keys = dynamicConfiguration
+ .getConfigKeys(ServiceNameMapping.buildGroup(serviceInterface, group, version, protocol));
+ serviceNames.addAll(keys);
});
return Collections.unmodifiableSet(serviceNames);
}
- protected static String buildGroup(String serviceInterface, String group, String version, String protocol) {
- // the issue : https://github.com/apache/dubbo/issues/4671
- // StringBuilder groupBuilder = new StringBuilder(serviceInterface)
- // .append(KEY_SEPARATOR).append(defaultString(group))
- // .append(KEY_SEPARATOR).append(defaultString(version))
- // .append(KEY_SEPARATOR).append(defaultString(protocol));
- // return groupBuilder.toString();
- return DEFAULT_MAPPING_GROUP + SLASH + serviceInterface;
- }
-
private void execute(Runnable runnable) {
try {
runnable.run();
@@ -118,9 +97,4 @@ public class DynamicConfigurationServiceNameMapping implements ServiceNameMappin
}
}
}
-
- @Override
- public int getPriority() {
- return PRIORITY;
- }
}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingChangedEvent.java
similarity index 65%
copy from dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java
copy to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingChangedEvent.java
index 45fc8e0..91a25f4 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingChangedEvent.java
@@ -16,21 +16,26 @@
*/
package org.apache.dubbo.metadata;
-import org.apache.dubbo.metadata.store.InMemoryWritableMetadataService;
+import java.util.Set;
-import org.junit.jupiter.api.Test;
+public class MappingChangedEvent {
+ private String serviceKey;
+ private Set<String> apps;
-import static org.junit.jupiter.api.Assertions.assertEquals;
+ public String getServiceKey() {
+ return serviceKey;
+ }
-/**
- * {@link WritableMetadataService} Test
- *
- * @since 2.7.5
- */
-public class LocalMetadataServiceTest {
+ public void setServiceKey(String serviceKey) {
+ this.serviceKey = serviceKey;
+ }
- @Test
- public void testDefaultExtension() {
- assertEquals(InMemoryWritableMetadataService.class, WritableMetadataService.getDefaultExtension().getClass());
+ public Set<String> getApps() {
+ return apps;
}
+
+ public void setApps(Set<String> apps) {
+ this.apps = apps;
+ }
+
}
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/AbstractPrefixConfigurationTest.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingListener.java
similarity index 87%
rename from dubbo-common/src/test/java/org/apache/dubbo/common/config/AbstractPrefixConfigurationTest.java
rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingListener.java
index ba4b5b8..f709d75 100644
--- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/AbstractPrefixConfigurationTest.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingListener.java
@@ -14,10 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.common.config;
+package org.apache.dubbo.metadata;
-/**
- *
- */
-public class AbstractPrefixConfigurationTest {
+public interface MappingListener {
+ void onEvent(MappingChangedEvent event);
}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataConstantsTest.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataChangeListener.java
similarity index 67%
copy from dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataConstantsTest.java
copy to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataChangeListener.java
index d0c201b..4c87af5 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataConstantsTest.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataChangeListener.java
@@ -16,20 +16,20 @@
*/
package org.apache.dubbo.metadata;
-import org.junit.jupiter.api.Test;
+public interface MetadataChangeListener {
+ /**
+ * Call when metadata in provider side update <p/>
+ * Used to notify consumer to update metadata of ServiceInstance
+ *
+ * @param metadata latest metadata
+ */
+ void onEvent(String metadata);
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-/**
- * {@link MetadataConstants} Test-Cases
- *
- * @since 2.7.8
- */
-public class MetadataConstantsTest {
-
- @Test
- public void testConstants() {
- assertEquals("exported-urls", MetadataConstants.EXPORTED_URLS_TAG);
- assertEquals("subscribed-urls", MetadataConstants.SUBSCRIBED_URLS_TAG);
+ /**
+ * Echo test
+ * Used to check consumer still online
+ */
+ default String echo(String msg) {
+ return msg;
}
}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataConstants.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataConstants.java
index d670089..6bf38c9 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataConstants.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataConstants.java
@@ -16,22 +16,15 @@
*/
package org.apache.dubbo.metadata;
-public interface MetadataConstants {
- String KEY_SEPARATOR = ":";
- String DEFAULT_PATH_TAG = "metadata";
- String KEY_REVISON_PREFIX = "revision";
- String META_DATA_STORE_TAG = ".metaData";
- String SERVICE_META_DATA_STORE_TAG = ".smd";
- String CONSUMER_META_DATA_STORE_TAG = ".cmd";
-
- /**
- * @since 2.7.8
- */
- String EXPORTED_URLS_TAG = "exported-urls";
-
- /**
- * @since 2.7.8
- */
- String SUBSCRIBED_URLS_TAG = "subscribed-urls";
-
+public class MetadataConstants {
+ public static final String KEY_SEPARATOR = ":";
+ public static final String DEFAULT_PATH_TAG = "metadata";
+ public static final String KEY_REVISON_PREFIX = "revision";
+ public static final String META_DATA_STORE_TAG = ".metaData";
+ public static final String SERVICE_META_DATA_STORE_TAG = ".smd";
+ public static final String CONSUMER_META_DATA_STORE_TAG = ".cmd";
+ public static final String METADATA_PUBLISH_DELAY_KEY = "dubbo.application.metadata.delay";
+ public static final int DEFAULT_METADATA_PUBLISH_DELAY = 5000;
+ public static final String METADATA_PROXY_TIMEOUT_KEY = "dubbo.application.metadata.delay";
+ public static final int DEFAULT_METADATA_TIMEOUT_VALUE = 5000;
}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfo.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfo.java
new file mode 100644
index 0000000..6fc6239
--- /dev/null
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfo.java
@@ -0,0 +1,449 @@
+/*
+ * 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.apache.dubbo.metadata;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.compiler.support.ClassUtils;
+import org.apache.dubbo.common.extension.ExtensionLoader;
+import org.apache.dubbo.common.utils.ArrayUtils;
+import org.apache.dubbo.common.utils.CollectionUtils;
+import org.apache.dubbo.common.utils.StringUtils;
+
+import java.io.Serializable;
+import java.lang.reflect.Method;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.dubbo.common.constants.CommonConstants.DOT_SEPARATOR;
+import static org.apache.dubbo.common.constants.CommonConstants.GROUP_CHAR_SEPARATOR;
+import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
+
+public class MetadataInfo implements Serializable {
+ public static String DEFAULT_REVISION = "0";
+ private String app;
+ private String revision;
+ private Map<String, ServiceInfo> services;
+
+ // used at runtime
+ private transient Map<String, String> extendParams;
+ private transient AtomicBoolean reported = new AtomicBoolean(false);
+
+ public MetadataInfo(String app) {
+ this(app, null, null);
+ }
+
+ public MetadataInfo(String app, String revision, Map<String, ServiceInfo> services) {
+ this.app = app;
+ this.revision = revision;
+ this.services = services == null ? new HashMap<>() : services;
+ this.extendParams = new HashMap<>();
+ }
+
+ public void addService(ServiceInfo serviceInfo) {
+ if (serviceInfo == null) {
+ return;
+ }
+ this.services.put(serviceInfo.getMatchKey(), serviceInfo);
+ markChanged();
+ }
+
+ public void removeService(ServiceInfo serviceInfo) {
+ if (serviceInfo == null) {
+ return;
+ }
+ this.services.remove(serviceInfo.getMatchKey());
+ markChanged();
+ }
+
+ public void removeService(String key) {
+ if (key == null) {
+ return;
+ }
+ this.services.remove(key);
+ markChanged();
+ }
+
+ public String calAndGetRevision() {
+ if (revision != null && hasReported()) {
+ return revision;
+ }
+
+ if (CollectionUtils.isEmptyMap(services)) {
+ return DEFAULT_REVISION;
+ }
+
+ StringBuilder sb = new StringBuilder();
+ sb.append(app);
+ for (Map.Entry<String, ServiceInfo> entry : services.entrySet()) {
+ sb.append(entry.getValue().toDescString());
+ }
+ this.revision = RevisionResolver.calRevision(sb.toString());
+ return revision;
+ }
+
+ public void setRevision(String revision) {
+ this.revision = revision;
+ }
+
+ public boolean hasReported() {
+ return reported.get();
+ }
+
+ public void markReported() {
+ reported.compareAndSet(false, true);
+ }
+
+ public void markChanged() {
+ reported.compareAndSet(true, false);
+ }
+
+ public String getApp() {
+ return app;
+ }
+
+ public void setApp(String app) {
+ this.app = app;
+ }
+
+ public Map<String, ServiceInfo> getServices() {
+ return services;
+ }
+
+ public void setServices(Map<String, ServiceInfo> services) {
+ this.services = services;
+ }
+
+ public ServiceInfo getServiceInfo(String serviceKey) {
+ return services.get(serviceKey);
+ }
+
+ public Map<String, String> getExtendParams() {
+ return extendParams;
+ }
+
+ public String getParameter(String key, String serviceKey) {
+ ServiceInfo serviceInfo = services.get(serviceKey);
+ if (serviceInfo == null) {
+ return null;
+ }
+ return serviceInfo.getParameter(key);
+ }
+
+ public Map<String, String> getParameters(String serviceKey) {
+ ServiceInfo serviceInfo = services.get(serviceKey);
+ if (serviceInfo == null) {
+ return Collections.emptyMap();
+ }
+ return serviceInfo.getAllParams();
+ }
+
+ @Override
+ public String toString() {
+ return "metadata{" +
+ "app='" + app + "'," +
+ "revision='" + revision + "'," +
+ "services=" + services +
+ "}";
+ }
+
+ public static class ServiceInfo implements Serializable {
+ private static ExtensionLoader<MetadataParamsFilter> loader = ExtensionLoader.getExtensionLoader(MetadataParamsFilter.class);
+ private String name;
+ private String group;
+ private String version;
+ private String protocol;
+ private String path; // most of the time, path is the same with the interface name.
+ private Map<String, String> params;
+
+ // params configuried on consumer side,
+ private transient Map<String, String> consumerParams;
+ // cached method params
+ private transient Map<String, Map<String, String>> methodParams;
+ private transient Map<String, Map<String, String>> consumerMethodParams;
+ // cached numbers
+ private transient Map<String, Number> numbers;
+ private transient Map<String, Map<String, Number>> methodNumbers;
+ // service + group + version
+ private transient String serviceKey;
+ // service + group + version + protocol
+ private transient String matchKey;
+
+ private transient URL url;
+
+ public ServiceInfo() {
+ }
+
+ public ServiceInfo(URL url) {
+ this(url.getServiceInterface(), url.getParameter(GROUP_KEY), url.getParameter(VERSION_KEY), url.getProtocol(), url.getPath(), null);
+
+ this.url = url;
+ Map<String, String> params = new HashMap<>();
+ List<MetadataParamsFilter> filters = loader.getActivateExtension(url, "params-filter");
+ for (MetadataParamsFilter filter : filters) {
+ String[] paramsIncluded = filter.serviceParamsIncluded();
+ if (ArrayUtils.isNotEmpty(paramsIncluded)) {
+ for (String p : paramsIncluded) {
+ String value = url.getParameter(p);
+ if (StringUtils.isNotEmpty(value) && params.get(p) == null) {
+ params.put(p, value);
+ }
+ String[] methods = url.getParameter(METHODS_KEY, (String[]) null);
+ if (methods != null) {
+ for (String method : methods) {
+ String mValue = url.getMethodParameterStrict(method, p);
+ if (StringUtils.isNotEmpty(mValue)) {
+ params.put(method + DOT_SEPARATOR + p, mValue);
+ }
+ }
+ }
+ }
+ }
+ }
+ this.params = params;
+ }
+
+ public ServiceInfo(String name, String group, String version, String protocol, String path, Map<String, String> params) {
+ this.name = name;
+ this.group = group;
+ this.version = version;
+ this.protocol = protocol;
+ this.path = path;
+ this.params = params == null ? new HashMap<>() : params;
+
+ this.serviceKey = URL.buildKey(name, group, version);
+ this.matchKey = buildMatchKey();
+ }
+
+ public String getMatchKey() {
+ if (matchKey != null) {
+ return matchKey;
+ }
+ buildMatchKey();
+ return matchKey;
+ }
+
+ private String buildMatchKey() {
+ matchKey = getServiceKey();
+ if (StringUtils.isNotEmpty(protocol)) {
+ matchKey = getServiceKey() + GROUP_CHAR_SEPARATOR + protocol;
+ }
+ return matchKey;
+ }
+
+ public String getServiceKey() {
+ if (serviceKey != null) {
+ return serviceKey;
+ }
+ this.serviceKey = URL.buildKey(name, group, version);
+ return serviceKey;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getGroup() {
+ return group;
+ }
+
+ public void setGroup(String group) {
+ this.group = group;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ public Map<String, String> getParams() {
+ if (params == null) {
+ return Collections.emptyMap();
+ }
+ return params;
+ }
+
+ public void setParams(Map<String, String> params) {
+ this.params = params;
+ }
+
+ public Map<String, String> getAllParams() {
+ if (consumerParams != null) {
+ Map<String, String> allParams = new HashMap<>((int) ((params.size() + consumerParams.size()) / 0.75f + 1));
+ allParams.putAll(params);
+ allParams.putAll(consumerParams);
+ return allParams;
+ }
+ return params;
+ }
+
+ public String getParameter(String key) {
+ if (consumerParams != null) {
+ String value = consumerParams.get(key);
+ if (value != null) {
+ return value;
+ }
+ }
+ return params.get(key);
+ }
+
+ public String getMethodParameter(String method, String key, String defaultValue) {
+ if (methodParams == null) {
+ methodParams = URL.toMethodParameters(params);
+ consumerMethodParams = URL.toMethodParameters(consumerParams);
+ }
+
+ String value = getMethodParameter(method, key, consumerMethodParams);
+ if (value != null) {
+ return value;
+ }
+ value = getMethodParameter(method, key, methodParams);
+ return value == null ? defaultValue : value;
+ }
+
+ private String getMethodParameter(String method, String key, Map<String, Map<String, String>> map) {
+ Map<String, String> keyMap = map.get(method);
+ String value = null;
+ if (keyMap != null) {
+ value = keyMap.get(key);
+ }
+ if (StringUtils.isEmpty(value)) {
+ value = getParameter(key);
+ }
+ return value;
+ }
+
+ public boolean hasMethodParameter(String method, String key) {
+ String value = this.getMethodParameter(method, key, (String) null);
+ return StringUtils.isNotEmpty(value);
+ }
+
+ public boolean hasMethodParameter(String method) {
+ if (methodParams == null) {
+ methodParams = URL.toMethodParameters(params);
+ consumerMethodParams = URL.toMethodParameters(consumerParams);
+ }
+
+ return consumerMethodParams.containsKey(method) || methodParams.containsKey(method);
+ }
+
+ public String toDescString() {
+ return this.getMatchKey() + getMethodSignaturesString() + getParams();
+ }
+
+ private String getMethodSignaturesString() {
+ SortedSet<String> methodStrings = new TreeSet();
+
+ Method[] methods = ClassUtils.forName(name).getMethods();
+ for (Method method : methods) {
+ methodStrings.add(method.toString());
+ }
+ return methodStrings.toString();
+ }
+
+ public void addParameter(String key, String value) {
+ if (consumerParams != null) {
+ this.consumerParams.put(key, value);
+ }
+ }
+
+ public void addParameterIfAbsent(String key, String value) {
+ if (consumerParams != null) {
+ this.consumerParams.putIfAbsent(key, value);
+ }
+ }
+
+ public void addConsumerParams(Map<String, String> params) {
+ // copy once for one service subscription
+ if (consumerParams == null) {
+ consumerParams = new HashMap<>(params);
+ }
+ }
+
+ public Map<String, Number> getNumbers() {
+ // concurrent initialization is tolerant
+ if (numbers == null) {
+ numbers = new ConcurrentHashMap<>();
+ }
+ return numbers;
+ }
+
+ public Map<String, Map<String, Number>> getMethodNumbers() {
+ if (methodNumbers == null) { // concurrent initialization is tolerant
+ methodNumbers = new ConcurrentHashMap<>();
+ }
+ return methodNumbers;
+ }
+
+ public URL getUrl() {
+ return url;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (!(obj instanceof ServiceInfo)) {
+ return false;
+ }
+
+ ServiceInfo serviceInfo = (ServiceInfo) obj;
+ return this.getMatchKey().equals(serviceInfo.getMatchKey()) && this.getParams().equals(serviceInfo.getParams());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getMatchKey(), getParams());
+ }
+
+ @Override
+ public String toString() {
+ return "service{" +
+ "name='" + name + "'," +
+ "group='" + group + "'," +
+ "version='" + version + "'," +
+ "protocol='" + protocol + "'," +
+ "params=" + params + "," +
+ "consumerParams=" + consumerParams +
+ "}";
+ }
+ }
+}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataConstantsTest.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataParamsFilter.java
similarity index 67%
copy from dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataConstantsTest.java
copy to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataParamsFilter.java
index d0c201b..542acb1 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataConstantsTest.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataParamsFilter.java
@@ -16,20 +16,22 @@
*/
package org.apache.dubbo.metadata;
-import org.junit.jupiter.api.Test;
+import org.apache.dubbo.common.extension.SPI;
-import static org.junit.jupiter.api.Assertions.assertEquals;
+@SPI
+public interface MetadataParamsFilter {
-/**
- * {@link MetadataConstants} Test-Cases
- *
- * @since 2.7.8
- */
-public class MetadataConstantsTest {
+ /**
+ * params that need to be sent to metadata center
+ *
+ * @return arrays of keys
+ */
+ String[] serviceParamsIncluded();
- @Test
- public void testConstants() {
- assertEquals("exported-urls", MetadataConstants.EXPORTED_URLS_TAG);
- assertEquals("subscribed-urls", MetadataConstants.SUBSCRIBED_URLS_TAG);
- }
+ /**
+ * params that need to be sent to registry center
+ *
+ * @return arrays of keys
+ */
+ String[] instanceParamsIncluded();
}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataService.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataService.java
index 660ac42..4971d72 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataService.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataService.java
@@ -19,6 +19,7 @@ package org.apache.dubbo.metadata;
import org.apache.dubbo.common.URL;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
@@ -177,6 +178,10 @@ public interface MetadataService {
*/
String getServiceDefinition(String serviceKey);
+ MetadataInfo getMetadataInfo(String revision);
+
+ Map<String, MetadataInfo> getMetadataInfos();
+
/**
* Is the {@link URL} for the {@link MetadataService} or not?
*
@@ -223,4 +228,46 @@ public interface MetadataService {
static SortedSet<String> toSortedStrings(Stream<URL> stream) {
return unmodifiableSortedSet(stream.map(URL::toFullString).collect(TreeSet::new, Set::add, Set::addAll));
}
+
+ /**
+ * Export Metadata in Service Instance of Service Discovery
+ * <p>
+ * Used for consumer to get Service Instance Metadata
+ * if Registry is unsupported with publishing metadata
+ *
+ * @param metadata {@link Map} of provider Service Instance Metadata
+ * @since 3.0
+ */
+ default void exportServiceDiscoveryMetadata(String metadata) {
+ throw new UnsupportedOperationException("This operation is not supported for consumer.");
+ }
+
+ /**
+ * Get all Metadata listener from local
+ * <p>
+ * Used for consumer to get Service Instance Metadata
+ * if Registry is unsupported with publishing metadata
+ *
+ * @return {@link Map} of {@link MetadataChangeListener}
+ * @since 3.0
+ */
+ default Map<String, MetadataChangeListener> getMetadataChangeListenerMap() {
+ throw new UnsupportedOperationException("This operation is not supported for consumer.");
+ }
+
+ /**
+ * 1. Fetch Metadata in Service Instance of Service Discovery
+ * 2. Add a metadata change listener
+ * <p>
+ * Used for consumer to get Service Instance Metadata
+ * if Registry is unsupported with publishing metadata
+ *
+ * @param consumerId consumerId
+ * @param listener {@link MetadataChangeListener} used to notify event
+ * @return {@link Map} of provider Service Instance Metadata
+ * @since 3.0
+ */
+ default String getAndListenServiceDiscoveryMetadata(String consumerId, MetadataChangeListener listener) {
+ throw new UnsupportedOperationException("This operation is not supported for consumer.");
+ }
}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/PropertiesFileServiceNameMapping.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/PropertiesFileServiceNameMapping.java
deleted file mode 100644
index 7870895..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/PropertiesFileServiceNameMapping.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * 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.apache.dubbo.metadata;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.config.Configuration;
-import org.apache.dubbo.common.constants.CommonConstants;
-import org.apache.dubbo.common.utils.ClassUtils;
-import org.apache.dubbo.common.utils.PathUtils;
-import org.apache.dubbo.common.utils.StringUtils;
-import org.apache.dubbo.rpc.model.ApplicationModel;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.Enumeration;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-
-import static java.lang.String.format;
-import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVICE_NAME_MAPPING_PROPERTIES_PATH;
-import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_NAME_MAPPING_PROPERTIES_FILE_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
-import static org.apache.dubbo.common.utils.StringUtils.SLASH;
-import static org.apache.dubbo.metadata.MetadataConstants.KEY_SEPARATOR;
-
-/**
- * The externalized {@link Properties} file implementation of {@link ServiceNameMapping},
- * the default properties class path is
- * {@link CommonConstants#DEFAULT_SERVICE_NAME_MAPPING_PROPERTIES_PATH "/META-INF/dubbo/service-name-mapping.properties"},
- * whose format as following:
- * <pre>
- * dubbo\:com.acme.Interface1\:default = Service1
- * thirft\:com.acme.InterfaceX = Service1,Service2
- * rest\:com.acme.interfaceN = Service3
- * </pre>
- * <p>
- * THe search path could be configured by the externalized property {@link CommonConstants#SERVICE_NAME_MAPPING_PROPERTIES_FILE_KEY}
- *
- * @see ReadOnlyServiceNameMapping
- * @see ParameterizedServiceNameMapping
- * @since 2.7.8
- */
-public class PropertiesFileServiceNameMapping extends ReadOnlyServiceNameMapping {
-
- /**
- * The priority of {@link PropertiesFileServiceNameMapping} is
- * lower than {@link ParameterizedServiceNameMapping}
- */
- static final int PRIORITY = ParameterizedServiceNameMapping.PRIORITY + 1;
-
-
- private final List<Properties> propertiesList;
-
- public PropertiesFileServiceNameMapping() {
- this.propertiesList = loadPropertiesList();
- }
-
- @Override
- public Set<String> get(URL subscribedURL) {
- String propertyKey = getPropertyKey(subscribedURL);
- String propertyValue = null;
-
- for (Properties properties : propertiesList) {
- propertyValue = properties.getProperty(propertyKey);
- if (propertyValue != null) {
- break;
- }
- }
-
- return getValue(propertyValue);
- }
-
- private String getPropertyKey(URL url) {
- String protocol = url.getProtocol();
- String serviceInterface = url.getServiceInterface();
- // Optional
- String group = url.getParameter(GROUP_KEY);
- String version = url.getParameter(VERSION_KEY);
-
- StringBuilder propertyKeyBuilder = new StringBuilder(protocol)
- .append(KEY_SEPARATOR)
- .append(serviceInterface);
-
- appendIfPresent(propertyKeyBuilder, group);
- appendIfPresent(propertyKeyBuilder, version);
-
- return propertyKeyBuilder.toString();
- }
-
- private void appendIfPresent(StringBuilder builder, String value) {
- if (!StringUtils.isBlank(value)) {
- builder.append(KEY_SEPARATOR).append(value);
- }
- }
-
- private List<Properties> loadPropertiesList() {
- List<Properties> propertiesList = new LinkedList<>();
- String propertiesPath = getPropertiesPath();
- try {
- Enumeration<java.net.URL> resources = ClassUtils.getClassLoader().getResources(propertiesPath);
- while (resources.hasMoreElements()) {
- java.net.URL resource = resources.nextElement();
- InputStream inputStream = resource.openStream();
- Properties properties = new Properties();
- properties.load(new InputStreamReader(inputStream, "UTF-8"));
- propertiesList.add(properties);
- }
- } catch (IOException e) {
- if (logger.isErrorEnabled()) {
- logger.error(format("The path of ServiceNameMapping's Properties file[path : %s] can't be loaded", propertiesPath), e);
- }
- }
- return propertiesList;
- }
-
- private String getPropertiesPath() {
- Configuration configuration = ApplicationModel.getEnvironment().getConfiguration();
- String propertyPath = configuration.getString(SERVICE_NAME_MAPPING_PROPERTIES_FILE_KEY, DEFAULT_SERVICE_NAME_MAPPING_PROPERTIES_PATH);
- propertyPath = PathUtils.normalize(propertyPath);
- if (propertyPath.startsWith(SLASH)) {
- propertyPath = propertyPath.substring(SLASH.length());
- }
- return propertyPath;
- }
-
- @Override
- public int getPriority() {
- return PRIORITY;
- }
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ReadOnlyServiceNameMapping.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ReadOnlyServiceNameMapping.java
deleted file mode 100644
index 58035d3..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ReadOnlyServiceNameMapping.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.apache.dubbo.metadata;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.logger.Logger;
-import org.apache.dubbo.common.logger.LoggerFactory;
-
-import java.util.Set;
-
-import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR_CHAR;
-import static org.apache.dubbo.common.utils.StringUtils.splitToSet;
-
-/**
- * Read-Only implementation of {@link ServiceNameMapping}
- *
- * @since 2.7.8
- */
-public abstract class ReadOnlyServiceNameMapping implements ServiceNameMapping {
-
- protected final Logger logger = LoggerFactory.getLogger(getClass());
-
- @Override
- public void map(URL exportedURL) {
- // DO NOTING for mapping
- }
-
- protected Set<String> getValue(String rawValue) {
- return splitToSet(rawValue, COMMA_SEPARATOR_CHAR, true);
- }
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/RevisionResolver.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/RevisionResolver.java
new file mode 100644
index 0000000..f8ebd3b
--- /dev/null
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/RevisionResolver.java
@@ -0,0 +1,59 @@
+/*
+ * 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.apache.dubbo.metadata;
+
+import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+public class RevisionResolver {
+ private static final Logger logger = LoggerFactory.getLogger(RevisionResolver.class);
+ private static char hexDigits[] = {
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
+ };
+
+ private static MessageDigest mdInst;
+
+ static {
+ try {
+ mdInst = MessageDigest.getInstance("MD5");
+ } catch (NoSuchAlgorithmException e) {
+ logger.error("Failed to calculate metadata revision", e);
+ }
+ }
+
+ public static String calRevision(String metadata) {
+ mdInst.update(metadata.getBytes(UTF_8));
+ byte[] md5 = mdInst.digest();
+
+ int j = md5.length;
+ char str[] = new char[j * 2];
+ int k = 0;
+ for (int i = 0; i < j; i++) {
+ byte byte0 = md5[i];
+ str[k++] = hexDigits[byte0 >>> 4 & 0xf];
+ str[k++] = hexDigits[byte0 & 0xf];
+ }
+ return new String(str);
+ }
+
+
+}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java
index 46f657d..f08a748 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java
@@ -18,65 +18,33 @@ package org.apache.dubbo.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
-import org.apache.dubbo.common.lang.Prioritized;
import java.util.Set;
+import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_MAPPING_TYPE;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
+import static org.apache.dubbo.common.utils.StringUtils.SLASH;
+import static org.apache.dubbo.metadata.DynamicConfigurationServiceNameMapping.DEFAULT_MAPPING_GROUP;
/**
* The interface for Dubbo service name Mapping
*
* @since 2.7.5
*/
-@SPI("default")
-public interface ServiceNameMapping extends Prioritized {
+@SPI("config")
+public interface ServiceNameMapping {
/**
* Map the specified Dubbo service interface, group, version and protocol to current Dubbo service name
- *
- * @param serviceInterface the class name of Dubbo service interface
- * @param group the group of Dubbo service interface (optional)
- * @param version the version of Dubbo service interface version (optional)
- * @param protocol the protocol of Dubbo service interface exported (optional)
- * @deprecated 2.7.8 This method will be removed since 3.0
- */
- @Deprecated
- default void map(String serviceInterface, String group, String version, String protocol) {
- throw new UnsupportedOperationException("This method has been deprecated and should not be invoked!");
- }
-
- /**
- * Map the specified Dubbo service {@link URL} to current Dubbo service name
- *
- * @param exportedURL the {@link URL} that the Dubbo Provider exported
- * @since 2.7.8
*/
- void map(URL exportedURL);
+ void map(URL url);
/**
* Get the service names from the specified Dubbo service interface, group, version and protocol
*
- * @param serviceInterface the class name of Dubbo service interface
- * @param group the group of Dubbo service interface (optional)
- * @param version the version of Dubbo service interface version (optional)
- * @param protocol the protocol of Dubbo service interface exported (optional)
- * @return non-null {@link Set}
- * @deprecated 2.7.8 This method will be removed since 3.0
+ * @return
*/
- @Deprecated
- default Set<String> get(String serviceInterface, String group, String version, String protocol) {
- throw new UnsupportedOperationException("This method has been deprecated and should not be invoked!");
- }
-
- /**
- * Get the service names from the subscribed Dubbo service {@link URL}
- *
- * @param subscribedURL the {@link URL} that the Dubbo consumer subscribed
- * @return non-null {@link Set}
- * @since 2.7.8
- */
- Set<String> get(URL subscribedURL);
+ Set<String> getAndListen(URL url, MappingListener mappingListener);
/**
* Get the default extension of {@link ServiceNameMapping}
@@ -87,4 +55,18 @@ public interface ServiceNameMapping extends Prioritized {
static ServiceNameMapping getDefaultExtension() {
return getExtensionLoader(ServiceNameMapping.class).getDefaultExtension();
}
+
+ static ServiceNameMapping getExtension(String name) {
+ return getExtensionLoader(ServiceNameMapping.class).getExtension(name == null ? CONFIG_MAPPING_TYPE : name);
+ }
+
+ static String buildGroup(String serviceInterface, String group, String version, String protocol) {
+ // the issue : https://github.com/apache/dubbo/issues/4671
+ // StringBuilder groupBuilder = new StringBuilder(serviceInterface)
+ // .append(KEY_SEPARATOR).append(defaultString(group))
+ // .append(KEY_SEPARATOR).append(defaultString(version))
+ // .append(KEY_SEPARATOR).append(defaultString(protocol));
+ // return groupBuilder.toString();
+ return DEFAULT_MAPPING_GROUP + SLASH + serviceInterface;
+ }
}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/URLRevisionResolver.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/URLRevisionResolver.java
deleted file mode 100644
index f3fe79c..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/URLRevisionResolver.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * 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.apache.dubbo.metadata;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.compiler.support.ClassUtils;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import java.util.stream.Collectors;
-import java.util.stream.StreamSupport;
-
-import static java.util.Collections.emptyList;
-import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
-import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty;
-
-/**
- * A class to resolve the version from {@link URL URLs}
- *
- * @revised 2.7.8 repackage and refactor
- * @since 2.7.5
- */
-public class URLRevisionResolver {
-
- /**
- * @since 2.7.8
- */
- public static final String UNKNOWN_REVISION = "X";
-
- /**
- * @since 2.7.8
- */
- public static final URLRevisionResolver INSTANCE = new URLRevisionResolver();
-
- /**
- * Resolve revision as {@link String} from the specified the {@link URL#toFullString() strings} presenting the {@link URL URLs}.
- *
- * @param url one {@link URL}
- * @param others the others {@link URL}
- * @return non-null
- * @since 2.7.8
- */
- public String resolve(String url, String... others) {
- List<String> urls = new ArrayList<>(others.length + 1);
- urls.add(url);
- urls.addAll(Arrays.asList(others));
- return resolve(urls);
- }
-
- /**
- * Resolve revision as {@link String}
- *
- * @param urls {@link URL#toFullString() strings} presenting the {@link URL URLs}
- * @return non-null
- * @revised 2.7.8 refactor the parameter as the super interface (from Collection to Iterable)
- */
- public String resolve(Iterable<String> urls) {
- List<URL> urlsList = toURLsList(urls);
- return resolve(urlsList);
- }
-
- /**
- * Resolve revision as {@link String} from the specified the {@link URL URLs}.
- *
- * @param urls the {@link URL URLs}
- * @return non-null
- * @since 2.7.8
- */
- public String resolve(Collection<URL> urls) {
-
- if (isEmpty(urls)) {
- return UNKNOWN_REVISION;
- }
-
- SortedSet<String> methodSignatures = resolveMethodSignatures(urls);
-
- SortedSet<String> urlParameters = resolveURLParameters(urls);
-
- SortedSet<String> values = new TreeSet<>(methodSignatures);
-
- values.addAll(urlParameters);
-
- return values.stream()
- .map(this::hashCode) // generate Long hashCode
- .reduce(Long::sum) // sum hashCode
- .map(Long::toHexString) // Using Hex for the shorten content
- .orElse(UNKNOWN_REVISION); // NO_REVISION as default
- }
-
- private List<URL> toURLsList(Iterable<String> urls) {
- if (urls == null) {
- return emptyList();
- }
- return StreamSupport.
- stream(urls.spliterator(), false)
- .map(URL::valueOf) // String to URL
- .filter(url -> isNotMetadataService(url.getServiceInterface())) // filter not MetadataService interface
- .collect(Collectors.toList());
- }
-
- private SortedSet<String> resolveMethodSignatures(Collection<URL> urls) {
- return urls.stream()
- .map(URL::getServiceInterface) // get the service interface
- .map(ClassUtils::forName) // load business interface class
- .map(Class::getMethods) // get all public methods from business interface
- .map(Arrays::asList) // Array to List
- .flatMap(Collection::stream) // flat Stream<Stream> to be Stream
- .map(Object::toString) // Method to String
- .collect(TreeSet::new, Set::add, Set::addAll); // sort and remove the duplicate
- }
-
- private SortedSet<String> resolveURLParameters(Collection<URL> urls) {
- return urls.stream()
- .map(url -> url.removeParameter(PID_KEY))
- .map(url -> url.removeParameter(TIMESTAMP_KEY))
- .map(URL::toParameterString)
- .collect(TreeSet::new, Set::add, Set::addAll); // sort and remove the duplicate
- }
-
- private long hashCode(String value) {
- long h = 0;
- char[] chars = value.toCharArray();
- for (int i = 0; i < chars.length; i++) {
- h = 31L * h + chars[i];
- }
- return h;
- }
-
- private boolean isNotMetadataService(String serviceInterface) {
- return !MetadataService.class.getName().equals(serviceInterface);
- }
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/WritableMetadataService.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/WritableMetadataService.java
index 6cde356..b870fff 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/WritableMetadataService.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/WritableMetadataService.java
@@ -19,11 +19,9 @@ package org.apache.dubbo.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.SPI;
-import org.apache.dubbo.metadata.store.InMemoryWritableMetadataService;
+import org.apache.dubbo.rpc.model.ApplicationModel;
-import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
-import static org.apache.dubbo.rpc.model.ApplicationModel.getName;
/**
* Local {@link MetadataService} that extends {@link MetadataService} and provides the modification, which is used for
@@ -31,7 +29,7 @@ import static org.apache.dubbo.rpc.model.ApplicationModel.getName;
*
* @since 2.7.5
*/
-@SPI(DEFAULT_METADATA_STORAGE_TYPE)
+@SPI("default")
public interface WritableMetadataService extends MetadataService {
/**
* Gets the current Dubbo Service name
@@ -40,7 +38,7 @@ public interface WritableMetadataService extends MetadataService {
*/
@Override
default String serviceName() {
- return getName();
+ return ApplicationModel.getApplication();
}
/**
@@ -60,17 +58,6 @@ public interface WritableMetadataService extends MetadataService {
boolean unexportURL(URL url);
/**
- * fresh Exports
- *
- * @return If success , return <code>true</code>
- * @deprecated Recommend to use {@link MetadataServiceExporter} since 2.7.8
- */
- @Deprecated
- default boolean refreshMetadata(String exportedRevision, String subscribedRevision) {
- return true;
- }
-
- /**
* Subscribes a {@link URL}
*
* @param url a {@link URL}
@@ -86,19 +73,15 @@ public interface WritableMetadataService extends MetadataService {
*/
boolean unsubscribeURL(URL url);
- void publishServiceDefinition(URL url);
+ void publishServiceDefinition(URL providerUrl);
+
/**
* Get {@link ExtensionLoader#getDefaultExtension() the defautl extension} of {@link WritableMetadataService}
*
* @return non-null
- * @see InMemoryWritableMetadataService
*/
static WritableMetadataService getDefaultExtension() {
return getExtensionLoader(WritableMetadataService.class).getDefaultExtension();
}
-
- static WritableMetadataService getExtension(String name) {
- return getExtensionLoader(WritableMetadataService.class).getOrDefaultExtension(name);
- }
}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java
index 068d3a0..012c162 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java
@@ -18,143 +18,60 @@ package org.apache.dubbo.metadata.report;
import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.utils.StringUtils;
-import org.apache.dubbo.metadata.URLRevisionResolver;
+import org.apache.dubbo.metadata.MappingListener;
+import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
-import com.google.gson.Gson;
-
-import java.util.Collection;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import static java.util.Collections.emptyList;
-import static java.util.Collections.emptySortedSet;
-import static org.apache.dubbo.rpc.model.ApplicationModel.getName;
-
-/**
- * The interface to report the metadata
- *
- * @see AutoCloseable since 2.7.8
- */
-public interface MetadataReport extends AutoCloseable {
+import java.util.Set;
+public interface MetadataReport {
+ /**
+ * Service Definition -- START
+ **/
void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition);
- void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map<String, String> serviceParameterMap);
+ String getServiceDefinition(MetadataIdentifier metadataIdentifier);
/**
- * @deprecated 2.7.8
- */
- @Deprecated
- default void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {
+ * Application Metadata -- START
+ **/
+ default void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {
}
- /**
- * @deprecated 2.7.8
- */
- @Deprecated
- default void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) {
-
+ default MetadataInfo getAppMetadata(SubscriberMetadataIdentifier identifier, Map<String, String> instanceMetadata) {
+ return null;
}
/**
- * @deprecated 2.7.8
- */
- @Deprecated
- default List<String> getExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
- return emptyList();
+ * Service<-->Application Mapping -- START
+ **/
+ default Set<String> getServiceAppMapping(String serviceKey, MappingListener listener, URL url) {
+ return Collections.emptySet();
}
- void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Collection<String> urls);
-
- Collection<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier);
-
- String getServiceDefinition(MetadataIdentifier metadataIdentifier);
-
- /**
- * Save the exported {@link URL#toFullString() strings} presenting the {@link URL URLs} in bulk.
- *
- * @param exportedURLs the exported {@link URL urls}
- * @return If successful, return <code>true</code>, or <code>false</code>
- * @since 2.7.8
- */
- default boolean saveExportedURLs(SortedSet<String> exportedURLs) {
- return saveExportedURLs(getName(), exportedURLs);
+ default void registerServiceAppMapping(String serviceKey, String application, URL url) {
+ return;
}
/**
- * Save the exported {@link URL#toFullString() strings} presenting the {@link URL URLs} in bulk.
- *
- * @param serviceName the specified Dubbo service name
- * @param exportedURLs the exported {@link URL urls}
- * @return If successful, return <code>true</code>, or <code>false</code>
- * @since 2.7.8
- */
- default boolean saveExportedURLs(String serviceName, SortedSet<String> exportedURLs) {
- return saveExportedURLs(serviceName, new URLRevisionResolver().resolve(exportedURLs), exportedURLs);
- }
+ * deprecated or need triage
+ **/
+ void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map<String, String> serviceParameterMap);
- /**
- * Save the exported {@link URL#toFullString() strings} presenting the {@link URL URLs} in bulk.
- *
- * @param serviceName the specified Dubbo service name
- * @param exportedServicesRevision the revision of the exported Services
- * @param exportedURLs the exported {@link URL urls}
- * @return If successful, return <code>true</code>, or <code>false</code>
- * @since 2.7.8
- */
- default boolean saveExportedURLs(String serviceName, String exportedServicesRevision, SortedSet<String> exportedURLs) {
- Gson gson = new Gson();
- String content = gson.toJson(exportedURLs);
- return saveExportedURLs(serviceName, exportedServicesRevision, content);
- }
+ List<String> getExportedURLs(ServiceMetadataIdentifier metadataIdentifier);
- /**
- * Save the exported {@link URL#toFullString() strings} presenting the {@link URL URLs} in bulk.
- *
- * @param serviceName the specified Dubbo service name
- * @param exportedServicesRevision the revision of the exported Services
- * @param exportedURLsContent the content of the exported {@link URL urls}
- * @return If successful, return <code>true</code>, or <code>false</code>
- * @since 2.7.8
- */
- default boolean saveExportedURLs(String serviceName, String exportedServicesRevision, String exportedURLsContent) {
- return true;
- }
+ void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url);
- /**
- * Get the {@link URL#toFullString() strings} presenting the {@link URL URLs} that were exported by the provider
- *
- * @param serviceName the specified Dubbo service name
- * @param exportedServicesRevision the revision of the exported Services
- * @return non-null
- * @since 2.7.8
- */
- default SortedSet<String> getExportedURLs(String serviceName, String exportedServicesRevision) {
- String exportedURLsContent = getExportedURLsContent(serviceName, exportedServicesRevision);
- if (StringUtils.isBlank(exportedURLsContent)) {
- return emptySortedSet();
- }
- Gson gson = new Gson();
- return gson.fromJson(exportedURLsContent, TreeSet.class);
- }
+ void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier);
- /**
- * Get the {@link URL#toFullString() strings} presenting the {@link URL URLs} that were exported by the provider
- *
- * @param serviceName the specified Dubbo service name
- * @param exportedServicesRevision the revision of the exported Services
- * @return the content of the exported {@link URL urls} if found, or <code>null</code>
- * @since 2.7.8
- */
- default String getExportedURLsContent(String serviceName, String exportedServicesRevision) {
- return null;
- }
+ void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set<String> urls);
+
+ List<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier);
-}
\ No newline at end of file
+}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java
index 4f84e0c..8d11784 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java
@@ -19,10 +19,14 @@ package org.apache.dubbo.metadata.report;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.extension.ExtensionLoader;
+import org.apache.dubbo.config.MetadataReportConfig;
+import java.util.HashMap;
+import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_DIRECTORY;
+import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY;
import static org.apache.dubbo.metadata.report.support.Constants.METADATA_REPORT_KEY;
/**
@@ -32,35 +36,45 @@ public class MetadataReportInstance {
private static AtomicBoolean init = new AtomicBoolean(false);
- private static MetadataReport metadataReport;
+ private static final Map<String, MetadataReport> metadataReports = new HashMap<>();
- public static void init(URL metadataReportURL) {
+ public static void init(MetadataReportConfig config) {
if (init.get()) {
return;
}
MetadataReportFactory metadataReportFactory = ExtensionLoader.getExtensionLoader(MetadataReportFactory.class).getAdaptiveExtension();
- if (METADATA_REPORT_KEY.equals(metadataReportURL.getProtocol())) {
- String protocol = metadataReportURL.getParameter(METADATA_REPORT_KEY, DEFAULT_DIRECTORY);
- metadataReportURL = URLBuilder.from(metadataReportURL)
+ URL url = config.toUrl();
+ if (METADATA_REPORT_KEY.equals(url.getProtocol())) {
+ String protocol = url.getParameter(METADATA_REPORT_KEY, DEFAULT_DIRECTORY);
+ url = URLBuilder.from(url)
.setProtocol(protocol)
.removeParameter(METADATA_REPORT_KEY)
.build();
}
- metadataReport = metadataReportFactory.getMetadataReport(metadataReportURL);
+ String relatedRegistryId = config.getRegistry() == null ? DEFAULT_KEY : config.getRegistry();
+// RegistryConfig registryConfig = ApplicationModel.getConfigManager().getRegistry(relatedRegistryId)
+// .orElseThrow(() -> new IllegalStateException("Registry id " + relatedRegistryId + " does not exist."));
+ metadataReports.put(relatedRegistryId, metadataReportFactory.getMetadataReport(url));
init.set(true);
}
- public static MetadataReport getMetadataReport() {
- return getMetadataReport(false);
- }
-
- public static MetadataReport getMetadataReport(boolean checked) {
+ public static Map<String, MetadataReport> getMetadataReports(boolean checked) {
if (checked) {
checkInit();
}
+ return metadataReports;
+ }
+
+ public static MetadataReport getMetadataReport(String registryKey) {
+ checkInit();
+ MetadataReport metadataReport = metadataReports.get(registryKey);
+ if (metadataReport == null) {
+ metadataReport = metadataReports.values().iterator().next();
+ }
return metadataReport;
}
+
private static void checkInit() {
if (!init.get()) {
throw new IllegalStateException("the metadata report was not inited.");
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java
index f3b90db..1d39401 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java
@@ -44,7 +44,6 @@ import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.Calendar;
-import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -53,6 +52,7 @@ import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadLocalRandom;
@@ -61,15 +61,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
-import static java.util.concurrent.Executors.newScheduledThreadPool;
-import static java.util.concurrent.Executors.newSingleThreadExecutor;
-import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
-import static org.apache.dubbo.common.utils.StringUtils.replace;
import static org.apache.dubbo.metadata.report.support.Constants.CYCLE_REPORT_KEY;
import static org.apache.dubbo.metadata.report.support.Constants.DEFAULT_METADATA_REPORT_CYCLE_REPORT;
import static org.apache.dubbo.metadata.report.support.Constants.DEFAULT_METADATA_REPORT_RETRY_PERIOD;
@@ -90,52 +86,24 @@ public abstract class AbstractMetadataReport implements MetadataReport {
// Log output
protected final Logger logger = LoggerFactory.getLogger(getClass());
- private final AtomicBoolean initialized = new AtomicBoolean(false);
-
+ // Local disk cache, where the special key value.registries records the list of metadata centers, and the others are the list of notified service providers
+ final Properties properties = new Properties();
+ private final ExecutorService reportCacheExecutor = Executors.newFixedThreadPool(1, new NamedThreadFactory("DubboSaveMetadataReport", true));
final Map<MetadataIdentifier, Object> allMetadataReports = new ConcurrentHashMap<>(4);
+ private final AtomicLong lastCacheChanged = new AtomicLong();
final Map<MetadataIdentifier, Object> failedReports = new ConcurrentHashMap<>(4);
-
private URL reportURL;
boolean syncReport;
-
// Local disk cache file
- File localCacheFile;
- // Local disk cache, where the special key value.registries records the list of metadata centers, and the others are the list of notified service providers
- final Properties properties = new Properties();
-
- private final AtomicLong lastCacheChanged = new AtomicLong();
-
- // ThreadPoolExecutors
- private final ExecutorService reportCacheExecutor;
-
- public final MetadataReportRetry metadataReportRetry;
-
- private final ScheduledExecutorService cycleReportExecutor;
+ File file;
+ private AtomicBoolean initialized = new AtomicBoolean(false);
+ public MetadataReportRetry metadataReportRetry;
public AbstractMetadataReport(URL reportServerURL) {
setUrl(reportServerURL);
-
- this.localCacheFile = initializeLocalCacheFile(reportServerURL);
- loadProperties();
- syncReport = reportServerURL.getParameter(SYNC_REPORT_KEY, false);
- metadataReportRetry = new MetadataReportRetry(reportServerURL.getParameter(RETRY_TIMES_KEY, DEFAULT_METADATA_REPORT_RETRY_TIMES),
- reportServerURL.getParameter(RETRY_PERIOD_KEY, DEFAULT_METADATA_REPORT_RETRY_PERIOD));
- this.reportCacheExecutor = newSingleThreadExecutor(new NamedThreadFactory("DubboSaveMetadataReport", true));
- this.cycleReportExecutor = newSingleThreadScheduledExecutor(new NamedThreadFactory("DubboMetadataReportTimer", true));
- // cycle report the data switch
- if (reportServerURL.getParameter(CYCLE_REPORT_KEY, DEFAULT_METADATA_REPORT_CYCLE_REPORT)) {
- cycleReportExecutor.scheduleAtFixedRate(this::publishAll, calculateStartTime(), ONE_DAY_IN_MILLISECONDS, TimeUnit.MILLISECONDS);
- }
- }
-
- private File initializeLocalCacheFile(URL reportServerURL) {
// Start file save timer
- String defaultFilename = System.getProperty("user.home") +
- "/.dubbo/dubbo-metadata-" +
- reportServerURL.getParameter(APPLICATION_KEY) + "-" +
- replace(reportServerURL.getAddress(), ":", "-") +
- ".cache";
+ String defaultFilename = System.getProperty("user.home") + "/.dubbo/dubbo-metadata-" + reportServerURL.getParameter(APPLICATION_KEY) + "-" + reportServerURL.getAddress().replaceAll(":", "-") + ".cache";
String filename = reportServerURL.getParameter(FILE_KEY, defaultFilename);
File file = null;
if (ConfigUtils.isNotEmpty(filename)) {
@@ -150,7 +118,16 @@ public abstract class AbstractMetadataReport implements MetadataReport {
file.delete();
}
}
- return file;
+ this.file = file;
+ loadProperties();
+ syncReport = reportServerURL.getParameter(SYNC_REPORT_KEY, false);
+ metadataReportRetry = new MetadataReportRetry(reportServerURL.getParameter(RETRY_TIMES_KEY, DEFAULT_METADATA_REPORT_RETRY_TIMES),
+ reportServerURL.getParameter(RETRY_PERIOD_KEY, DEFAULT_METADATA_REPORT_RETRY_PERIOD));
+ // cycle report the data switch
+ if (reportServerURL.getParameter(CYCLE_REPORT_KEY, DEFAULT_METADATA_REPORT_CYCLE_REPORT)) {
+ ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("DubboMetadataReportTimer", true));
+ scheduler.scheduleAtFixedRate(this::publishAll, calculateStartTime(), ONE_DAY_IN_MILLISECONDS, TimeUnit.MILLISECONDS);
+ }
}
public URL getUrl() {
@@ -168,12 +145,12 @@ public abstract class AbstractMetadataReport implements MetadataReport {
if (version < lastCacheChanged.get()) {
return;
}
- if (localCacheFile == null) {
+ if (file == null) {
return;
}
// Save
try {
- File lockfile = new File(localCacheFile.getAbsolutePath() + ".lock");
+ File lockfile = new File(file.getAbsolutePath() + ".lock");
if (!lockfile.exists()) {
lockfile.createNewFile();
}
@@ -181,14 +158,14 @@ public abstract class AbstractMetadataReport implements MetadataReport {
FileChannel channel = raf.getChannel()) {
FileLock lock = channel.tryLock();
if (lock == null) {
- throw new IOException("Can not lock the metadataReport cache file " + localCacheFile.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.metadata.file=xxx.properties");
+ throw new IOException("Can not lock the metadataReport cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.metadata.file=xxx.properties");
}
// Save
try {
- if (!localCacheFile.exists()) {
- localCacheFile.createNewFile();
+ if (!file.exists()) {
+ file.createNewFile();
}
- try (FileOutputStream outputFile = new FileOutputStream(localCacheFile)) {
+ try (FileOutputStream outputFile = new FileOutputStream(file)) {
properties.store(outputFile, "Dubbo metadataReport Cache");
}
} finally {
@@ -206,20 +183,20 @@ public abstract class AbstractMetadataReport implements MetadataReport {
}
void loadProperties() {
- if (localCacheFile != null && localCacheFile.exists()) {
- try (InputStream in = new FileInputStream(localCacheFile)) {
+ if (file != null && file.exists()) {
+ try (InputStream in = new FileInputStream(file)) {
properties.load(in);
if (logger.isInfoEnabled()) {
- logger.info("Load service store file " + localCacheFile + ", data: " + properties);
+ logger.info("Load service store file " + file + ", data: " + properties);
}
} catch (Throwable e) {
- logger.warn("Failed to load service store file " + localCacheFile, e);
+ logger.warn("Failed to load service store file " + file, e);
}
}
}
private void saveProperties(MetadataIdentifier metadataIdentifier, String value, boolean add, boolean sync) {
- if (localCacheFile == null) {
+ if (file == null) {
return;
}
@@ -341,7 +318,7 @@ public abstract class AbstractMetadataReport implements MetadataReport {
}
@Override
- public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Collection<String> urls) {
+ public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set<String> urls) {
if (syncReport) {
doSaveSubscriberData(subscriberMetadataIdentifier, new Gson().toJson(urls));
} else {
@@ -351,7 +328,7 @@ public abstract class AbstractMetadataReport implements MetadataReport {
@Override
- public Set<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
+ public List<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
String content = doGetSubscribedURLs(subscriberMetadataIdentifier);
Type setType = new TypeToken<SortedSet<String>>() {
}.getType();
@@ -415,7 +392,7 @@ public abstract class AbstractMetadataReport implements MetadataReport {
class MetadataReportRetry {
protected final Logger logger = LoggerFactory.getLogger(getClass());
- final ScheduledExecutorService retryExecutor = newScheduledThreadPool(0, new NamedThreadFactory("DubboMetadataReportRetryTimer", true));
+ final ScheduledExecutorService retryExecutor = Executors.newScheduledThreadPool(0, new NamedThreadFactory("DubboMetadataReportRetryTimer", true));
volatile ScheduledFuture retryScheduledFuture;
final AtomicInteger retryCounter = new AtomicInteger(0);
// retry task schedule period
@@ -458,10 +435,8 @@ public abstract class AbstractMetadataReport implements MetadataReport {
}
void cancelRetryTask() {
- if (retryScheduledFuture != null) {
- retryScheduledFuture.cancel(false);
- }
- shutdown(retryExecutor);
+ retryScheduledFuture.cancel(false);
+ retryExecutor.shutdown();
}
}
@@ -476,13 +451,6 @@ public abstract class AbstractMetadataReport implements MetadataReport {
doSaveSubscriberData(subscriberMetadataIdentifier, encodedUrlList);
}
- @Override
- public final void close() throws Exception {
- this.shutdownThreadPoolExecutors();
- this.clearCache();
- doClose();
- }
-
protected abstract void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions);
protected abstract void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString);
@@ -497,35 +465,4 @@ public abstract class AbstractMetadataReport implements MetadataReport {
protected abstract String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier);
- /**
- * Close other resources
- *
- * @since 2.7.8
- */
- protected void doClose() throws Exception {
-
- }
-
- private void clearCache() {
- this.properties.clear();
- this.allMetadataReports.clear();
- this.failedReports.clear();
- this.localCacheFile.delete();
- }
-
- private void shutdownThreadPoolExecutors() {
- this.metadataReportRetry.cancelRetryTask();
- shutdown(this.reportCacheExecutor);
- shutdown(cycleReportExecutor);
- }
-
- private static void shutdown(ExecutorService executorService) {
- if (executorService == null) {
- return;
- }
- if (!executorService.isShutdown()) {
- executorService.shutdown();
- }
- }
-
}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/ConfigCenterBasedMetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/ConfigCenterBasedMetadataReport.java
deleted file mode 100644
index d962ca5..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/ConfigCenterBasedMetadataReport.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * 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.apache.dubbo.metadata.report.support;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
-import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory;
-import org.apache.dubbo.metadata.report.MetadataReport;
-import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier;
-import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
-import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
-import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
-import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
-
-import java.util.List;
-
-import static org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory.getDynamicConfigurationFactory;
-import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
-import static org.apache.dubbo.metadata.MetadataConstants.EXPORTED_URLS_TAG;
-
-/**
- * The generic implementation of {@link MetadataReport} based on {@link DynamicConfiguration
- * the config-center infrastructure}
- *
- * @see AbstractMetadataReport
- * @since 2.7.8
- */
-public class ConfigCenterBasedMetadataReport extends AbstractMetadataReport {
-
- private final KeyTypeEnum keyType;
-
- private final String group;
-
- private final DynamicConfiguration dynamicConfiguration;
-
- public ConfigCenterBasedMetadataReport(URL reportServerURL, KeyTypeEnum keyTypeEnum) {
- super(reportServerURL);
- this.keyType = keyTypeEnum;
- this.group = reportServerURL.getParameter(GROUP_KEY, DEFAULT_ROOT);
- String extensionName = reportServerURL.getProtocol();
- DynamicConfigurationFactory dynamicConfigurationFactory = getDynamicConfigurationFactory(extensionName);
- dynamicConfiguration = dynamicConfigurationFactory.getDynamicConfiguration(reportServerURL);
- }
-
-
- @Override
- protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) {
- saveMetadata(providerMetadataIdentifier, serviceDefinitions);
- }
-
- @Override
- protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) {
- saveMetadata(consumerMetadataIdentifier, serviceParameterString);
- }
-
- @Override
- protected void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {
- saveMetadata(metadataIdentifier, URL.encode(url.toFullString()));
- }
-
- @Override
- protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) {
- removeMetadata(metadataIdentifier);
- }
-
- @Override
- protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
- throw new UnsupportedOperationException("doGetExportedURLs method will not be supported!");
- }
-
- @Override
- protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr) {
- saveMetadata(subscriberMetadataIdentifier, urlListStr);
- }
-
- @Override
- protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
- return getMetadata(subscriberMetadataIdentifier);
- }
-
- @Override
- public String getServiceDefinition(MetadataIdentifier metadataIdentifier) {
- return getMetadata(metadataIdentifier);
- }
-
- @Override
- public boolean saveExportedURLs(String serviceName, String exportedServicesRevision, String exportedURLsContent) {
- String key = buildExportedURLsMetadataKey(serviceName, exportedServicesRevision);
- return dynamicConfiguration.publishConfig(key, group, exportedURLsContent);
- }
-
- @Override
- public String getExportedURLsContent(String serviceName, String exportedServicesRevision) {
- String key = buildExportedURLsMetadataKey(serviceName, exportedServicesRevision);
- return dynamicConfiguration.getConfig(key, group);
- }
-
- private String buildExportedURLsMetadataKey(String serviceName, String exportedServicesRevision) {
- return keyType.build(EXPORTED_URLS_TAG, serviceName, exportedServicesRevision);
- }
-
- protected void saveMetadata(BaseMetadataIdentifier metadataIdentifier, String value) {
- String key = getKey(metadataIdentifier);
- dynamicConfiguration.publishConfig(key, group, value);
- }
-
- protected void saveMetadata(MetadataIdentifier metadataIdentifier, String value) {
- String key = getKey(metadataIdentifier);
- dynamicConfiguration.publishConfig(key, group, value);
- }
-
- protected String getMetadata(ServiceMetadataIdentifier metadataIdentifier) {
- String key = getKey(metadataIdentifier);
- return dynamicConfiguration.getConfig(key, group);
- }
-
- protected String getMetadata(MetadataIdentifier metadataIdentifier) {
- String key = getKey(metadataIdentifier);
- return dynamicConfiguration.getConfig(key, group);
- }
-
- protected String getMetadata(SubscriberMetadataIdentifier metadataIdentifier) {
- String key = getKey(metadataIdentifier);
- return dynamicConfiguration.getConfig(key, group);
- }
-
- protected void removeMetadata(MetadataIdentifier metadataIdentifier) {
- String key = getKey(metadataIdentifier);
- dynamicConfiguration.removeConfig(key, group);
- }
-
- protected void removeMetadata(ServiceMetadataIdentifier metadataIdentifier) {
- String key = getKey(metadataIdentifier);
- dynamicConfiguration.removeConfig(key, group);
- }
-
- protected String getKey(BaseMetadataIdentifier metadataIdentifier) {
- return metadataIdentifier.getUniqueKey(keyType);
- }
-
- protected String getKey(MetadataIdentifier metadataIdentifier) {
- return metadataIdentifier.getUniqueKey(keyType);
- }
-
- protected void doClose() throws Exception {
- this.dynamicConfiguration.close();
- }
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/ConfigCenterBasedMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/ConfigCenterBasedMetadataReportFactory.java
deleted file mode 100644
index b445feb..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/ConfigCenterBasedMetadataReportFactory.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * 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.apache.dubbo.metadata.report.support;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
-import org.apache.dubbo.metadata.report.MetadataReport;
-import org.apache.dubbo.metadata.report.MetadataReportFactory;
-import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import static org.apache.dubbo.common.config.configcenter.TreePathDynamicConfiguration.CONFIG_ROOT_PATH_PARAM_NAME;
-import static org.apache.dubbo.common.utils.StringUtils.SLASH;
-import static org.apache.dubbo.common.utils.StringUtils.isBlank;
-import static org.apache.dubbo.metadata.report.identifier.KeyTypeEnum.PATH;
-import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY;
-import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
-
-/**
- * The abstract implementation of {@link MetadataReportFactory} based on
- * {@link DynamicConfiguration the config-center infrastructure}
- *
- * @see MetadataReportFactory
- * @see MetadataReport
- * @see DynamicConfiguration
- * @since 2.7.8
- */
-public abstract class ConfigCenterBasedMetadataReportFactory implements MetadataReportFactory {
-
- /**
- * org.apache.dubbo.metadata.report.MetadataReport
- */
- private static final String URL_PATH = MetadataReport.class.getName();
-
- // Registry Collection Map<metadataAddress, MetadataReport>
- private static final Map<String, ConfigCenterBasedMetadataReport> metadataReportCache = new ConcurrentHashMap();
-
- private final KeyTypeEnum keyType;
-
- public ConfigCenterBasedMetadataReportFactory(KeyTypeEnum keyType) {
- if (keyType == null) {
- throw new NullPointerException("The keyType argument must not be null!");
- }
- this.keyType = keyType;
- }
-
- @Override
- public ConfigCenterBasedMetadataReport getMetadataReport(URL url) {
- url = url.setPath(URL_PATH);
- final URL actualURL = resolveURLParameters(url);
- String key = actualURL.toServiceString();
- // Lock the metadata access process to ensure a single instance of the metadata instance
- return metadataReportCache.computeIfAbsent(key, k -> new ConfigCenterBasedMetadataReport(actualURL, keyType));
- }
-
- private URL resolveURLParameters(URL url) {
- URL resolvedURL = url.removeParameters(EXPORT_KEY, REFER_KEY);
- if (PATH.equals(getKeyType())) { // Only handles for "PATH" type
- if (isBlank(resolvedURL.getParameter(CONFIG_ROOT_PATH_PARAM_NAME))) {
- resolvedURL = resolvedURL.addParameter(CONFIG_ROOT_PATH_PARAM_NAME, SLASH);
- }
- }
- return resolvedURL;
- }
-
- /**
- * Get {@link KeyTypeEnum the key type}
- *
- * @return non-null
- */
- protected KeyTypeEnum getKeyType() {
- return keyType;
- }
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/file/FileSystemMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/file/FileSystemMetadataReportFactory.java
deleted file mode 100644
index c4cc487..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/file/FileSystemMetadataReportFactory.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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.apache.dubbo.metadata.report.support.file;
-
-import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
-import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReportFactory;
-
-/**
- * The implementation of {@link ConfigCenterBasedMetadataReportFactory} based on File System
- *
- * @see ConfigCenterBasedMetadataReportFactory
- * @since 2.7.8
- */
-public class FileSystemMetadataReportFactory extends ConfigCenterBasedMetadataReportFactory {
-
- public FileSystemMetadataReportFactory() {
- super(KeyTypeEnum.PATH);
- }
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/store/RemoteWritableMetadataService.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/store/RemoteWritableMetadataService.java
deleted file mode 100644
index c2ae3e5..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/store/RemoteWritableMetadataService.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * 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.apache.dubbo.metadata.store;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.utils.StringUtils;
-import org.apache.dubbo.metadata.URLRevisionResolver;
-import org.apache.dubbo.metadata.WritableMetadataService;
-import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder;
-import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
-import org.apache.dubbo.metadata.report.MetadataReport;
-import org.apache.dubbo.metadata.report.MetadataReportInstance;
-import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
-
-import java.util.SortedSet;
-
-import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
-import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
-import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
-
-/**
- * The {@link WritableMetadataService} implementation stores the metadata of Dubbo services in metadata center when they
- * exported.
- * It is used by server (provider).
- *
- * @since 2.7.5
- */
-public class RemoteWritableMetadataService extends AbstractAbstractWritableMetadataService {
-
- private final InMemoryWritableMetadataService writableMetadataServiceDelegate;
-
- private final URLRevisionResolver urlRevisionResolver;
-
- public RemoteWritableMetadataService() {
- this.writableMetadataServiceDelegate = (InMemoryWritableMetadataService) WritableMetadataService.getDefaultExtension();
- urlRevisionResolver = URLRevisionResolver.INSTANCE;
- }
-
- public MetadataReport getMetadataReport() {
- return MetadataReportInstance.getMetadataReport(true);
- }
-
- @Override
- protected void publishConsumerParameters(URL consumerURL) {
- getMetadataReport().storeConsumerMetadata(new MetadataIdentifier(consumerURL.getServiceInterface(),
- consumerURL.getParameter(VERSION_KEY), consumerURL.getParameter(GROUP_KEY), CONSUMER_SIDE,
- consumerURL.getParameter(APPLICATION_KEY)), consumerURL.getParameters());
- }
-
- @Override
- protected void publishProviderServiceDefinition(URL providerURL) {
- try {
- String interfaceName = providerURL.getParameter(INTERFACE_KEY);
- if (StringUtils.isNotEmpty(interfaceName)) {
- Class interfaceClass = Class.forName(interfaceName);
- FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass,
- providerURL.getParameters());
- getMetadataReport().storeProviderMetadata(new MetadataIdentifier(providerURL.getServiceInterface(),
- providerURL.getParameter(VERSION_KEY), providerURL.getParameter(GROUP_KEY),
- PROVIDER_SIDE, providerURL.getParameter(APPLICATION_KEY)), fullServiceDefinition);
- return;
- }
- logger.error("publishProvider interfaceName is empty . url: " + providerURL.toFullString());
- } catch (ClassNotFoundException e) {
- //ignore error
- logger.error("publishProvider getServiceDescriptor error. url: " + providerURL.toFullString(), e);
- }
- }
-
- @Override
- public boolean exportURL(URL url) {
- return writableMetadataServiceDelegate.exportURL(url);
- }
-
- @Override
- public boolean unexportURL(URL url) {
- return writableMetadataServiceDelegate.unexportURL(url);
- }
-
- @Override
- public boolean subscribeURL(URL url) {
- return writableMetadataServiceDelegate.subscribeURL(url);
- }
-
- @Override
- public boolean unsubscribeURL(URL url) {
- return writableMetadataServiceDelegate.unsubscribeURL(url);
- }
-
- @Override
- public SortedSet<String> getExportedURLs(String serviceInterface, String group, String version, String protocol) {
- return writableMetadataServiceDelegate.getExportedURLs(serviceInterface, group, version, protocol);
- }
-
- @Override
- public String getServiceDefinition(String serviceKey) {
- return writableMetadataServiceDelegate.getServiceDefinition(serviceKey);
- }
-
- @Override
- public SortedSet<String> getSubscribedURLs() {
- return writableMetadataServiceDelegate.getSubscribedURLs();
- }
-
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataParamsFilter b/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataParamsFilter
new file mode 100644
index 0000000..6754126
--- /dev/null
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataParamsFilter
@@ -0,0 +1 @@
+default=org.apache.dubbo.metadata.DefaultMetadataParamsFilter
\ No newline at end of file
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping b/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping
index beadd2e..b991bc3 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping
@@ -1,9 +1 @@
-# "default" implementation has been changed since 2.7.8
-default=org.apache.dubbo.metadata.CompositeServiceNameMapping
-
-# "properties-file" and "parameterized" are introduced since 2.7.8
-properties-file = org.apache.dubbo.metadata.PropertiesFileServiceNameMapping
-parameterized = org.apache.dubbo.metadata.ParameterizedServiceNameMapping
-
-# "dynamic-configuration" has been revised since 2.7.8
-dynamic-configuration = org.apache.dubbo.metadata.DynamicConfigurationServiceNameMapping
\ No newline at end of file
+config=org.apache.dubbo.metadata.DynamicConfigurationServiceNameMapping
\ No newline at end of file
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService b/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService
deleted file mode 100644
index 26bc942..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService
+++ /dev/null
@@ -1,2 +0,0 @@
-local=org.apache.dubbo.metadata.store.InMemoryWritableMetadataService
-remote=org.apache.dubbo.metadata.store.RemoteWritableMetadataService
\ No newline at end of file
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory
deleted file mode 100644
index b686fce..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory
+++ /dev/null
@@ -1 +0,0 @@
-file = org.apache.dubbo.metadata.report.support.file.FileSystemMetadataReportFactory
\ No newline at end of file
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/CompositeServiceNameMappingTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/CompositeServiceNameMappingTest.java
deleted file mode 100644
index 48243f8..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/CompositeServiceNameMappingTest.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * 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.apache.dubbo.metadata;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.config.configcenter.file.FileSystemDynamicConfiguration;
-import org.apache.dubbo.config.ApplicationConfig;
-import org.apache.dubbo.rpc.model.ApplicationModel;
-import org.apache.dubbo.rpc.service.EchoService;
-
-import org.apache.commons.io.FileUtils;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import java.util.Set;
-
-import static java.util.Collections.singleton;
-import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
-import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY;
-import static org.apache.dubbo.common.utils.CollectionUtils.ofSet;
-import static org.apache.dubbo.metadata.DynamicConfigurationServiceNameMapping.buildGroup;
-import static org.apache.dubbo.rpc.model.ApplicationModel.getApplicationConfig;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-/**
- * {@link CompositeServiceNameMapping} Test
- *
- * @since 2.7.8
- */
-public class CompositeServiceNameMappingTest {
-
- private static final URL BASE_URL = URL.valueOf("dubbo://127.0.0.1:20880")
- .setPath(EchoService.class.getName())
- .addParameter(GROUP_KEY, "default")
- .addParameter(VERSION_KEY, "1.0.0");
-
- private static final String APP_NAME = "test-service";
-
- private ServiceNameMapping serviceNameMapping;
-
- private FileSystemDynamicConfiguration dynamicConfiguration;
-
- @BeforeEach
- public void init() {
- serviceNameMapping = ServiceNameMapping.getDefaultExtension();
- dynamicConfiguration = new FileSystemDynamicConfiguration();
- ApplicationModel.getConfigManager().setApplication(new ApplicationConfig(APP_NAME));
- ApplicationModel.getEnvironment().setDynamicConfiguration(dynamicConfiguration);
- }
-
- @AfterEach
- public void reset() {
- FileUtils.deleteQuietly(dynamicConfiguration.getRootDirectory());
- ApplicationModel.reset();
- }
-
- @Test
- public void testType() {
- assertEquals(CompositeServiceNameMapping.class, serviceNameMapping.getClass());
- }
-
- @Test
- public void testMap() {
- serviceNameMapping.map(BASE_URL);
- assertNotNull(dynamicConfiguration.getConfig(APP_NAME,
- buildGroup(BASE_URL.getServiceInterface(), null, null, null)));
- }
-
- @Test
- public void testGet() {
- serviceNameMapping.map(BASE_URL);
- Set<String> serviceNames = serviceNameMapping.get(BASE_URL);
- assertEquals(singleton(APP_NAME), serviceNames);
-
- getApplicationConfig().setName("service1");
- serviceNameMapping.map(BASE_URL);
- serviceNames = serviceNameMapping.get(BASE_URL);
- assertEquals(ofSet(APP_NAME, "service1"), serviceNames);
-
- serviceNames = serviceNameMapping.get(BASE_URL
- .setPath("com.acme.Interface1")
- .removeParameter(VERSION_KEY)
- );
- assertEquals(singleton("Service1"), serviceNames);
-
- serviceNames = serviceNameMapping.get(BASE_URL.addParameter(SUBSCRIBED_SERVICE_NAMES_KEY, "s1 , s2 , s3 "));
- assertEquals(ofSet("s1", "s2", "s3"), serviceNames);
- }
-}
-
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataConstantsTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DemoService.java
similarity index 67%
rename from dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataConstantsTest.java
rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DemoService.java
index d0c201b..33bcbc7 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataConstantsTest.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DemoService.java
@@ -16,20 +16,22 @@
*/
package org.apache.dubbo.metadata;
-import org.junit.jupiter.api.Test;
+import org.apache.dubbo.metadata.rest.User;
+
+import java.util.List;
-import static org.junit.jupiter.api.Assertions.assertEquals;
/**
- * {@link MetadataConstants} Test-Cases
- *
- * @since 2.7.8
+ * DemoService
*/
-public class MetadataConstantsTest {
-
- @Test
- public void testConstants() {
- assertEquals("exported-urls", MetadataConstants.EXPORTED_URLS_TAG);
- assertEquals("subscribed-urls", MetadataConstants.SUBSCRIBED_URLS_TAG);
- }
-}
+public interface DemoService {
+
+ String sayName(String name);
+
+ void throwRuntimeException() throws RuntimeException;
+
+ List<User> getUsers(List<User> users);
+
+ int echo(int i);
+
+}
\ No newline at end of file
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java
deleted file mode 100644
index d4d25ee..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * 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.apache.dubbo.metadata;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
-import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory;
-import org.apache.dubbo.config.ApplicationConfig;
-import org.apache.dubbo.rpc.model.ApplicationModel;
-
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-
-import java.util.Set;
-import java.util.TreeSet;
-
-import static java.util.Arrays.asList;
-import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
-import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
-import static org.apache.dubbo.metadata.DynamicConfigurationServiceNameMapping.buildGroup;
-import static org.apache.dubbo.metadata.ServiceNameMapping.getDefaultExtension;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-/**
- * {@link DynamicConfigurationServiceNameMapping} Test
- *
- * @since 2.7.5
- */
-public class DynamicConfigurationServiceNameMappingTest {
-
-
- private final ServiceNameMapping serviceNameMapping = getDefaultExtension();
-
- @BeforeAll
- public static void setUp() throws Exception {
-
- DynamicConfiguration configuration = getExtensionLoader(DynamicConfigurationFactory.class)
- .getExtension("file")
- .getDynamicConfiguration(null);
-
- ApplicationModel.getEnvironment().setDynamicConfiguration(configuration);
- }
-
- @Test
- public void testBuildGroup() {
- assertEquals("mapping/test", buildGroup("test", null, null, null));
- assertEquals("mapping/test", buildGroup("test", "default", null, null));
- assertEquals("mapping/test", buildGroup("test", "default", "1.0.0", null));
- assertEquals("mapping/test", buildGroup("test", "default", "1.0.0", "dubbo"));
- }
-
- @Test
- public void testAndGetOnFailed() {
- assertThrows(UnsupportedOperationException.class, () -> {
- serviceNameMapping.map(null, null, null, null);
- });
-
- assertThrows(UnsupportedOperationException.class, () -> {
- serviceNameMapping.get(null, null, null, null);
- });
- }
-
- @Test
- public void testMapAndGet() {
-
- String serviceName = "test";
- String serviceName2 = "test2";
-
- ApplicationModel.getConfigManager().setApplication(new ApplicationConfig(serviceName));
-
- String serviceInterface = "org.apache.dubbo.service.UserService";
- String group = null;
- String version = null;
- String protocol = null;
-
- URL url = URL.valueOf("dubbo://127.0.0.1:20880").setServiceInterface(serviceInterface)
- .addParameter(GROUP_KEY, group)
- .addParameter(VERSION_KEY, version);
-
- serviceNameMapping.map(url);
-
- ApplicationModel.getConfigManager().removeConfig(new ApplicationConfig(serviceName));
- ApplicationModel.getConfigManager().setApplication(new ApplicationConfig(serviceName2));
-
- serviceNameMapping.map(url);
-
- Set<String> serviceNames = serviceNameMapping.get(url);
-
- assertEquals(new TreeSet(asList(serviceName, serviceName2)), serviceNames);
-
- ApplicationModel.getConfigManager().removeConfig(new ApplicationConfig(serviceName2));
- }
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/InMemoryWritableMetadataServiceTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/InMemoryWritableMetadataServiceTest.java
deleted file mode 100644
index 187f126..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/InMemoryWritableMetadataServiceTest.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * 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.apache.dubbo.metadata;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.config.ApplicationConfig;
-import org.apache.dubbo.metadata.store.InMemoryWritableMetadataService;
-import org.apache.dubbo.rpc.model.ApplicationModel;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import static java.util.Arrays.asList;
-import static java.util.Collections.unmodifiableSortedSet;
-import static org.apache.dubbo.common.URL.valueOf;
-import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-/**
- * {@link InMemoryWritableMetadataService} Test
- *
- * @since 2.7.5
- */
-public class InMemoryWritableMetadataServiceTest {
-
- private WritableMetadataService metadataService = new InMemoryWritableMetadataService();
-
- private static final String TEST_SERVICE = "org.apache.dubbo.test.TestService";
-
- private static final URL BASE_URL = valueOf("dubbo://127.0.0.1:20880/" + TEST_SERVICE);
- private static final URL REST_BASE_URL = valueOf("rest://127.0.0.1:20880/" + TEST_SERVICE);
- private static final URL BASE_URL_GROUP = BASE_URL.addParameter(GROUP_KEY, "test");
- private static final URL BASE_URL_GROUP_AND_VERSION = BASE_URL_GROUP.addParameter(VERSION_KEY, "1.0.0");
- private static final URL BASE_URL_GROUP_AND_VERSION_AND_PROTOCOL = BASE_URL_GROUP_AND_VERSION.addParameter(PROTOCOL_KEY, "rest");
-
- @BeforeEach
- public void init() {
- ApplicationConfig applicationConfig = new ApplicationConfig("test");
- ApplicationModel.getConfigManager().setApplication(applicationConfig);
- }
-
- @AfterEach
- public void reset() {
- ApplicationModel.reset();
- }
-
- @Test
- public void testServiceName() {
- assertEquals("test", metadataService.serviceName());
- }
-
- @Test
- public void testVersion() {
- assertEquals("1.0.0", MetadataService.VERSION);
- assertEquals("1.0.0", metadataService.version());
- }
-
- @Test
- public void testGetExportedURLs() {
-
- assertTrue(metadataService.exportURL(BASE_URL));
- Set<String> exportedURLs = metadataService.getExportedURLs(TEST_SERVICE);
- assertEquals(1, exportedURLs.size());
- assertEquals(asSortedSet(BASE_URL.toFullString()), exportedURLs);
- assertTrue(metadataService.unexportURL(BASE_URL));
-
- assertTrue(metadataService.exportURL(BASE_URL));
- assertFalse(metadataService.exportURL(BASE_URL));
-
- assertTrue(metadataService.exportURL(BASE_URL_GROUP));
- assertTrue(metadataService.exportURL(BASE_URL_GROUP_AND_VERSION));
-
- exportedURLs = metadataService.getExportedURLs(TEST_SERVICE);
- assertEquals(asSortedSet(BASE_URL.toFullString()), exportedURLs);
- assertEquals(asSortedSet(
- BASE_URL.toFullString(),
- BASE_URL_GROUP.toFullString(),
- BASE_URL_GROUP_AND_VERSION.toFullString()), metadataService.getExportedURLs());
-
- assertTrue(metadataService.exportURL(REST_BASE_URL));
- exportedURLs = metadataService.getExportedURLs(TEST_SERVICE);
- assertEquals(asSortedSet(BASE_URL.toFullString(), REST_BASE_URL.toFullString()), exportedURLs);
-
- metadataService.exportURL(BASE_URL_GROUP_AND_VERSION_AND_PROTOCOL);
-
- exportedURLs = metadataService.getExportedURLs(TEST_SERVICE, "test", "1.0.0", "rest");
-
- assertEquals(asSortedSet(BASE_URL_GROUP_AND_VERSION_AND_PROTOCOL.toFullString()), exportedURLs);
- }
-
- @Test
- public void testGetSubscribedURLs() {
- assertTrue(metadataService.subscribeURL(BASE_URL));
- assertFalse(metadataService.subscribeURL(BASE_URL));
-
- assertTrue(metadataService.subscribeURL(BASE_URL_GROUP));
- assertTrue(metadataService.subscribeURL(BASE_URL_GROUP_AND_VERSION));
- assertTrue(metadataService.subscribeURL(REST_BASE_URL));
-
- Set<String> subscribedURLs = metadataService.getSubscribedURLs();
- assertEquals(4, subscribedURLs.size());
- assertEquals(asSortedSet(
- BASE_URL.toFullString(),
- REST_BASE_URL.toFullString(),
- BASE_URL_GROUP.toFullString(),
- BASE_URL_GROUP_AND_VERSION.toFullString()), subscribedURLs);
-
- assertTrue(metadataService.unsubscribeURL(REST_BASE_URL));
- subscribedURLs = metadataService.getSubscribedURLs();
- assertEquals(3, subscribedURLs.size());
- assertEquals(asSortedSet(
- BASE_URL.toFullString(),
- BASE_URL_GROUP.toFullString(),
- BASE_URL_GROUP_AND_VERSION.toFullString()), subscribedURLs);
-
- assertTrue(metadataService.unsubscribeURL(BASE_URL_GROUP));
- subscribedURLs = metadataService.getSubscribedURLs();
- assertEquals(2, subscribedURLs.size());
- assertEquals(asSortedSet(
- BASE_URL.toFullString(),
- BASE_URL_GROUP_AND_VERSION.toFullString()), subscribedURLs);
-
- assertTrue(metadataService.unsubscribeURL(BASE_URL_GROUP_AND_VERSION));
- subscribedURLs = metadataService.getSubscribedURLs();
- assertEquals(1, subscribedURLs.size());
- assertEquals(asSortedSet(
- BASE_URL.toFullString()), subscribedURLs);
- }
-
- private static <T extends Comparable<T>> SortedSet<T> asSortedSet(T... values) {
- return unmodifiableSortedSet(new TreeSet<>(asList(values)));
- }
-
-}
\ No newline at end of file
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataInfoTest.java
similarity index 61%
rename from dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java
rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataInfoTest.java
index 45fc8e0..fdb7021 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataInfoTest.java
@@ -16,21 +16,21 @@
*/
package org.apache.dubbo.metadata;
-import org.apache.dubbo.metadata.store.InMemoryWritableMetadataService;
+import org.apache.dubbo.common.URL;
import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.assertEquals;
+public class MetadataInfoTest {
+ @Test
+ public void revisionTest() {
+ MetadataInfo metadataInfo = new MetadataInfo("demo");
+ metadataInfo.setApp("demo");
-/**
- * {@link WritableMetadataService} Test
- *
- * @since 2.7.5
- */
-public class LocalMetadataServiceTest {
+ URL url = URL.valueOf("dubbo://10.230.11.211:20880/org.apache.dubbo.metadata.DemoService?timeout=1000&testKey=aaa");
+ MetadataInfo.ServiceInfo serviceInfo = new MetadataInfo.ServiceInfo(url);
+ metadataInfo.addService(serviceInfo);
- @Test
- public void testDefaultExtension() {
- assertEquals(InMemoryWritableMetadataService.class, WritableMetadataService.getDefaultExtension().getClass());
+ System.out.println(serviceInfo.toDescString());
+ System.out.println(metadataInfo.calAndGetRevision());
}
}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/ParameterizedServiceNameMappingTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/ParameterizedServiceNameMappingTest.java
deleted file mode 100644
index dbe5454..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/ParameterizedServiceNameMappingTest.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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.apache.dubbo.metadata;
-
-import org.apache.dubbo.common.URL;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import java.util.Arrays;
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-import static java.util.Collections.emptySet;
-import static java.util.Collections.singleton;
-import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-/**
- * {@link ParameterizedServiceNameMapping} Test
- *
- * @see ParameterizedServiceNameMapping
- * @since 2.7.8
- */
-public class ParameterizedServiceNameMappingTest {
-
- private static final URL BASE_URL = URL.valueOf("dubbo://127.0.0.1:20880");
-
- private ParameterizedServiceNameMapping serviceNameMapping;
-
- @BeforeEach
- public void init() {
- serviceNameMapping = new ParameterizedServiceNameMapping();
- }
-
- @Test
- public void testMap() {
- // NOTHING to happen
- serviceNameMapping.map(BASE_URL);
- }
-
- @Test
- public void testGet() {
- Set<String> serviceNames = serviceNameMapping.get(BASE_URL);
- assertEquals(emptySet(), serviceNames);
-
- serviceNames = serviceNameMapping.get(BASE_URL.addParameter(SUBSCRIBED_SERVICE_NAMES_KEY, " Service1 "));
- assertEquals(singleton("Service1"), serviceNames);
-
- serviceNames = serviceNameMapping.get(BASE_URL.addParameter(SUBSCRIBED_SERVICE_NAMES_KEY, "Service1 , Service2 "));
- assertEquals(new LinkedHashSet(Arrays.asList("Service1", "Service2")), serviceNames);
- }
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/PropertiesFileServiceNameMappingTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/PropertiesFileServiceNameMappingTest.java
deleted file mode 100644
index 68a6ebf..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/PropertiesFileServiceNameMappingTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.apache.dubbo.metadata;
-
-import org.apache.dubbo.common.URL;
-
-import org.junit.jupiter.api.Test;
-
-import java.util.Arrays;
-import java.util.LinkedHashSet;
-
-import static java.util.Collections.singleton;
-import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_NAME_MAPPING_PROPERTIES_FILE_KEY;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-/**
- * {@link PropertiesFileServiceNameMapping} Test
- *
- * @since 2.7.8
- */
-public class PropertiesFileServiceNameMappingTest {
-
- private static final URL BASE_URL = URL.valueOf("dubbo://127.0.0.1:20880");
-
-
- @Test
- public void testMap() {
- PropertiesFileServiceNameMapping serviceNameMapping = new PropertiesFileServiceNameMapping();
- serviceNameMapping.map(BASE_URL);
- }
-
- @Test
- public void testGet() {
-
- PropertiesFileServiceNameMapping serviceNameMapping = new PropertiesFileServiceNameMapping();
- URL url = BASE_URL.setServiceInterface("com.acme.Interface1").addParameter(GROUP_KEY, "default");
- assertEquals(singleton("Service1"), serviceNameMapping.get(url));
-
- System.setProperty(SERVICE_NAME_MAPPING_PROPERTIES_FILE_KEY, "///META-INF//dubbo/service-name-mapping.properties");
- serviceNameMapping = new PropertiesFileServiceNameMapping();
-
- url = BASE_URL.setProtocol("thirft").setServiceInterface("com.acme.InterfaceX");
- assertEquals(new LinkedHashSet<>(Arrays.asList("Service1", "Service2")), serviceNameMapping.get(url));
- }
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/ServiceNameMappingTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/ServiceNameMappingTest.java
index 8c37998..e4b4c1e 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/ServiceNameMappingTest.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/ServiceNameMappingTest.java
@@ -13,7 +13,8 @@
* 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.apache.dubbo.metadata;
import org.apache.dubbo.common.URL;
@@ -39,11 +40,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
+*/
/**
* {@link ServiceNameMapping} Test
*
* @since 2.7.8
- */
+ *//*
+
public class ServiceNameMappingTest {
private static final URL BASE_URL = URL.valueOf("dubbo://127.0.0.1:20880");
@@ -119,3 +122,4 @@ public class ServiceNameMappingTest {
}
}
+*/
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/URLRevisionResolverTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/URLRevisionResolverTest.java
deleted file mode 100644
index b36ebcb..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/URLRevisionResolverTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * 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.apache.dubbo.metadata;
-
-import org.junit.jupiter.api.Test;
-
-import java.util.Arrays;
-import java.util.Collection;
-
-import static java.util.Arrays.asList;
-import static org.apache.dubbo.metadata.URLRevisionResolver.UNKNOWN_REVISION;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-/**
- * {@link URLRevisionResolver} Test
- *
- * @since 2.7.5
- */
-public class URLRevisionResolverTest {
-
- private static final String URL = "dubbo://192.168.0.102:20881/org.apache.dubbo.metadata.URLRevisionResolverTest";
-
- private final URLRevisionResolver resolver = URLRevisionResolver.INSTANCE;
-
- @Test
- public void testResolve() {
- String revision = resolver.resolve(Arrays.<String>asList());
- assertEquals(UNKNOWN_REVISION, revision);
-
- revision = resolver.resolve((Collection<String>) null);
- assertEquals(UNKNOWN_REVISION, revision);
-
- revision = resolver.resolve(asList(URL));
- assertEquals("2ca0638f189ce569", revision);
- }
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java
index 3aa5c02..5b0ffd7 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java
@@ -1,135 +1,135 @@
-/*
- * 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.apache.dubbo.metadata.report.support;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.utils.NetUtils;
-import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
-import org.apache.dubbo.metadata.report.MetadataReport;
-import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
-import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
-import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
-
-import com.alibaba.fastjson.JSON;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.Test;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * 2018/9/14
- */
-public class AbstractMetadataReportFactoryTest {
-
- private AbstractMetadataReportFactory metadataReportFactory = new AbstractMetadataReportFactory() {
- @Override
- protected MetadataReport createMetadataReport(URL url) {
- return new MetadataReport() {
-
- @Override
- public void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) {
- store.put(providerMetadataIdentifier.getIdentifierKey(), JSON.toJSONString(serviceDefinition));
- }
-
- @Override
- public void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {
-
- }
-
- @Override
- public void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) {
-
- }
-
- @Override
- public List<String> getExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
- return null;
- }
-
- @Override
- public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier,
- Collection<String> urls) {
-
- }
-
- @Override
- public List<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
- return null;
- }
-
- @Override
- public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) {
- return null;
- }
-
- @Override
- public void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) {
- store.put(consumerMetadataIdentifier.getIdentifierKey(), JSON.toJSONString(serviceParameterMap));
- }
-
- @Override
- public void close() throws Exception {
-
- }
-
- Map<String, String> store = new ConcurrentHashMap<>();
-
-
- };
- }
- };
-
- @Test
- public void testGetOneMetadataReport() {
- URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
- MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url);
- MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url);
- Assertions.assertEquals(metadataReport1, metadataReport2);
- }
-
- @Test
- public void testGetOneMetadataReportForIpFormat() {
- String hostName = NetUtils.getLocalAddress().getHostName();
- String ip = NetUtils.getIpByHost(hostName);
- URL url1 = URL.valueOf("zookeeper://" + hostName + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
- URL url2 = URL.valueOf("zookeeper://" + ip + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
- MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1);
- MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2);
- Assertions.assertEquals(metadataReport1, metadataReport2);
- }
-
- @Test
- public void testGetForDiffService() {
- URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService1?version=1.0.0&application=vic");
- URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService2?version=1.0.0&application=vic");
- MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1);
- MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2);
- Assertions.assertEquals(metadataReport1, metadataReport2);
- }
-
- @Test
- public void testGetForDiffGroup() {
- URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=aaa");
- URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=bbb");
- MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1);
- MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2);
- Assertions.assertNotEquals(metadataReport1, metadataReport2);
- }
-}
+///*
+// * 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.apache.dubbo.metadata.report.support;
+//
+//import org.apache.dubbo.common.URL;
+//import org.apache.dubbo.common.utils.NetUtils;
+//import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
+//import org.apache.dubbo.metadata.report.MetadataReport;
+//import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
+//import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
+//import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
+//
+//import com.alibaba.fastjson.JSON;
+//import org.junit.jupiter.api.Assertions;
+//import org.junit.jupiter.api.Test;
+//
+//import java.util.Collection;
+//import java.util.List;
+//import java.util.Map;
+//import java.util.concurrent.ConcurrentHashMap;
+//
+///**
+// * 2018/9/14
+// */
+//public class AbstractMetadataReportFactoryTest {
+//
+// private AbstractMetadataReportFactory metadataReportFactory = new AbstractMetadataReportFactory() {
+// @Override
+// protected MetadataReport createMetadataReport(URL url) {
+// return new MetadataReport() {
+//
+// @Override
+// public void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) {
+// store.put(providerMetadataIdentifier.getIdentifierKey(), JSON.toJSONString(serviceDefinition));
+// }
+//
+// @Override
+// public void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {
+//
+// }
+//
+// @Override
+// public void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) {
+//
+// }
+//
+// @Override
+// public List<String> getExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
+// return null;
+// }
+//
+// @Override
+// public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier,
+// Collection<String> urls) {
+//
+// }
+//
+// @Override
+// public List<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
+// return null;
+// }
+//
+// @Override
+// public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) {
+// return null;
+// }
+//
+// @Override
+// public void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) {
+// store.put(consumerMetadataIdentifier.getIdentifierKey(), JSON.toJSONString(serviceParameterMap));
+// }
+//
+// @Override
+// public void close() throws Exception {
+//
+// }
+//
+// Map<String, String> store = new ConcurrentHashMap<>();
+//
+//
+// };
+// }
+// };
+//
+// @Test
+// public void testGetOneMetadataReport() {
+// URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
+// MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url);
+// MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url);
+// Assertions.assertEquals(metadataReport1, metadataReport2);
+// }
+//
+// @Test
+// public void testGetOneMetadataReportForIpFormat() {
+// String hostName = NetUtils.getLocalAddress().getHostName();
+// String ip = NetUtils.getIpByHost(hostName);
+// URL url1 = URL.valueOf("zookeeper://" + hostName + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
+// URL url2 = URL.valueOf("zookeeper://" + ip + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
+// MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1);
+// MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2);
+// Assertions.assertEquals(metadataReport1, metadataReport2);
+// }
+//
+// @Test
+// public void testGetForDiffService() {
+// URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService1?version=1.0.0&application=vic");
+// URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService2?version=1.0.0&application=vic");
+// MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1);
+// MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2);
+// Assertions.assertEquals(metadataReport1, metadataReport2);
+// }
+//
+// @Test
+// public void testGetForDiffGroup() {
+// URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=aaa");
+// URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=bbb");
+// MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1);
+// MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2);
+// Assertions.assertNotEquals(metadataReport1, metadataReport2);
+// }
+//}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java
index c5325a1..37b0d3c 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java
@@ -13,7 +13,8 @@
* 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.apache.dubbo.metadata.report.support;
import org.apache.dubbo.common.URL;
@@ -49,9 +50,19 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
+*/
/**
+ * Test {@link MetadataReport#saveExportedURLs(String, String, String)} method
*
- */
+ * @since 2.7.8
+ * <p>
+ * Test {@link MetadataReport#getExportedURLs(String, String)} method
+ * @since 2.7.8
+ * <p>
+ * Test {@link MetadataReport#getExportedURLsContent(String, String)} method
+ * @since 2.7.8
+ *//*
+
public class AbstractMetadataReportTest {
private NewMetadataReport abstractMetadataReport;
@@ -266,11 +277,19 @@ public class AbstractMetadataReportTest {
}
}
- /**
- * Test {@link MetadataReport#saveExportedURLs(String, String, String)} method
- *
- * @since 2.7.8
- */
+ */
+/**
+ * Test {@link MetadataReport#saveExportedURLs(String, String, String)} method
+ *
+ * @since 2.7.8
+ * <p>
+ * Test {@link MetadataReport#getExportedURLs(String, String)} method
+ * @since 2.7.8
+ * <p>
+ * Test {@link MetadataReport#getExportedURLsContent(String, String)} method
+ * @since 2.7.8
+ *//*
+
@Test
public void testSaveExportedURLs() {
String serviceName = null;
@@ -284,11 +303,13 @@ public class AbstractMetadataReportTest {
assertTrue(abstractMetadataReport.saveExportedURLs(serviceName, exportedServiceRevision, exportedURLsContent));
}
- /**
- * Test {@link MetadataReport#getExportedURLs(String, String)} method
- *
- * @since 2.7.8
- */
+ */
+/**
+ * Test {@link MetadataReport#getExportedURLs(String, String)} method
+ *
+ * @since 2.7.8
+ *//*
+
@Test
public void testGetExportedURLs() {
String serviceName = null;
@@ -296,11 +317,13 @@ public class AbstractMetadataReportTest {
assertEquals(emptySet(), abstractMetadataReport.getExportedURLs(serviceName, exportedServiceRevision));
}
- /**
- * Test {@link MetadataReport#getExportedURLsContent(String, String)} method
- *
- * @since 2.7.8
- */
+ */
+/**
+ * Test {@link MetadataReport#getExportedURLsContent(String, String)} method
+ *
+ * @since 2.7.8
+ *//*
+
@Test
public void testGetExportedURLsContent() {
String serviceName = null;
@@ -446,3 +469,4 @@ public class AbstractMetadataReportTest {
}
+*/
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/ConfigCenterBasedMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/ConfigCenterBasedMetadataReportTest.java
deleted file mode 100644
index 32205b9..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/ConfigCenterBasedMetadataReportTest.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * 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.apache.dubbo.metadata.report.support;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.config.ApplicationConfig;
-import org.apache.dubbo.metadata.URLRevisionResolver;
-import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder;
-import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
-import org.apache.dubbo.metadata.report.MetadataReport;
-import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
-import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
-import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
-import org.apache.dubbo.metadata.report.support.file.FileSystemMetadataReportFactory;
-import org.apache.dubbo.rpc.model.ApplicationModel;
-import org.apache.dubbo.rpc.service.EchoService;
-
-import com.google.gson.Gson;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import java.util.Collection;
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import static java.util.Collections.singleton;
-import static java.util.stream.Collectors.toSet;
-import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
-import static org.apache.dubbo.metadata.report.support.Constants.SYNC_REPORT_KEY;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNull;
-
-/**
- * {@link ConfigCenterBasedMetadataReport} Test-Cases
- *
- * @since 2.7.8
- */
-public class ConfigCenterBasedMetadataReportTest {
-
- private static final URL REPORT_SERVER_URL = URL.valueOf("file://")
- .addParameter(APPLICATION_KEY, "test")
- .addParameter(SYNC_REPORT_KEY, "true");
-
- private static final Class<EchoService> INTERFACE_CLASS = EchoService.class;
-
- private static final String INTERFACE_NAME = INTERFACE_CLASS.getName();
-
- private static final String APP_NAME = "test-service";
-
- private static final URL BASE_URL = URL
- .valueOf("dubbo://127.0.0.1:20880")
- .setPath(INTERFACE_NAME)
- .addParameter(APPLICATION_KEY, APP_NAME)
- .addParameter(SIDE_KEY, "provider");
-
- private ConfigCenterBasedMetadataReport metadataReport;
-
- @BeforeEach
- public void init() {
- ApplicationModel.getConfigManager().setApplication(new ApplicationConfig("test-service"));
- this.metadataReport = new FileSystemMetadataReportFactory().getMetadataReport(REPORT_SERVER_URL);
- }
-
- @AfterEach
- public void reset() throws Exception {
- ApplicationModel.reset();
- this.metadataReport.close();
- }
-
- /**
- * Test {@link MetadataReport#storeProviderMetadata(MetadataIdentifier, ServiceDefinition)} and
- * {@link MetadataReport#getServiceDefinition(MetadataIdentifier)}
- */
- @Test
- public void testStoreProviderMetadataAndGetServiceDefinition() {
- MetadataIdentifier metadataIdentifier = new MetadataIdentifier(BASE_URL);
- ServiceDefinition serviceDefinition = ServiceDefinitionBuilder.buildFullDefinition(INTERFACE_CLASS, BASE_URL.getParameters());
- metadataReport.storeProviderMetadata(metadataIdentifier, serviceDefinition);
- String serviceDefinitionJSON = metadataReport.getServiceDefinition(metadataIdentifier);
- assertEquals(serviceDefinitionJSON, new Gson().toJson(serviceDefinition));
- }
-
- /**
- * Test {@link MetadataReport#storeConsumerMetadata(MetadataIdentifier, Map)} and
- * {@link MetadataReport#getServiceDefinition(MetadataIdentifier)}
- */
- @Test
- public void testStoreConsumerMetadata() {
- MetadataIdentifier metadataIdentifier = new MetadataIdentifier(BASE_URL);
- metadataReport.storeConsumerMetadata(metadataIdentifier, BASE_URL.getParameters());
- String parametersJSON = metadataReport.getServiceDefinition(metadataIdentifier);
- assertEquals(parametersJSON, new Gson().toJson(BASE_URL.getParameters()));
- }
-
- /**
- * Test {@link MetadataReport#saveServiceMetadata(ServiceMetadataIdentifier, URL)} and
- * {@link MetadataReport#removeServiceMetadata(ServiceMetadataIdentifier)}
- */
- @Test
- public void testSaveServiceMetadataAndRemoveServiceMetadata() {
- ServiceMetadataIdentifier metadataIdentifier = new ServiceMetadataIdentifier(BASE_URL);
- metadataReport.saveServiceMetadata(metadataIdentifier, BASE_URL);
- String metadata = metadataReport.getMetadata(metadataIdentifier);
- assertEquals(URL.encode(BASE_URL.toFullString()), metadata);
- metadataReport.removeServiceMetadata(metadataIdentifier);
- assertNull(metadataReport.getMetadata(metadataIdentifier));
- }
-
- /**
- * Test {@link MetadataReport#saveSubscribedData(SubscriberMetadataIdentifier, Collection)} and
- * {@link MetadataReport#getSubscribedURLs(SubscriberMetadataIdentifier)}
- */
- @Test
- public void testSaveSubscribedDataAndGetSubscribedURLs() {
- SubscriberMetadataIdentifier metadataIdentifier = new SubscriberMetadataIdentifier(BASE_URL);
- Set<String> urls = singleton(BASE_URL).stream().map(URL::toIdentityString).collect(toSet());
- metadataReport.saveSubscribedData(metadataIdentifier, urls);
- Collection<String> subscribedURLs = metadataReport.getSubscribedURLs(metadataIdentifier);
- assertEquals(1, subscribedURLs.size());
- assertEquals(urls, subscribedURLs);
- }
-
- /**
- * Test {@link MetadataReport#saveExportedURLs(SortedSet)},
- * {@link MetadataReport#getExportedURLsContent(String, String)} and
- * {@link MetadataReport#getExportedURLs(String, String)}
- */
- @Test
- public void testSaveExportedURLsAndGetExportedURLs() {
- SortedSet<String> urls = singleton(BASE_URL).stream().map(URL::toIdentityString).collect(TreeSet::new, Set::add, Set::addAll);
- metadataReport.saveExportedURLs(urls);
-
- URLRevisionResolver urlRevisionResolver = URLRevisionResolver.INSTANCE;
- String revision = urlRevisionResolver.resolve(urls);
- assertEquals(urls, metadataReport.getExportedURLs(APP_NAME, revision));
- }
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InMemoryWritableMetadataServiceTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InMemoryWritableMetadataServiceTest.java
deleted file mode 100644
index b7db3fb..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InMemoryWritableMetadataServiceTest.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * 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.
- */
-
-/*
- * 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.apache.dubbo.metadata.store;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.utils.NetUtils;
-
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-/**
- * 2019-08-29
- */
-public class InMemoryWritableMetadataServiceTest {
-
- String interfaceName = "org.apache.dubbo.metadata.store.InterfaceNameTestService2", version = "0.9.9", group = null;
- URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/?interface=" + interfaceName + "&version="
- + version + "&application=vicpubprovder&side=provider");
-
- @BeforeEach
- public void before() {
- }
-
- @Test
- public void testPublishServiceDefinition() {
- InMemoryWritableMetadataService inMemoryWritableMetadataService = new InMemoryWritableMetadataService();
- inMemoryWritableMetadataService.publishServiceDefinition(url);
-
- String v = inMemoryWritableMetadataService.getServiceDefinition(interfaceName, version, group);
- Assertions.assertNotNull(v);
- }
-
- @Test
- public void testExportURL() {
- InMemoryWritableMetadataService inMemoryWritableMetadataService = new InMemoryWritableMetadataService();
- URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.Test567Service?version=1.0.44&application=vicpubprovder&side=provider");
- inMemoryWritableMetadataService.exportURL(url);
-
- Assertions.assertTrue(inMemoryWritableMetadataService.getExportedServiceURLs().size() == 1);
- Assertions.assertEquals(inMemoryWritableMetadataService.getExportedServiceURLs().get(url.getServiceKey()).first(), url);
- }
-
- @Test
- public void testSubscribeURL() {
- InMemoryWritableMetadataService inMemoryWritableMetadataService = new InMemoryWritableMetadataService();
- URL url = URL.valueOf("subscriber://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.Test678Service?version=1.0.44&application=vicpubprovder&side=provider");
- inMemoryWritableMetadataService.subscribeURL(url);
-
- Assertions.assertTrue(inMemoryWritableMetadataService.getSubscribedServiceURLs().size() == 1);
- Assertions.assertEquals(inMemoryWritableMetadataService.getSubscribedServiceURLs().get(url.getServiceKey()).first(), url);
- }
-
- @Test
- public void testUnExportURL() {
- InMemoryWritableMetadataService inMemoryWritableMetadataService = new InMemoryWritableMetadataService();
- URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.Test567Service?version=1.0.44&application=vicpubprovder&side=provider");
- inMemoryWritableMetadataService.exportURL(url);
-
- Assertions.assertTrue(inMemoryWritableMetadataService.getExportedServiceURLs().size() == 1);
- Assertions.assertEquals(inMemoryWritableMetadataService.getExportedServiceURLs().get(url.getServiceKey()).first(), url);
-
- inMemoryWritableMetadataService.unexportURL(url);
- Assertions.assertTrue(inMemoryWritableMetadataService.getExportedServiceURLs().size() == 0);
- }
-
- @Test
- public void testUnSubscribeURL() {
- InMemoryWritableMetadataService inMemoryWritableMetadataService = new InMemoryWritableMetadataService();
- URL url = URL.valueOf("subscriber://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.Test678Service?version=1.0.44&application=vicpubprovder&side=provider");
- inMemoryWritableMetadataService.subscribeURL(url);
-
- Assertions.assertTrue(inMemoryWritableMetadataService.getSubscribedServiceURLs().size() == 1);
- Assertions.assertEquals(inMemoryWritableMetadataService.getSubscribedServiceURLs().get(url.getServiceKey()).first(), url);
-
- inMemoryWritableMetadataService.unsubscribeURL(url);
- Assertions.assertTrue(inMemoryWritableMetadataService.getSubscribedServiceURLs().size() == 0);
- }
-
-}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RemoteWritableMetadataServiceTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RemoteWritableMetadataServiceTest.java
deleted file mode 100644
index e9ca89f..0000000
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RemoteWritableMetadataServiceTest.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * 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.apache.dubbo.metadata.store;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.utils.NetUtils;
-import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
-import org.apache.dubbo.metadata.report.MetadataReportInstance;
-import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
-import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
-import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
-import org.apache.dubbo.metadata.test.JTestMetadataReport4Test;
-import org.apache.dubbo.rpc.model.ApplicationModel;
-
-import com.google.gson.Gson;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import java.util.Map;
-
-/**
- * 2018/9/14
- */
-public class RemoteWritableMetadataServiceTest {
- URL url = URL.valueOf("JTest://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
- RemoteWritableMetadataService metadataReportService1;
-
- @BeforeEach
- public void before() {
- metadataReportService1 = new RemoteWritableMetadataService();
- MetadataReportInstance.init(url);
- }
-
- @Test
- public void testPublishProviderNoInterfaceName() {
- URL publishUrl = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vicpubprovder&side=provider");
- metadataReportService1.publishServiceDefinition(publishUrl);
-
- Assertions.assertTrue(metadataReportService1.getMetadataReport() instanceof JTestMetadataReport4Test);
-
- JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.getMetadataReport();
- Assertions.assertTrue(!jTestMetadataReport4Test.store.containsKey(JTestMetadataReport4Test.getProviderKey(publishUrl)));
-
- }
-
- @Test
- public void testPublishProviderWrongInterface() {
-
- URL publishUrl = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vicpu&interface=ccc&side=provider");
- metadataReportService1.publishServiceDefinition(publishUrl);
-
- Assertions.assertTrue(metadataReportService1.getMetadataReport() instanceof JTestMetadataReport4Test);
-
- JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.getMetadataReport();
- Assertions.assertTrue(!jTestMetadataReport4Test.store.containsKey(JTestMetadataReport4Test.getProviderKey(publishUrl)));
-
- }
-
- @Test
- public void testPublishProviderContainInterface() throws InterruptedException {
-
- URL publishUrl = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.3&application=vicpubp&interface=org.apache.dubbo.metadata.store.InterfaceNameTestService&side=provider");
- metadataReportService1.publishServiceDefinition(publishUrl);
- Thread.sleep(300);
-
- Assertions.assertTrue(metadataReportService1.getMetadataReport() instanceof JTestMetadataReport4Test);
-
- JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.getMetadataReport();
- Assertions.assertTrue(jTestMetadataReport4Test.store.containsKey(JTestMetadataReport4Test.getProviderKey(publishUrl)));
-
- String value = jTestMetadataReport4Test.store.get(JTestMetadataReport4Test.getProviderKey(publishUrl));
- FullServiceDefinition fullServiceDefinition = toServiceDefinition(value);
- Map<String, String> map = fullServiceDefinition.getParameters();
- Assertions.assertEquals(map.get("application"), "vicpubp");
- Assertions.assertEquals(map.get("version"), "1.0.3");
- Assertions.assertEquals(map.get("interface"), "org.apache.dubbo.metadata.store.InterfaceNameTestService");
- }
-
- @Test
- public void testPublishConsumer() throws InterruptedException {
-
- URL publishUrl = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.x&application=vicpubconsumer&side=consumer");
- metadataReportService1.publishServiceDefinition(publishUrl);
- Thread.sleep(300);
-
- Assertions.assertTrue(metadataReportService1.getMetadataReport() instanceof JTestMetadataReport4Test);
-
- JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.getMetadataReport();
- Assertions.assertTrue(jTestMetadataReport4Test.store.containsKey(JTestMetadataReport4Test.getConsumerKey(publishUrl)));
-
- String value = jTestMetadataReport4Test.store.get(JTestMetadataReport4Test.getConsumerKey(publishUrl));
- Gson gson = new Gson();
- Map<String, String> map = gson.fromJson(value, Map.class);
- Assertions.assertEquals(map.get("application"), "vicpubconsumer");
- Assertions.assertEquals(map.get("version"), "1.0.x");
-
- }
-
- @Test
- public void testPublishServiceDefinition() {
- URL publishUrl = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vicpubprovder&side=provider");
- metadataReportService1.publishServiceDefinition(publishUrl);
-
- Assertions.assertTrue(metadataReportService1.getMetadataReport() instanceof JTestMetadataReport4Test);
-
- JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.getMetadataReport();
- Assertions.assertTrue(!jTestMetadataReport4Test.store.containsKey(JTestMetadataReport4Test.getProviderKey(publishUrl)));
-
- }
-
- @Test
- public void testUnexportURL() {
-
- }
-
- @Test
- public void testRefreshMetadataService() throws InterruptedException {
- URL publishUrl = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestRefreshMetadataService?version=1.0.8&application=vicpubprovder&side=provider");
- URL publishUrl2 = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestRefreshMetadata2Service?version=1.0.5&application=vicpubprovder&side=provider");
- metadataReportService1.exportURL(publishUrl);
- metadataReportService1.exportURL(publishUrl2);
- String exportedRevision = "9999";
- JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.getMetadataReport();
- int origSize = jTestMetadataReport4Test.store.size();
- Assertions.assertTrue(metadataReportService1.refreshMetadata(exportedRevision, "1109"));
- Thread.sleep(200);
- int size = jTestMetadataReport4Test.store.size();
- Assertions.assertEquals(origSize, size);
- Assertions.assertNull(jTestMetadataReport4Test.store.get(getServiceMetadataIdentifier(publishUrl, exportedRevision).getUniqueKey(KeyTypeEnum.UNIQUE_KEY)));
- Assertions.assertNull(jTestMetadataReport4Test.store.get(getServiceMetadataIdentifier(publishUrl2, exportedRevision).getUniqueKey(KeyTypeEnum.UNIQUE_KEY)));
- }
-
- @Test
- public void testRefreshMetadataSubscription() throws InterruptedException {
- URL subscriberUrl1 = URL.valueOf("subscriber://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestRefreshMetadata00Service?version=1.0.8&application=vicpubprovder&side=provider");
- URL subscriberUrl2 = URL.valueOf("subscriber://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestRefreshMetadata09Service?version=1.0.5&application=vicpubprovder&side=provider");
- metadataReportService1.subscribeURL(subscriberUrl1);
- metadataReportService1.subscribeURL(subscriberUrl2);
- String exportedRevision = "9999";
- String subscriberRevision = "2099";
- String applicationName = "wriableMetadataService";
- JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.getMetadataReport();
- int origSize = jTestMetadataReport4Test.store.size();
- ApplicationModel.setApplication(applicationName);
- Assertions.assertTrue(metadataReportService1.refreshMetadata(exportedRevision, subscriberRevision));
- Thread.sleep(200);
- int size = jTestMetadataReport4Test.store.size();
- Assertions.assertEquals(origSize, size);
- String r = jTestMetadataReport4Test.store.get(getSubscriberMetadataIdentifier(
- subscriberRevision).getUniqueKey(KeyTypeEnum.UNIQUE_KEY));
- Assertions.assertNull(r);
- }
-
- private ServiceMetadataIdentifier getServiceMetadataIdentifier(URL publishUrl, String exportedRevision) {
- ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(publishUrl);
- serviceMetadataIdentifier.setRevision(exportedRevision);
- serviceMetadataIdentifier.setProtocol(publishUrl.getProtocol());
- return serviceMetadataIdentifier;
- }
-
- private SubscriberMetadataIdentifier getSubscriberMetadataIdentifier(String subscriberRevision) {
- SubscriberMetadataIdentifier subscriberMetadataIdentifier = new SubscriberMetadataIdentifier();
- subscriberMetadataIdentifier.setRevision(subscriberRevision);
- subscriberMetadataIdentifier.setApplication(ApplicationModel.getApplication());
- return subscriberMetadataIdentifier;
- }
-
- private FullServiceDefinition toServiceDefinition(String urlQuery) {
- Gson gson = new Gson();
- return gson.fromJson(urlQuery, FullServiceDefinition.class);
- }
-
-}
diff --git a/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java
index e6b7054..c1e0a30 100644
--- a/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java
+++ b/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java
@@ -27,7 +27,6 @@ import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReport;
-import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReport;
import org.apache.dubbo.rpc.RpcException;
import com.ecwid.consul.v1.ConsulClient;
@@ -41,10 +40,7 @@ import java.util.List;
/**
* metadata report impl for consul
- *
- * @deprecated 2.7.8 This class will be removed in the future, {@link ConfigCenterBasedMetadataReport} as a substitute.
*/
-@Deprecated
public class ConsulMetadataReport extends AbstractMetadataReport {
private static final Logger logger = LoggerFactory.getLogger(ConsulMetadataReport.class);
private static final int DEFAULT_PORT = 8500;
diff --git a/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java
index 7f5f190..1d1f5bb 100644
--- a/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java
+++ b/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java
@@ -17,15 +17,16 @@
package org.apache.dubbo.metadata.store.consul;
-import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
-import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReportFactory;
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.metadata.report.MetadataReport;
+import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory;
/**
* metadata report factory impl for consul
*/
-public class ConsulMetadataReportFactory extends ConfigCenterBasedMetadataReportFactory {
-
- public ConsulMetadataReportFactory() {
- super(KeyTypeEnum.UNIQUE_KEY);
+public class ConsulMetadataReportFactory extends AbstractMetadataReportFactory {
+ @Override
+ protected MetadataReport createMetadataReport(URL url) {
+ return new ConsulMetadataReport(url);
}
}
diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java
index 2d2efd5..ceaa54a 100644
--- a/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java
+++ b/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java
@@ -55,7 +55,7 @@ public class EtcdMetadataReportTest {
private static final String TEST_SERVICE = "org.apache.dubbo.metadata.store.etcd.EtcdMetadata4TstService";
- private EtcdCluster etcdCluster = EtcdClusterFactory.buildCluster(getClass().getSimpleName(), 1, false, false);
+ private EtcdCluster etcdCluster = EtcdClusterFactory.buildCluster(getClass().getSimpleName(), 1, false);
private Client etcdClientForTest;
private EtcdMetadataReport etcdMetadataReport;
private URL registryUrl;
diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java
index 5c413d8..707d2b8 100644
--- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java
+++ b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java
@@ -18,7 +18,6 @@
package org.apache.dubbo.metadata.store.nacos;
import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
@@ -28,36 +27,132 @@ import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReport;
-import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReport;
import org.apache.dubbo.rpc.RpcException;
+import com.alibaba.nacos.api.NacosFactory;
+import com.alibaba.nacos.api.config.ConfigService;
+import com.alibaba.nacos.api.exception.NacosException;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-
-import static java.util.concurrent.TimeUnit.SECONDS;
+import java.util.Properties;
+
+import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY;
+import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME;
+import static com.alibaba.nacos.api.PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT;
+import static com.alibaba.nacos.api.PropertyKeyConst.CONFIG_RETRY_TIME;
+import static com.alibaba.nacos.api.PropertyKeyConst.CONTEXT_PATH;
+import static com.alibaba.nacos.api.PropertyKeyConst.ENABLE_REMOTE_SYNC_CONFIG;
+import static com.alibaba.nacos.api.PropertyKeyConst.ENCODE;
+import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT;
+import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT_PORT;
+import static com.alibaba.nacos.api.PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING;
+import static com.alibaba.nacos.api.PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE;
+import static com.alibaba.nacos.api.PropertyKeyConst.MAX_RETRY;
+import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE;
+import static com.alibaba.nacos.api.PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT;
+import static com.alibaba.nacos.api.PropertyKeyConst.NAMING_LOAD_CACHE_AT_START;
+import static com.alibaba.nacos.api.PropertyKeyConst.NAMING_POLLING_THREAD_COUNT;
+import static com.alibaba.nacos.api.PropertyKeyConst.RAM_ROLE_NAME;
+import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY;
+import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR;
+import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME;
+import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
+import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY;
/**
* metadata report impl for nacos
- *
- * @deprecated 2.7.8 This class will be removed in the future, {@link ConfigCenterBasedMetadataReport} as a substitute.
*/
-@Deprecated
public class NacosMetadataReport extends AbstractMetadataReport {
private static final Logger logger = LoggerFactory.getLogger(NacosMetadataReport.class);
- private final DynamicConfiguration dynamicConfiguration;
+ private ConfigService configService;
/**
* The group used to store metadata in Nacos
*/
private String group;
- public NacosMetadataReport(URL url, DynamicConfiguration dynamicConfiguration) {
+
+ public NacosMetadataReport(URL url) {
super(url);
- this.dynamicConfiguration = dynamicConfiguration;
+ this.configService = buildConfigService(url);
+ group = url.getParameter(GROUP_KEY, DEFAULT_ROOT);
+ }
+
+ public ConfigService buildConfigService(URL url) {
+ Properties nacosProperties = buildNacosProperties(url);
+ try {
+ configService = NacosFactory.createConfigService(nacosProperties);
+ } catch (NacosException e) {
+ if (logger.isErrorEnabled()) {
+ logger.error(e.getErrMsg(), e);
+ }
+ throw new IllegalStateException(e);
+ }
+ return configService;
+ }
+
+ private Properties buildNacosProperties(URL url) {
+ Properties properties = new Properties();
+ setServerAddr(url, properties);
+ setProperties(url, properties);
+ return properties;
+ }
+
+ private void setServerAddr(URL url, Properties properties) {
+ StringBuilder serverAddrBuilder =
+ new StringBuilder(url.getHost()) // Host
+ .append(":")
+ .append(url.getPort()); // Port
+ // Append backup parameter as other servers
+ String backup = url.getParameter(BACKUP_KEY);
+ if (backup != null) {
+ serverAddrBuilder.append(",").append(backup);
+ }
+ String serverAddr = serverAddrBuilder.toString();
+ properties.put(SERVER_ADDR, serverAddr);
+ }
+
+ private static void setProperties(URL url, Properties properties) {
+ putPropertyIfAbsent(url, properties, NACOS_NAMING_LOG_NAME);
+ putPropertyIfAbsent(url, properties, IS_USE_CLOUD_NAMESPACE_PARSING);
+ putPropertyIfAbsent(url, properties, IS_USE_ENDPOINT_PARSING_RULE);
+ putPropertyIfAbsent(url, properties, ENDPOINT);
+ putPropertyIfAbsent(url, properties, ENDPOINT_PORT);
+ putPropertyIfAbsent(url, properties, NAMESPACE);
+ putPropertyIfAbsent(url, properties, ACCESS_KEY);
+ putPropertyIfAbsent(url, properties, SECRET_KEY);
+ putPropertyIfAbsent(url, properties, RAM_ROLE_NAME);
+ putPropertyIfAbsent(url, properties, CONTEXT_PATH);
+ putPropertyIfAbsent(url, properties, CLUSTER_NAME);
+ putPropertyIfAbsent(url, properties, ENCODE);
+ putPropertyIfAbsent(url, properties, CONFIG_LONG_POLL_TIMEOUT);
+ putPropertyIfAbsent(url, properties, CONFIG_RETRY_TIME);
+ putPropertyIfAbsent(url, properties, MAX_RETRY);
+ putPropertyIfAbsent(url, properties, ENABLE_REMOTE_SYNC_CONFIG);
+ putPropertyIfAbsent(url, properties, NAMING_LOAD_CACHE_AT_START, "true");
+ putPropertyIfAbsent(url, properties, NAMING_CLIENT_BEAT_THREAD_COUNT);
+ putPropertyIfAbsent(url, properties, NAMING_POLLING_THREAD_COUNT);
+ }
+
+ private static void putPropertyIfAbsent(URL url, Properties properties, String propertyName) {
+ String propertyValue = url.getParameter(propertyName);
+ if (StringUtils.isNotEmpty(propertyValue)) {
+ properties.setProperty(propertyName, propertyValue);
+ }
+ }
+
+ private static void putPropertyIfAbsent(URL url, Properties properties, String propertyName, String defaultValue) {
+ String propertyValue = url.getParameter(propertyName);
+ if (StringUtils.isNotEmpty(propertyValue)) {
+ properties.setProperty(propertyName, propertyValue);
+ } else {
+ properties.setProperty(propertyName, defaultValue);
+ }
}
@Override
@@ -104,19 +199,9 @@ public class NacosMetadataReport extends AbstractMetadataReport {
return getConfig(metadataIdentifier);
}
- @Override
- public boolean saveExportedURLs(String serviceName, String exportedServicesRevision, String exportedURLsContent) {
- return dynamicConfiguration.publishConfig(serviceName, exportedServicesRevision, exportedURLsContent);
- }
-
- @Override
- public String getExportedURLsContent(String serviceName, String exportedServicesRevision) {
- return dynamicConfiguration.getConfig(serviceName, exportedServicesRevision, SECONDS.toMillis(3));
- }
-
private void storeMetadata(BaseMetadataIdentifier identifier, String value) {
try {
- boolean publishResult = dynamicConfiguration.publishConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, value);
+ boolean publishResult = configService.publishConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, value);
if (!publishResult) {
throw new RuntimeException("publish nacos metadata failed");
}
@@ -128,7 +213,7 @@ public class NacosMetadataReport extends AbstractMetadataReport {
private void deleteMetadata(BaseMetadataIdentifier identifier) {
try {
- boolean publishResult = dynamicConfiguration.removeConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group);
+ boolean publishResult = configService.removeConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group);
if (!publishResult) {
throw new RuntimeException("remove nacos metadata failed");
}
@@ -140,7 +225,7 @@ public class NacosMetadataReport extends AbstractMetadataReport {
private String getConfig(BaseMetadataIdentifier identifier) {
try {
- return dynamicConfiguration.getConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, 300);
+ return configService.getConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, 300);
} catch (Throwable t) {
logger.error("Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t);
throw new RpcException("Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t);
diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java
index 8c8d5a2..2cff74c 100644
--- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java
+++ b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java
@@ -17,15 +17,16 @@
package org.apache.dubbo.metadata.store.nacos;
-import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
-import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReportFactory;
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.metadata.report.MetadataReport;
+import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory;
/**
* metadata report factory impl for nacos
*/
-public class NacosMetadataReportFactory extends ConfigCenterBasedMetadataReportFactory {
-
- public NacosMetadataReportFactory() {
- super(KeyTypeEnum.UNIQUE_KEY);
+public class NacosMetadataReportFactory extends AbstractMetadataReportFactory {
+ @Override
+ protected MetadataReport createMetadataReport(URL url) {
+ return new NacosMetadataReport(url);
}
}
diff --git a/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java
index 3a74f8d..b221a5b 100644
--- a/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java
+++ b/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java
@@ -16,37 +16,40 @@
*/
package org.apache.dubbo.metadata.store.zookeeper;
+import com.google.gson.Gson;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
-import org.apache.dubbo.common.utils.PathUtils;
import org.apache.dubbo.common.utils.StringUtils;
+import org.apache.dubbo.metadata.MappingChangedEvent;
+import org.apache.dubbo.metadata.MappingListener;
+import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReport;
-import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReport;
+import org.apache.dubbo.remoting.zookeeper.ChildListener;
import org.apache.dubbo.remoting.zookeeper.ZookeeperClient;
import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
-import static org.apache.dubbo.metadata.MetadataConstants.DEFAULT_PATH_TAG;
-import static org.apache.dubbo.metadata.MetadataConstants.EXPORTED_URLS_TAG;
/**
* ZookeeperMetadataReport
- *
- * @deprecated 2.7.8 This class will be removed in the future, {@link ConfigCenterBasedMetadataReport} as a substitute.
*/
-@Deprecated
public class ZookeeperMetadataReport extends AbstractMetadataReport {
private final static Logger logger = LoggerFactory.getLogger(ZookeeperMetadataReport.class);
@@ -55,6 +58,10 @@ public class ZookeeperMetadataReport extends AbstractMetadataReport {
final ZookeeperClient zkClient;
+ private Gson gson = new Gson();
+
+ private Map<String, ChildListener> listenerMap = new ConcurrentHashMap<>();
+
public ZookeeperMetadataReport(URL url, ZookeeperTransporter zookeeperTransporter) {
super(url);
if (url.isAnyHost()) {
@@ -128,25 +135,49 @@ public class ZookeeperMetadataReport extends AbstractMetadataReport {
}
@Override
- public boolean saveExportedURLs(String serviceName, String exportedServicesRevision, String exportedURLsContent) {
- String path = buildExportedURLsMetadataPath(serviceName, exportedServicesRevision);
- zkClient.create(path, exportedURLsContent, false);
- return true;
+ public void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {
+ String path = getNodePath(identifier);
+ if (StringUtils.isBlank(zkClient.getContent(path))) {
+ zkClient.create(path, gson.toJson(metadataInfo), false);
+ }
}
@Override
- public String getExportedURLsContent(String serviceName, String exportedServicesRevision) {
- String path = buildExportedURLsMetadataPath(serviceName, exportedServicesRevision);
- String content = zkClient.getContent(path);
- return content;
+ public void registerServiceAppMapping(String serviceKey, String application, URL url) {
+ String path = toRootDir() + serviceKey + PATH_SEPARATOR + application;
+ if (StringUtils.isBlank(zkClient.getContent(path))) {
+ Map<String, String> value = new HashMap<>();
+ value.put("timestamp", String.valueOf(System.currentTimeMillis()));
+ zkClient.create(path, gson.toJson(value), false);
+ }
}
- private String buildExportedURLsMetadataPath(String serviceName, String exportedServicesRevision) {
- return buildPath(DEFAULT_PATH_TAG, EXPORTED_URLS_TAG, serviceName, exportedServicesRevision);
+ @Override
+ public MetadataInfo getAppMetadata(SubscriberMetadataIdentifier identifier, Map<String, String> instanceMetadata) {
+ String content = zkClient.getContent(getNodePath(identifier));
+ return gson.fromJson(content, MetadataInfo.class);
}
- private String buildPath(String... paths) {
- return PathUtils.buildPath(toRootDir(), paths);
- }
+ @Override
+ public Set<String> getServiceAppMapping(String serviceKey, MappingListener listener, URL url) {
+ Set<String> appNameSet = new HashSet<>();
+ String path = toRootDir() + serviceKey;
+ appNameSet.addAll(zkClient.getChildren(path));
+
+ if (null == listenerMap.get(path)) {
+ ChildListener zkListener = new ChildListener() {
+ @Override
+ public void childChanged(String path, List<String> children) {
+ MappingChangedEvent event = new MappingChangedEvent();
+ event.setServiceKey(serviceKey);
+ event.setApps(null != children ? new HashSet<>(children): null);
+ listener.onEvent(event);
+ }
+ };
+ zkClient.addChildListener(path, zkListener);
+ listenerMap.put(path, zkListener);
+ }
+ return appNameSet;
+ }
}
diff --git a/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java
index 4773e1e..0ffed8d 100644
--- a/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java
+++ b/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java
@@ -16,17 +16,25 @@
*/
package org.apache.dubbo.metadata.store.zookeeper;
-import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
-import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReportFactory;
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.metadata.report.MetadataReport;
+import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory;
+import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter;
/**
* ZookeeperRegistryFactory.
- *
- * @revised 2.7.8 {@link ConfigCenterBasedMetadataReportFactory}
*/
-public class ZookeeperMetadataReportFactory extends ConfigCenterBasedMetadataReportFactory {
+public class ZookeeperMetadataReportFactory extends AbstractMetadataReportFactory {
+
+ private ZookeeperTransporter zookeeperTransporter;
- public ZookeeperMetadataReportFactory() {
- super(KeyTypeEnum.PATH);
+ public void setZookeeperTransporter(ZookeeperTransporter zookeeperTransporter) {
+ this.zookeeperTransporter = zookeeperTransporter;
}
+
+ @Override
+ public MetadataReport createMetadataReport(URL url) {
+ return new ZookeeperMetadataReport(url, zookeeperTransporter);
+ }
+
}
diff --git a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java
index 2180b27..dce7e51 100644
--- a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java
+++ b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java
@@ -119,7 +119,7 @@ public class MonitorFilterTest {
public void testFilter() throws Exception {
MonitorFilter monitorFilter = new MonitorFilter();
monitorFilter.setMonitorFactory(monitorFactory);
- Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), new Class<?>[0], new Object[0]);
+ Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]);
RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345);
Result result = monitorFilter.invoke(serviceInvoker, invocation);
result.whenCompleteWithContext((r, t) -> {
@@ -149,7 +149,7 @@ public class MonitorFilterTest {
MonitorFilter monitorFilter = new MonitorFilter();
MonitorFactory mockMonitorFactory = mock(MonitorFactory.class);
monitorFilter.setMonitorFactory(mockMonitorFactory);
- Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), new Class<?>[0], new Object[0]);
+ Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]);
Invoker invoker = mock(Invoker.class);
given(invoker.getUrl()).willReturn(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + APPLICATION_KEY + "=abc&" + SIDE_KEY + "=" + CONSUMER_SIDE));
@@ -162,7 +162,7 @@ public class MonitorFilterTest {
public void testGenericFilter() throws Exception {
MonitorFilter monitorFilter = new MonitorFilter();
monitorFilter.setMonitorFactory(monitorFactory);
- Invocation invocation = new RpcInvocation("$invoke", MonitorService.class.getName(), new Class<?>[]{String.class, String[].class, Object[].class}, new Object[]{"xxx", new String[]{}, new Object[]{}});
+ Invocation invocation = new RpcInvocation("$invoke", MonitorService.class.getName(), "", new Class<?>[]{String.class, String[].class, Object[].class}, new Object[]{"xxx", new String[]{}, new Object[]{}});
RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345);
Result result = monitorFilter.invoke(serviceInvoker, invocation);
result.whenCompleteWithContext((r, t) -> {
@@ -196,7 +196,7 @@ public class MonitorFilterTest {
monitorFilter.setMonitorFactory(mockMonitorFactory);
given(mockMonitorFactory.getMonitor(any(URL.class))).willReturn(mockMonitor);
- Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), new Class<?>[0], new Object[0]);
+ Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]);
monitorFilter.invoke(serviceInvoker, invocation);
}
diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java
index c1808c5..0583259 100644
--- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java
+++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java
@@ -116,7 +116,7 @@ public class MetricsFilterTest {
IMetricManager metricManager = MetricManager.getIMetricManager();
metricManager.clear();
MetricsFilter metricsFilter = new MetricsFilter();
- Invocation invocation = new RpcInvocation("sayName", DemoService.class.getName(), new Class<?>[]{Integer.class}, new Object[0]);
+ Invocation invocation = new RpcInvocation("sayName", DemoService.class.getName(), "", new Class<?>[]{Integer.class}, new Object[0]);
RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345);
RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(SIDE_KEY, CONSUMER_SIDE));
AppResponse response = AppResponseBuilder.create()
@@ -144,7 +144,7 @@ public class MetricsFilterTest {
IMetricManager metricManager = MetricManager.getIMetricManager();
metricManager.clear();
MetricsFilter metricsFilter = new MetricsFilter();
- Invocation invocation = new RpcInvocation("timeoutException", DemoService.class.getName(), null, null);
+ Invocation invocation = new RpcInvocation("timeoutException", DemoService.class.getName(), "", null, null);
RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345);
RpcContext.getContext().setUrl(timeoutInvoker.getUrl().addParameter(SIDE_KEY, CONSUMER_SIDE)
.addParameter(TIMEOUT_KEY, 300));
@@ -177,7 +177,7 @@ public class MetricsFilterTest {
IMetricManager metricManager = MetricManager.getIMetricManager();
metricManager.clear();
MetricsFilter metricsFilter = new MetricsFilter();
- Invocation invocation = new RpcInvocation("sayName", DemoService.class.getName(), new Class<?>[0], new Object[0]);
+ Invocation invocation = new RpcInvocation("sayName", DemoService.class.getName(), "", new Class<?>[0], new Object[0]);
RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345);
RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(SIDE_KEY, PROVIDER));
AppResponse response = AppResponseBuilder.create()
@@ -204,7 +204,7 @@ public class MetricsFilterTest {
IMetricManager metricManager = MetricManager.getIMetricManager();
metricManager.clear();
MetricsFilter metricsFilter = new MetricsFilter();
- Invocation invocation = new RpcInvocation("sayName", DemoService.class.getName(), new Class<?>[0], new Object[0]);
+ Invocation invocation = new RpcInvocation("sayName", DemoService.class.getName(), "", new Class<?>[0], new Object[0]);
RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345);
RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(SIDE_KEY, PROVIDER_SIDE)
.addParameter(TIMEOUT_KEY, 300));
@@ -222,7 +222,7 @@ public class MetricsFilterTest {
Protocol protocol = new DubboProtocol();
URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":20880/" + MetricsService.class.getName());
Invoker<MetricsService> invoker = protocol.refer(MetricsService.class, url);
- invocation = new RpcInvocation("getMetricsByGroup", DemoService.class.getName(), new Class<?>[]{String.class}, new Object[]{DUBBO_GROUP});
+ invocation = new RpcInvocation("getMetricsByGroup", DemoService.class.getName(), "", new Class<?>[]{String.class}, new Object[]{DUBBO_GROUP});
try {
Thread.sleep(5000);
} catch (Exception e) {
@@ -251,13 +251,13 @@ public class MetricsFilterTest {
IMetricManager metricManager = MetricManager.getIMetricManager();
metricManager.clear();
MetricsFilter metricsFilter = new MetricsFilter();
- Invocation sayNameInvocation = new RpcInvocation("sayName", DemoService.class.getName(), new Class<?>[0], new Object[0]);
- Invocation echoInvocation = new RpcInvocation("echo", DemoService.class.getName(), new Class<?>[]{Integer.class}, new Integer[]{1});
+ Invocation sayNameInvocation = new RpcInvocation("sayName", DemoService.class.getName(), "", new Class<?>[0], new Object[0]);
+ Invocation echoInvocation = new RpcInvocation("echo", DemoService.class.getName(), "", new Class<?>[]{Integer.class}, new Integer[]{1});
RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345);
RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(SIDE_KEY, PROVIDER_SIDE)
- .addParameter(TIMEOUT_KEY, 300));
+ .addParameter(TIMEOUT_KEY, 300));
AppResponse response = AppResponseBuilder.create()
- .build();
+ .build();
onInvokeReturns(response);
for (int i = 0; i < 50; i++) {
metricsFilter.invoke(serviceInvoker, sayNameInvocation);
@@ -277,7 +277,7 @@ public class MetricsFilterTest {
Protocol protocol = new DubboProtocol();
URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":20880/" + MetricsService.class.getName());
Invoker<MetricsService> invoker = protocol.refer(MetricsService.class, url);
- Invocation invocation = new RpcInvocation("getMetricsByGroup", DemoService.class.getName(), new Class<?>[]{String.class}, new Object[]{DUBBO_GROUP});
+ Invocation invocation = new RpcInvocation("getMetricsByGroup", DemoService.class.getName(), "", new Class<?>[]{String.class}, new Object[]{DUBBO_GROUP});
try {
Thread.sleep(15000);
} catch (Exception e) {
diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.java
new file mode 100644
index 0000000..990854c
--- /dev/null
+++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.java
@@ -0,0 +1,63 @@
+/*
+ * 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.apache.dubbo.qos.command.impl;
+
+import org.apache.dubbo.common.extension.ExtensionLoader;
+import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
+import org.apache.dubbo.common.utils.ArrayUtils;
+import org.apache.dubbo.qos.command.BaseCommand;
+import org.apache.dubbo.qos.command.CommandContext;
+import org.apache.dubbo.qos.command.annotation.Cmd;
+import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils;
+
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+
+@Cmd(name = "publishMetadata", summary = "update service metadata and service instance", example = {
+ "publishMetadata",
+ "publishMetadata 5"
+})
+public class PublishMetadata implements BaseCommand {
+ private static final Logger logger = LoggerFactory.getLogger(PublishMetadata.class);
+ private final ExecutorRepository executorRepository = ExtensionLoader.getExtensionLoader(ExecutorRepository.class).getDefaultExtension();
+ private ScheduledFuture future;
+
+ @Override
+ public String execute(CommandContext commandContext, String[] args) {
+ logger.info("received publishMetadata command.");
+
+ if (ArrayUtils.isEmpty(args)) {
+ ServiceInstanceMetadataUtils.refreshMetadataAndInstance();
+ return "publish metadata succeeded.";
+ }
+
+ try {
+ int delay = Integer.parseInt(args[0]);
+ if (future == null || future.isDone() || future.isCancelled()) {
+ future = executorRepository.nextScheduledExecutor()
+ .scheduleWithFixedDelay(ServiceInstanceMetadataUtils::refreshMetadataAndInstance, 0, delay, TimeUnit.MILLISECONDS);
+ }
+ } catch (NumberFormatException e) {
+ logger.error("Wrong delay param", e);
+ return "publishMetadata failed! Wrong delay param!";
+ }
+ return "publish task submitted, will publish in " + args[0] + " seconds.";
+ }
+
+}
diff --git a/dubbo-plugin/dubbo-qos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.qos.command.BaseCommand b/dubbo-plugin/dubbo-qos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.qos.command.BaseCommand
index cb6e9a7..b92b6b2 100644
--- a/dubbo-plugin/dubbo-qos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.qos.command.BaseCommand
+++ b/dubbo-plugin/dubbo-qos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.qos.command.BaseCommand
@@ -5,3 +5,4 @@ ls=org.apache.dubbo.qos.command.impl.Ls
offline=org.apache.dubbo.qos.command.impl.Offline
ready=org.apache.dubbo.qos.command.impl.Ready
version=org.apache.dubbo.qos.command.impl.Version
+publish-metadata=org.apache.dubbo.qos.command.impl.PublishMetadata
diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java
index 812d5c7..20cd04b 100644
--- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java
+++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java
@@ -21,9 +21,11 @@ import org.apache.dubbo.qos.command.impl.Help;
import org.apache.dubbo.qos.command.impl.Ls;
import org.apache.dubbo.qos.command.impl.Offline;
import org.apache.dubbo.qos.command.impl.Online;
+import org.apache.dubbo.qos.command.impl.PublishMetadata;
import org.apache.dubbo.qos.command.impl.Quit;
import org.apache.dubbo.qos.command.impl.Ready;
import org.apache.dubbo.qos.command.impl.Version;
+
import org.junit.jupiter.api.Test;
import java.util.List;
@@ -47,7 +49,7 @@ public class CommandHelperTest {
List<Class<?>> classes = CommandHelper.getAllCommandClass();
assertThat(classes,
containsInAnyOrder(GreetingCommand.class, Help.class, Ls.class, Offline.class, Online.class, Quit.class,
- Ready.class, Version.class));
+ Ready.class, Version.class, PublishMetadata.class));
}
@Test
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/NotifyListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/NotifyListener.java
index 0e41cc9..89e3e75 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/NotifyListener.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/NotifyListener.java
@@ -17,6 +17,7 @@
package org.apache.dubbo.registry;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import java.util.List;
@@ -41,4 +42,7 @@ public interface NotifyListener {
*/
void notify(List<URL> urls);
+ default void addServiceListener(ServiceInstancesChangedListener instanceListener) {
+ }
+
}
\ No newline at end of file
diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/proxy/MyMetadataServiceProxyFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java
similarity index 62%
copy from dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/proxy/MyMetadataServiceProxyFactory.java
copy to dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java
index 86247e1..bebc73a 100644
--- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/proxy/MyMetadataServiceProxyFactory.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java
@@ -14,16 +14,23 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.registry.client.metadata.proxy;
+package org.apache.dubbo.registry.client;
-import org.apache.dubbo.metadata.MetadataService;
-import org.apache.dubbo.metadata.store.InMemoryWritableMetadataService;
-import org.apache.dubbo.registry.client.ServiceInstance;
+public abstract class AbstractServiceDiscovery implements ServiceDiscovery {
-public class MyMetadataServiceProxyFactory extends BaseMetadataServiceProxyFactory {
+ protected ServiceInstance serviceInstance;
@Override
- protected MetadataService createProxy(ServiceInstance serviceInstance) {
- return new InMemoryWritableMetadataService();
+ public ServiceInstance getLocalInstance() {
+ return serviceInstance;
+ }
+
+ @Override
+ public void register(ServiceInstance serviceInstance) throws RuntimeException {
+ }
+
+ @Override
+ public void update(ServiceInstance serviceInstance) throws RuntimeException {
+ this.serviceInstance = serviceInstance;
}
}
diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/proxy/MyMetadataServiceProxyFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultRegistryClusterIdentifier.java
similarity index 64%
copy from dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/proxy/MyMetadataServiceProxyFactory.java
copy to dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultRegistryClusterIdentifier.java
index 86247e1..42cc10b 100644
--- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/proxy/MyMetadataServiceProxyFactory.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultRegistryClusterIdentifier.java
@@ -14,16 +14,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.registry.client.metadata.proxy;
+package org.apache.dubbo.registry.client;
-import org.apache.dubbo.metadata.MetadataService;
-import org.apache.dubbo.metadata.store.InMemoryWritableMetadataService;
-import org.apache.dubbo.registry.client.ServiceInstance;
+import org.apache.dubbo.common.URL;
-public class MyMetadataServiceProxyFactory extends BaseMetadataServiceProxyFactory {
+import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY;
+public class DefaultRegistryClusterIdentifier implements RegistryClusterIdentifier {
@Override
- protected MetadataService createProxy(ServiceInstance serviceInstance) {
- return new InMemoryWritableMetadataService();
+ public String providerKey(URL url) {
+ return url.getParameter(REGISTRY_CLUSTER_KEY);
+ }
+
+ @Override
+ public String consumerKey(URL url) {
+ return url.getParameter(REGISTRY_CLUSTER_KEY);
}
}
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java
index 366f607..eb581f9 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java
@@ -16,10 +16,14 @@
*/
package org.apache.dubbo.registry.client;
+import org.apache.dubbo.metadata.MetadataInfo;
+
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
+import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY;
+
/**
* The default implementation of {@link ServiceInstance}.
*
@@ -43,6 +47,11 @@ public class DefaultServiceInstance implements ServiceInstance {
private Map<String, String> metadata = new HashMap<>();
+ private transient String address;
+ private transient MetadataInfo serviceMetadata;
+ // used at runtime
+ private transient Map<String, String> extendParams = new HashMap<>();
+
public DefaultServiceInstance() {
}
@@ -99,6 +108,18 @@ public class DefaultServiceInstance implements ServiceInstance {
}
@Override
+ public String getAddress() {
+ if (address == null) {
+ address = getAddress(host, port);
+ }
+ return address;
+ }
+
+ private static String getAddress(String host, int port) {
+ return port <= 0 ? host : host + ':' + port;
+ }
+
+ @Override
public boolean isEnabled() {
return enabled;
}
@@ -121,27 +142,64 @@ public class DefaultServiceInstance implements ServiceInstance {
return metadata;
}
+ @Override
+ public Map<String, String> getExtendParams() {
+ return extendParams;
+ }
+
+ @Override
+ public Map<String, String> getAllParams() {
+ Map<String, String> allParams = new HashMap<>((int) ((metadata.size() + extendParams.size()) / 0.75f + 1));
+ allParams.putAll(metadata);
+ allParams.putAll(extendParams);
+ return allParams;
+ }
+
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
+ public MetadataInfo getServiceMetadata() {
+ return serviceMetadata;
+ }
+
+ public void setServiceMetadata(MetadataInfo serviceMetadata) {
+ this.serviceMetadata = serviceMetadata;
+ }
+
+ @Override
+ public InstanceAddressURL toURL() {
+ return new InstanceAddressURL(this, serviceMetadata);
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DefaultServiceInstance)) return false;
DefaultServiceInstance that = (DefaultServiceInstance) o;
- return isEnabled() == that.isEnabled() &&
- isHealthy() == that.isHealthy() &&
- Objects.equals(getId(), that.getId()) &&
- Objects.equals(getServiceName(), that.getServiceName()) &&
+ boolean equals = Objects.equals(getServiceName(), that.getServiceName()) &&
Objects.equals(getHost(), that.getHost()) &&
- Objects.equals(getPort(), that.getPort()) &&
- Objects.equals(getMetadata(), that.getMetadata());
+ Objects.equals(getPort(), that.getPort());
+ for (Map.Entry<String, String> entry : this.getMetadata().entrySet()) {
+ if (entry.getKey().equals(REVISION_KEY)) {
+ continue;
+ }
+ equals = equals && !entry.getValue().equals(that.getMetadata().get(entry.getKey()));
+ }
+
+ return equals;
}
@Override
public int hashCode() {
- return Objects.hash(getId(), getServiceName(), getHost(), getPort(), isEnabled(), isHealthy(), getMetadata());
+ int result = Objects.hash(getServiceName(), getHost(), getPort());
+ for (Map.Entry<String, String> entry : this.getMetadata().entrySet()) {
+ if (entry.getKey().equals(REVISION_KEY)) {
+ continue;
+ }
+ result = 31 * result + (entry.getValue() == null ? 0 : entry.getValue().hashCode());
+ }
+ return result;
}
@Override
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java
index b3a8b92..ee99000 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java
@@ -224,6 +224,16 @@ final class EventPublishingServiceDiscovery implements ServiceDiscovery {
}
@Override
+ public URL getUrl() {
+ return serviceDiscovery.getUrl();
+ }
+
+ @Override
+ public ServiceInstance getLocalInstance() {
+ return serviceDiscovery.getLocalInstance();
+ }
+
+ @Override
public void initialize(URL registryURL) {
assertInitialized(INITIALIZE_ACTION);
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/FileSystemServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/FileSystemServiceDiscovery.java
index 82bc860..2a51168 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/FileSystemServiceDiscovery.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/FileSystemServiceDiscovery.java
@@ -62,6 +62,8 @@ public class FileSystemServiceDiscovery implements ServiceDiscovery, EventListen
private FileSystemDynamicConfiguration dynamicConfiguration;
+ private ServiceInstance serviceInstance;
+
@Override
public void onEvent(ServiceInstancesChangedEvent event) {
@@ -129,7 +131,18 @@ public class FileSystemServiceDiscovery implements ServiceDiscovery, EventListen
}
@Override
+ public URL getUrl() {
+ return null;
+ }
+
+ @Override
+ public ServiceInstance getLocalInstance() {
+ return serviceInstance;
+ }
+
+ @Override
public void register(ServiceInstance serviceInstance) throws RuntimeException {
+ this.serviceInstance = serviceInstance;
String serviceInstanceId = getServiceInstanceId(serviceInstance);
String serviceName = getServiceName(serviceInstance);
String content = toJSONString(serviceInstance);
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/InstanceAddressURL.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/InstanceAddressURL.java
new file mode 100644
index 0000000..5159cfc
--- /dev/null
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/InstanceAddressURL.java
@@ -0,0 +1,376 @@
+/*
+ * 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.apache.dubbo.registry.client;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.utils.StringUtils;
+import org.apache.dubbo.metadata.MetadataInfo;
+import org.apache.dubbo.rpc.RpcContext;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
+
+public class InstanceAddressURL extends URL {
+ private ServiceInstance instance;
+ private MetadataInfo metadataInfo;
+
+ // cached numbers
+ private volatile transient Map<String, Number> numbers;
+ private volatile transient Map<String, Map<String, Number>> methodNumbers;
+
+ public InstanceAddressURL() {
+ }
+
+ public InstanceAddressURL(
+ ServiceInstance instance,
+ MetadataInfo metadataInfo
+ ) {
+ this.instance = instance;
+ this.metadataInfo = metadataInfo;
+ this.host = instance.getHost();
+ this.port = instance.getPort();
+ }
+
+ public ServiceInstance getInstance() {
+ return instance;
+ }
+
+ public MetadataInfo getMetadataInfo() {
+ return metadataInfo;
+ }
+
+ @Override
+ public String getServiceInterface() {
+ return RpcContext.getContext().getInterfaceName();
+ }
+
+ public String getGroup() {
+ return RpcContext.getContext().getGroup();
+ }
+
+ public String getVersion() {
+ return RpcContext.getContext().getVersion();
+ }
+
+ @Override
+ public String getProtocol() {
+ return RpcContext.getContext().getProtocol();
+ }
+
+ @Override
+ public String getProtocolServiceKey() {
+ return RpcContext.getContext().getProtocolServiceKey();
+ }
+
+ @Override
+ public String getServiceKey() {
+ return RpcContext.getContext().getServiceKey();
+ }
+
+ @Override
+ public String getAddress() {
+ return instance.getAddress();
+ }
+
+ @Override
+ public String getPath() {
+ MetadataInfo.ServiceInfo serviceInfo = metadataInfo.getServiceInfo(getProtocolServiceKey());
+ return serviceInfo.getPath();
+ }
+
+ @Override
+ public String getParameter(String key) {
+ if (VERSION_KEY.equals(key)) {
+ return getVersion();
+ } else if (GROUP_KEY.equals(key)) {
+ return getGroup();
+ } else if (INTERFACE_KEY.equals(key)) {
+ return getServiceInterface();
+ }
+
+ String protocolServiceKey = getProtocolServiceKey();
+ if (protocolServiceKey == null) {
+ return getInstanceParameter(key);
+ }
+ return getServiceParameter(protocolServiceKey, key);
+ }
+
+ @Override
+ public String getServiceParameter(String service, String key) {
+ String value = getInstanceParameter(key);
+ if (StringUtils.isEmpty(value) && metadataInfo != null) {
+ value = metadataInfo.getParameter(key, service);
+ }
+ return value;
+ }
+
+ /**
+ * method parameter only exists in ServiceInfo
+ *
+ * @param method
+ * @param key
+ * @return
+ */
+ @Override
+ public String getServiceMethodParameter(String protocolServiceKey, String method, String key) {
+ MetadataInfo.ServiceInfo serviceInfo = metadataInfo.getServiceInfo(protocolServiceKey);
+ String value = serviceInfo.getMethodParameter(method, key, null);
+ if (StringUtils.isNotEmpty(value)) {
+ return value;
+ }
+ return getParameter(key);
+ }
+
+ @Override
+ public String getMethodParameter(String method, String key) {
+ String protocolServiceKey = getProtocolServiceKey();
+ if (protocolServiceKey == null) {
+ return null;
+ }
+ return getServiceMethodParameter(protocolServiceKey, method, key);
+ }
+
+ /**
+ * method parameter only exists in ServiceInfo
+ *
+ * @param method
+ * @param key
+ * @return
+ */
+ @Override
+ public boolean hasServiceMethodParameter(String protocolServiceKey, String method, String key) {
+ MetadataInfo.ServiceInfo serviceInfo = metadataInfo.getServiceInfo(protocolServiceKey);
+
+ if (method == null) {
+ String suffix = "." + key;
+ for (String fullKey : getParameters().keySet()) {
+ if (fullKey.endsWith(suffix)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ if (key == null) {
+ String prefix = method + ".";
+ for (String fullKey : getParameters().keySet()) {
+ if (fullKey.startsWith(prefix)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ return serviceInfo.hasMethodParameter(method, key);
+ }
+
+ @Override
+ public boolean hasMethodParameter(String method, String key) {
+ String protocolServiceKey = getProtocolServiceKey();
+ if (protocolServiceKey == null) {
+ return false;
+ }
+ return hasServiceMethodParameter(protocolServiceKey, method, key);
+ }
+
+ /**
+ * method parameter only exists in ServiceInfo
+ *
+ * @param method
+ * @return
+ */
+ @Override
+ public boolean hasServiceMethodParameter(String protocolServiceKey, String method) {
+ MetadataInfo.ServiceInfo serviceInfo = metadataInfo.getServiceInfo(protocolServiceKey);
+ return serviceInfo.hasMethodParameter(method);
+ }
+
+ @Override
+ public boolean hasMethodParameter(String method) {
+ String protocolServiceKey = getProtocolServiceKey();
+ if (protocolServiceKey == null) {
+ return false;
+ }
+ return hasServiceMethodParameter(protocolServiceKey, method);
+ }
+
+ /**
+ * Avoid calling this method in RPC call.
+ *
+ * @return
+ */
+ @Override
+ public Map<String, String> getServiceParameters(String protocolServiceKey) {
+ Map<String, String> instanceParams = getInstanceMetadata();
+ Map<String, String> metadataParams = (metadataInfo == null ? new HashMap<>() : metadataInfo.getParameters(protocolServiceKey));
+ int i = instanceParams == null ? 0 : instanceParams.size();
+ int j = metadataParams == null ? 0 : metadataParams.size();
+ Map<String, String> params = new HashMap<>((int) ((i + j) / 0.75) + 1);
+ if (instanceParams != null) {
+ params.putAll(instanceParams);
+ }
+ if (metadataParams != null) {
+ params.putAll(metadataParams);
+ }
+ return params;
+ }
+
+ @Override
+ public Map<String, String> getParameters() {
+ String protocolServiceKey = getProtocolServiceKey();
+ if (protocolServiceKey == null) {
+ return getInstance().getAllParams();
+ }
+ return getServiceParameters(protocolServiceKey);
+ }
+
+ @Override
+ public URL addParameter(String key, String value) {
+ if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
+ return this;
+ }
+
+ getInstance().getExtendParams().put(key, value);
+ return this;
+ }
+
+ @Override
+ public URL addParameterIfAbsent(String key, String value) {
+ if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
+ return this;
+ }
+
+ getInstance().getExtendParams().putIfAbsent(key, value);
+ return this;
+ }
+
+ public URL addServiceParameter(String protocolServiceKey, String key, String value) {
+ if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
+ return this;
+ }
+
+ getMetadataInfo().getServiceInfo(protocolServiceKey).addParameter(key, value);
+ return this;
+ }
+
+ public URL addServiceParameterIfAbsent(String protocolServiceKey, String key, String value) {
+ if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
+ return this;
+ }
+
+ getMetadataInfo().getServiceInfo(protocolServiceKey).addParameterIfAbsent(key, value);
+ return this;
+ }
+
+ public URL addConsumerParams(String protocolServiceKey, Map<String, String> params) {
+ getMetadataInfo().getServiceInfo(protocolServiceKey).addConsumerParams(params);
+ return this;
+ }
+
+ @Override
+ protected Map<String, Number> getServiceNumbers(String protocolServiceKey) {
+ return getServiceInfo(protocolServiceKey).getNumbers();
+ }
+
+ @Override
+ protected Map<String, Number> getNumbers() {
+ String protocolServiceKey = getProtocolServiceKey();
+ if (protocolServiceKey == null) {
+ if (numbers == null) { // concurrent initialization is tolerant
+ numbers = new ConcurrentHashMap<>();
+ }
+ return numbers;
+ }
+ return getServiceNumbers(protocolServiceKey);
+ }
+
+ @Override
+ protected Map<String, Map<String, Number>> getServiceMethodNumbers(String protocolServiceKey) {
+ return getServiceInfo(protocolServiceKey).getMethodNumbers();
+ }
+
+ @Override
+ protected Map<String, Map<String, Number>> getMethodNumbers() {
+ String protocolServiceKey = getProtocolServiceKey();
+ if (protocolServiceKey == null) {
+ if (methodNumbers == null) { // concurrent initialization is tolerant
+ methodNumbers = new ConcurrentHashMap<>();
+ }
+ return methodNumbers;
+ }
+ return getServiceMethodNumbers(protocolServiceKey);
+ }
+
+ private MetadataInfo.ServiceInfo getServiceInfo(String protocolServiceKey) {
+ return metadataInfo.getServiceInfo(protocolServiceKey);
+ }
+
+ private String getInstanceParameter(String key) {
+ String value = this.instance.getMetadata().get(key);
+ if (StringUtils.isNotEmpty(value)) {
+ return value;
+ }
+ return this.instance.getExtendParams().get(key);
+ }
+
+ private Map<String, String> getInstanceMetadata() {
+ return this.instance.getMetadata();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ // instance metadata equals
+ if (obj == null) {
+ return false;
+ }
+ if (!(obj instanceof InstanceAddressURL)) {
+ return false;
+ }
+
+ InstanceAddressURL that = (InstanceAddressURL) obj;
+
+ return this.getInstance().equals(that.getInstance());
+ }
+
+ @Override
+ public int hashCode() {
+ return getInstance().hashCode();
+ }
+
+ public String getServiceString(String service) {
+ MetadataInfo.ServiceInfo serviceInfo = metadataInfo.getServiceInfo(service);
+ if (serviceInfo == null) {
+ return instance.toString();
+ }
+ return instance.toString() + serviceInfo.toString();
+ }
+
+ @Override
+ public String toString() {
+ if (instance == null) {
+ return "{}";
+ }
+ if (metadataInfo == null) {
+ return instance.toString();
+ }
+ return instance.toString() + metadataInfo.toString();
+ }
+}
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ParameterizedServiceNameMapping.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryClusterIdentifier.java
similarity index 58%
rename from dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ParameterizedServiceNameMapping.java
rename to dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryClusterIdentifier.java
index 893a6f4..9d0e4a0 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ParameterizedServiceNameMapping.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryClusterIdentifier.java
@@ -14,34 +14,23 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.metadata;
+package org.apache.dubbo.registry.client;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.extension.ExtensionLoader;
+import org.apache.dubbo.common.extension.SPI;
-import java.util.Set;
+import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_TYPE_KEY;
-import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY;
+@SPI
+public interface RegistryClusterIdentifier {
+ String providerKey(URL url);
-/**
- * The parameterized implementation of {@link ServiceNameMapping}
- *
- * @see ReadOnlyServiceNameMapping
- * @since 2.7.8
- */
-public class ParameterizedServiceNameMapping extends ReadOnlyServiceNameMapping {
-
- /**
- * The priority of {@link PropertiesFileServiceNameMapping}
- */
- static final int PRIORITY = MAX_PRIORITY + 99;
-
- @Override
- public Set<String> get(URL subscribedURL) {
- return getValue(subscribedURL.getParameter(SUBSCRIBED_SERVICE_NAMES_KEY));
- }
+ String consumerKey(URL url);
- @Override
- public int getPriority() {
- return PRIORITY;
+ static RegistryClusterIdentifier getExtension(URL url) {
+ ExtensionLoader<RegistryClusterIdentifier> loader
+ = ExtensionLoader.getExtensionLoader(RegistryClusterIdentifier.class);
+ return loader.getExtension(url.getParameter(REGISTRY_CLUSTER_TYPE_KEY, "default"));
}
}
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryProtocol.java
similarity index 91%
rename from dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java
rename to dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryProtocol.java
index 12a94f0..64ffe04 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryProtocol.java
@@ -1,825 +1,825 @@
-/*
- * 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.apache.dubbo.registry.integration;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.URLBuilder;
-import org.apache.dubbo.common.config.ConfigurationUtils;
-import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
-import org.apache.dubbo.common.extension.ExtensionLoader;
-import org.apache.dubbo.common.logger.Logger;
-import org.apache.dubbo.common.logger.LoggerFactory;
-import org.apache.dubbo.common.timer.HashedWheelTimer;
-import org.apache.dubbo.common.utils.CollectionUtils;
-import org.apache.dubbo.common.utils.NamedThreadFactory;
-import org.apache.dubbo.common.utils.StringUtils;
-import org.apache.dubbo.common.utils.UrlUtils;
-import org.apache.dubbo.registry.NotifyListener;
-import org.apache.dubbo.registry.Registry;
-import org.apache.dubbo.registry.RegistryFactory;
-import org.apache.dubbo.registry.RegistryService;
-import org.apache.dubbo.registry.retry.ReExportTask;
-import org.apache.dubbo.registry.support.SkipFailbackWrapperException;
-import org.apache.dubbo.rpc.Exporter;
-import org.apache.dubbo.rpc.Invoker;
-import org.apache.dubbo.rpc.Protocol;
-import org.apache.dubbo.rpc.ProtocolServer;
-import org.apache.dubbo.rpc.ProxyFactory;
-import org.apache.dubbo.rpc.RpcException;
-import org.apache.dubbo.rpc.cluster.Cluster;
-import org.apache.dubbo.rpc.cluster.Configurator;
-import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
-import org.apache.dubbo.rpc.cluster.support.MergeableCluster;
-import org.apache.dubbo.rpc.model.ApplicationModel;
-import org.apache.dubbo.rpc.model.ProviderModel;
-import org.apache.dubbo.rpc.protocol.InvokerWrapper;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.TimeUnit;
-
-import static java.util.concurrent.Executors.newSingleThreadExecutor;
-import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
-import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.EXTRA_KEYS_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX;
-import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
-import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY;
-import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP;
-import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE;
-import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST;
-import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT;
-import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
-import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY;
-import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL;
-import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY;
-import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
-import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL;
-import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY;
-import static org.apache.dubbo.common.utils.UrlUtils.classifyUrls;
-import static org.apache.dubbo.registry.Constants.CONFIGURATORS_SUFFIX;
-import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL;
-import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY;
-import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_PERIOD;
-import static org.apache.dubbo.registry.Constants.PROVIDER_PROTOCOL;
-import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY;
-import static org.apache.dubbo.registry.Constants.REGISTER_KEY;
-import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY;
-import static org.apache.dubbo.registry.Constants.SIMPLIFIED_KEY;
-import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY;
-import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY;
-import static org.apache.dubbo.remoting.Constants.CHECK_KEY;
-import static org.apache.dubbo.remoting.Constants.CODEC_KEY;
-import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY;
-import static org.apache.dubbo.remoting.Constants.EXCHANGER_KEY;
-import static org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY;
-import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY;
-import static org.apache.dubbo.rpc.Constants.INTERFACES;
-import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
-import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
-import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY;
-import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
-import static org.apache.dubbo.rpc.cluster.Constants.WARMUP_KEY;
-import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY;
-
-/**
- * RegistryProtocol
- */
-public class RegistryProtocol implements Protocol {
- public static final String[] DEFAULT_REGISTER_PROVIDER_KEYS = {
- APPLICATION_KEY, CODEC_KEY, EXCHANGER_KEY, SERIALIZATION_KEY, CLUSTER_KEY, CONNECTIONS_KEY, DEPRECATED_KEY,
- GROUP_KEY, LOADBALANCE_KEY, MOCK_KEY, PATH_KEY, TIMEOUT_KEY, TOKEN_KEY, VERSION_KEY, WARMUP_KEY,
- WEIGHT_KEY, TIMESTAMP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY
- };
-
- public static final String[] DEFAULT_REGISTER_CONSUMER_KEYS = {
- APPLICATION_KEY, VERSION_KEY, GROUP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY
- };
-
- private final static Logger logger = LoggerFactory.getLogger(RegistryProtocol.class);
- private final Map<URL, NotifyListener> overrideListeners = new ConcurrentHashMap<>();
- private final Map<String, ServiceConfigurationListener> serviceConfigurationListeners = new ConcurrentHashMap<>();
- private final ProviderConfigurationListener providerConfigurationListener = new ProviderConfigurationListener();
- //To solve the problem of RMI repeated exposure port conflicts, the services that have been exposed are no longer exposed.
- //providerurl <--> exporter
- private final ConcurrentMap<String, ExporterChangeableWrapper<?>> bounds = new ConcurrentHashMap<>();
- private Protocol protocol;
- private RegistryFactory registryFactory;
- private ProxyFactory proxyFactory;
-
- private ConcurrentMap<URL, ReExportTask> reExportFailedTasks = new ConcurrentHashMap<>();
- private HashedWheelTimer retryTimer = new HashedWheelTimer(new NamedThreadFactory("DubboReexportTimer", true), DEFAULT_REGISTRY_RETRY_PERIOD, TimeUnit.MILLISECONDS, 128);
-
- //Filter the parameters that do not need to be output in url(Starting with .)
- private static String[] getFilteredKeys(URL url) {
- Map<String, String> params = url.getParameters();
- if (CollectionUtils.isNotEmptyMap(params)) {
- return params.keySet().stream()
- .filter(k -> k.startsWith(HIDE_KEY_PREFIX))
- .toArray(String[]::new);
- } else {
- return new String[0];
- }
- }
-
- public void setProtocol(Protocol protocol) {
- this.protocol = protocol;
- }
-
- public void setRegistryFactory(RegistryFactory registryFactory) {
- this.registryFactory = registryFactory;
- }
-
- public void setProxyFactory(ProxyFactory proxyFactory) {
- this.proxyFactory = proxyFactory;
- }
-
- @Override
- public int getDefaultPort() {
- return 9090;
- }
-
- public Map<URL, NotifyListener> getOverrideListeners() {
- return overrideListeners;
- }
-
- private void register(URL registryUrl, URL registeredProviderUrl) {
- Registry registry = registryFactory.getRegistry(registryUrl);
- registry.register(registeredProviderUrl);
- }
-
- private void registerStatedUrl(URL registryUrl, URL registeredProviderUrl, boolean registered) {
- ProviderModel model = ApplicationModel.getProviderModel(registeredProviderUrl.getServiceKey());
- model.addStatedUrl(new ProviderModel.RegisterStatedURL(
- registeredProviderUrl,
- registryUrl,
- registered));
- }
-
- @Override
- public <T> Exporter<T> export(final Invoker<T> originInvoker) throws RpcException {
- URL registryUrl = getRegistryUrl(originInvoker);
- // url to export locally
- URL providerUrl = getProviderUrl(originInvoker);
-
- // Subscribe the override data
- // FIXME When the provider subscribes, it will affect the scene : a certain JVM exposes the service and call
- // the same service. Because the subscribed is cached key with the name of the service, it causes the
- // subscription information to cover.
- final URL overrideSubscribeUrl = getSubscribedOverrideUrl(providerUrl);
- final OverrideListener overrideSubscribeListener = new OverrideListener(overrideSubscribeUrl, originInvoker);
- overrideListeners.put(overrideSubscribeUrl, overrideSubscribeListener);
-
- providerUrl = overrideUrlWithConfig(providerUrl, overrideSubscribeListener);
- //export invoker
- final ExporterChangeableWrapper<T> exporter = doLocalExport(originInvoker, providerUrl);
-
- // url to registry
- final Registry registry = getRegistry(originInvoker);
- final URL registeredProviderUrl = getUrlToRegistry(providerUrl, registryUrl);
-
- // decide if we need to delay publish
- boolean register = providerUrl.getParameter(REGISTER_KEY, true);
- if (register) {
- register(registryUrl, registeredProviderUrl);
- }
-
- // register stated url on provider model
- registerStatedUrl(registryUrl, registeredProviderUrl, register);
-
-
- exporter.setRegisterUrl(registeredProviderUrl);
- exporter.setSubscribeUrl(overrideSubscribeUrl);
-
- // Deprecated! Subscribe to override rules in 2.6.x or before.
- registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener);
-
- notifyExport(exporter);
- //Ensure that a new exporter instance is returned every time export
- return new DestroyableExporter<>(exporter);
- }
-
- private <T> void notifyExport(ExporterChangeableWrapper<T> exporter) {
- List<RegistryProtocolListener> listeners = ExtensionLoader.getExtensionLoader(RegistryProtocolListener.class)
- .getActivateExtension(exporter.getOriginInvoker().getUrl(), "registry.protocol.listener");
- if (CollectionUtils.isNotEmpty(listeners)) {
- for (RegistryProtocolListener listener : listeners) {
- listener.onExport(this, exporter);
- }
- }
- }
-
- private URL overrideUrlWithConfig(URL providerUrl, OverrideListener listener) {
- providerUrl = providerConfigurationListener.overrideUrl(providerUrl);
- ServiceConfigurationListener serviceConfigurationListener = new ServiceConfigurationListener(providerUrl, listener);
- serviceConfigurationListeners.put(providerUrl.getServiceKey(), serviceConfigurationListener);
- return serviceConfigurationListener.overrideUrl(providerUrl);
- }
-
- @SuppressWarnings("unchecked")
- private <T> ExporterChangeableWrapper<T> doLocalExport(final Invoker<T> originInvoker, URL providerUrl) {
- String key = getCacheKey(originInvoker);
-
- return (ExporterChangeableWrapper<T>) bounds.computeIfAbsent(key, s -> {
- Invoker<?> invokerDelegate = new InvokerDelegate<>(originInvoker, providerUrl);
- return new ExporterChangeableWrapper<>((Exporter<T>) protocol.export(invokerDelegate), originInvoker);
- });
- }
-
- public <T> void reExport(Exporter<T> exporter, URL newInvokerUrl) {
- if (exporter instanceof ExporterChangeableWrapper) {
- ExporterChangeableWrapper<T> exporterWrapper = (ExporterChangeableWrapper<T>) exporter;
- Invoker<T> originInvoker = exporterWrapper.getOriginInvoker();
- reExport(originInvoker, newInvokerUrl);
- }
- }
-
- /**
- * Reexport the invoker of the modified url
- *
- * @param originInvoker
- * @param newInvokerUrl
- * @param <T>
- */
- @SuppressWarnings("unchecked")
- public <T> void reExport(final Invoker<T> originInvoker, URL newInvokerUrl) {
- String key = getCacheKey(originInvoker);
- ExporterChangeableWrapper<T> exporter = (ExporterChangeableWrapper<T>) bounds.get(key);
- URL registeredUrl = exporter.getRegisterUrl();
-
- URL registryUrl = getRegistryUrl(originInvoker);
- URL newProviderUrl = getUrlToRegistry(newInvokerUrl, registryUrl);
-
- // update local exporter
- Invoker<T> invokerDelegate = new InvokerDelegate<T>(originInvoker, newInvokerUrl);
- exporter.setExporter(protocol.export(invokerDelegate));
-
- // update registry
- if (!newProviderUrl.equals(registeredUrl)) {
- try {
- doReExport(originInvoker, exporter, registryUrl, registeredUrl, newProviderUrl);
- } catch (Exception e) {
- ReExportTask oldTask = reExportFailedTasks.get(registeredUrl);
- if (oldTask != null) {
- return;
- }
- ReExportTask task = new ReExportTask(
- () -> doReExport(originInvoker, exporter, registryUrl, registeredUrl, newProviderUrl),
- registeredUrl,
- null
- );
- oldTask = reExportFailedTasks.putIfAbsent(registeredUrl, task);
- if (oldTask == null) {
- // never has a retry task. then start a new task for retry.
- retryTimer.newTimeout(task, registryUrl.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD), TimeUnit.MILLISECONDS);
- }
- }
- }
- }
-
- private <T> void doReExport(final Invoker<T> originInvoker, ExporterChangeableWrapper<T> exporter,
- URL registryUrl, URL oldProviderUrl, URL newProviderUrl) {
- if (getProviderUrl(originInvoker).getParameter(REGISTER_KEY, true)) {
- Registry registry = null;
- try {
- registry = getRegistry(originInvoker);
- } catch (Exception e) {
- throw new SkipFailbackWrapperException(e);
- }
-
- logger.info("Try to unregister old url: " + oldProviderUrl);
- registry.reExportUnregister(oldProviderUrl);
-
- logger.info("Try to register new url: " + newProviderUrl);
- registry.reExportRegister(newProviderUrl);
- }
- try {
- ProviderModel.RegisterStatedURL statedUrl = getStatedUrl(registryUrl, newProviderUrl);
- statedUrl.setProviderUrl(newProviderUrl);
- exporter.setRegisterUrl(newProviderUrl);
- } catch (Exception e) {
- throw new SkipFailbackWrapperException(e);
- }
- }
-
- private ProviderModel.RegisterStatedURL getStatedUrl(URL registryUrl, URL providerUrl) {
- ProviderModel providerModel = ApplicationModel.getServiceRepository()
- .lookupExportedService(providerUrl.getServiceKey());
-
- List<ProviderModel.RegisterStatedURL> statedUrls = providerModel.getStatedUrl();
- return statedUrls.stream()
- .filter(u -> u.getRegistryUrl().equals(registryUrl)
- && u.getProviderUrl().getProtocol().equals(providerUrl.getProtocol()))
- .findFirst().orElseThrow(() -> new IllegalStateException("There should have at least one registered url."));
- }
-
- /**
- * Get an instance of registry based on the address of invoker
- *
- * @param originInvoker
- * @return
- */
- protected Registry getRegistry(final Invoker<?> originInvoker) {
- URL registryUrl = getRegistryUrl(originInvoker);
- return registryFactory.getRegistry(registryUrl);
- }
-
- protected URL getRegistryUrl(Invoker<?> originInvoker) {
- URL registryUrl = originInvoker.getUrl();
- if (REGISTRY_PROTOCOL.equals(registryUrl.getProtocol())) {
- String protocol = registryUrl.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY);
- registryUrl = registryUrl.setProtocol(protocol).removeParameter(REGISTRY_KEY);
- }
- return registryUrl;
- }
-
- protected URL getRegistryUrl(URL url) {
- return URLBuilder.from(url)
- .setProtocol(url.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY))
- .removeParameter(REGISTRY_KEY)
- .build();
- }
-
-
- /**
- * Return the url that is registered to the registry and filter the url parameter once
- *
- * @param providerUrl
- * @return url to registry.
- */
- private URL getUrlToRegistry(final URL providerUrl, final URL registryUrl) {
- //The address you see at the registry
- if (!registryUrl.getParameter(SIMPLIFIED_KEY, false)) {
- return providerUrl.removeParameters(getFilteredKeys(providerUrl)).removeParameters(
- MONITOR_KEY, BIND_IP_KEY, BIND_PORT_KEY, QOS_ENABLE, QOS_HOST, QOS_PORT, ACCEPT_FOREIGN_IP, VALIDATION_KEY,
- INTERFACES);
- } else {
- String extraKeys = registryUrl.getParameter(EXTRA_KEYS_KEY, "");
- // if path is not the same as interface name then we should keep INTERFACE_KEY,
- // otherwise, the registry structure of zookeeper would be '/dubbo/path/providers',
- // but what we expect is '/dubbo/interface/providers'
- if (!providerUrl.getPath().equals(providerUrl.getParameter(INTERFACE_KEY))) {
- if (StringUtils.isNotEmpty(extraKeys)) {
- extraKeys += ",";
- }
- extraKeys += INTERFACE_KEY;
- }
- String[] paramsToRegistry = getParamsToRegistry(DEFAULT_REGISTER_PROVIDER_KEYS
- , COMMA_SPLIT_PATTERN.split(extraKeys));
- return URL.valueOf(providerUrl, paramsToRegistry, providerUrl.getParameter(METHODS_KEY, (String[]) null));
- }
-
- }
-
- private URL getSubscribedOverrideUrl(URL registeredProviderUrl) {
- return registeredProviderUrl.setProtocol(PROVIDER_PROTOCOL)
- .addParameters(CATEGORY_KEY, CONFIGURATORS_CATEGORY, CHECK_KEY, String.valueOf(false));
- }
-
- /**
- * Get the address of the providerUrl through the url of the invoker
- *
- * @param originInvoker
- * @return
- */
- private URL getProviderUrl(final Invoker<?> originInvoker) {
- String export = originInvoker.getUrl().getParameterAndDecoded(EXPORT_KEY);
- if (export == null || export.length() == 0) {
- throw new IllegalArgumentException("The registry export url is null! registry: " + originInvoker.getUrl());
- }
- return URL.valueOf(export);
- }
-
- /**
- * Get the key cached in bounds by invoker
- *
- * @param originInvoker
- * @return
- */
- private String getCacheKey(final Invoker<?> originInvoker) {
- URL providerUrl = getProviderUrl(originInvoker);
- String key = providerUrl.removeParameters("dynamic", "enabled").toFullString();
- return key;
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
- url = getRegistryUrl(url);
- Registry registry = registryFactory.getRegistry(url);
- if (RegistryService.class.equals(type)) {
- return proxyFactory.getInvoker((T) registry, type, url);
- }
-
- // group="a,b" or group="*"
- Map<String, String> qs = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY));
- String group = qs.get(GROUP_KEY);
- if (group != null && group.length() > 0) {
- if ((COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) {
- return doRefer(Cluster.getCluster(MergeableCluster.NAME), registry, type, url);
- }
- }
-
- Cluster cluster = Cluster.getCluster(qs.get(CLUSTER_KEY));
- return doRefer(cluster, registry, type, url);
- }
-
- private <T> Invoker<T> doRefer(Cluster cluster, Registry registry, Class<T> type, URL url) {
- RegistryDirectory<T> directory = new RegistryDirectory<T>(type, url);
- directory.setRegistry(registry);
- directory.setProtocol(protocol);
- // all attributes of REFER_KEY
- Map<String, String> parameters = new HashMap<String, String>(directory.getConsumerUrl().getParameters());
- URL subscribeUrl = new URL(CONSUMER_PROTOCOL, parameters.remove(REGISTER_IP_KEY), 0, type.getName(), parameters);
- if (directory.isShouldRegister()) {
- directory.setRegisteredConsumerUrl(subscribeUrl);
- registry.register(directory.getRegisteredConsumerUrl());
- }
- directory.buildRouterChain(subscribeUrl);
- directory.subscribe(toSubscribeUrl(subscribeUrl));
-
- Invoker<T> invoker = cluster.join(directory);
- List<RegistryProtocolListener> listeners = findRegistryProtocolListeners(url);
- if (CollectionUtils.isEmpty(listeners)) {
- return invoker;
- }
-
- RegistryInvokerWrapper<T> registryInvokerWrapper = new RegistryInvokerWrapper<>(directory, cluster, invoker);
- for (RegistryProtocolListener listener : listeners) {
- listener.onRefer(this, registryInvokerWrapper);
- }
- return registryInvokerWrapper;
- }
-
- public <T> void reRefer(Invoker<T> invoker, URL newSubscribeUrl) {
- if (!(invoker instanceof RegistryInvokerWrapper)) {
- return;
- }
-
- RegistryInvokerWrapper<T> invokerWrapper = (RegistryInvokerWrapper<T>) invoker;
- URL oldSubscribeUrl = invokerWrapper.getUrl();
- RegistryDirectory<T> directory = invokerWrapper.getDirectory();
- Registry registry = directory.getRegistry();
- registry.unregister(directory.getRegisteredConsumerUrl());
- directory.unSubscribe(toSubscribeUrl(oldSubscribeUrl));
-
- directory.setRegisteredConsumerUrl(newSubscribeUrl);
- registry.register(directory.getRegisteredConsumerUrl());
- directory.buildRouterChain(newSubscribeUrl);
- directory.subscribe(toSubscribeUrl(newSubscribeUrl));
-
- invokerWrapper.setInvoker(invokerWrapper.getCluster().join(directory));
- }
-
- private static URL toSubscribeUrl(URL url) {
- return url.addParameter(CATEGORY_KEY, PROVIDERS_CATEGORY + "," + CONFIGURATORS_CATEGORY + "," + ROUTERS_CATEGORY);
- }
-
- private List<RegistryProtocolListener> findRegistryProtocolListeners(URL url) {
- return ExtensionLoader.getExtensionLoader(RegistryProtocolListener.class)
- .getActivateExtension(url, "registry.protocol.listener");
- }
-
- // available to test
- public String[] getParamsToRegistry(String[] defaultKeys, String[] additionalParameterKeys) {
- int additionalLen = additionalParameterKeys.length;
- String[] registryParams = new String[defaultKeys.length + additionalLen];
- System.arraycopy(defaultKeys, 0, registryParams, 0, defaultKeys.length);
- System.arraycopy(additionalParameterKeys, 0, registryParams, defaultKeys.length, additionalLen);
- return registryParams;
- }
-
- @Override
- public void destroy() {
- List<RegistryProtocolListener> listeners = ExtensionLoader.getExtensionLoader(RegistryProtocolListener.class)
- .getLoadedExtensionInstances();
- if (CollectionUtils.isNotEmpty(listeners)) {
- for (RegistryProtocolListener listener : listeners) {
- listener.onDestroy();
- }
- }
-
- List<Exporter<?>> exporters = new ArrayList<>(bounds.values());
- for (Exporter<?> exporter : exporters) {
- exporter.unexport();
- }
- bounds.clear();
-
- ExtensionLoader.getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension()
- .removeListener(ApplicationModel.getApplication() + CONFIGURATORS_SUFFIX, providerConfigurationListener);
- }
-
- @Override
- public List<ProtocolServer> getServers() {
- return protocol.getServers();
- }
-
- //Merge the urls of configurators
- private static URL getConfigedInvokerUrl(List<Configurator> configurators, URL url) {
- if (configurators != null && configurators.size() > 0) {
- for (Configurator configurator : configurators) {
- url = configurator.configure(url);
- }
- }
- return url;
- }
-
- public static class InvokerDelegate<T> extends InvokerWrapper<T> {
- private final Invoker<T> invoker;
-
- /**
- * @param invoker
- * @param url invoker.getUrl return this value
- */
- public InvokerDelegate(Invoker<T> invoker, URL url) {
- super(invoker, url);
- this.invoker = invoker;
- }
-
- public Invoker<T> getInvoker() {
- if (invoker instanceof InvokerDelegate) {
- return ((InvokerDelegate<T>) invoker).getInvoker();
- } else {
- return invoker;
- }
- }
- }
-
- private static class DestroyableExporter<T> implements Exporter<T> {
-
- private Exporter<T> exporter;
-
- public DestroyableExporter(Exporter<T> exporter) {
- this.exporter = exporter;
- }
-
- @Override
- public Invoker<T> getInvoker() {
- return exporter.getInvoker();
- }
-
- @Override
- public void unexport() {
- exporter.unexport();
- }
- }
-
- /**
- * Reexport: the exporter destroy problem in protocol
- * 1.Ensure that the exporter returned by registryprotocol can be normal destroyed
- * 2.No need to re-register to the registry after notify
- * 3.The invoker passed by the export method , would better to be the invoker of exporter
- */
- private class OverrideListener implements NotifyListener {
- private final URL subscribeUrl;
- private final Invoker originInvoker;
-
-
- private List<Configurator> configurators;
-
- public OverrideListener(URL subscribeUrl, Invoker originalInvoker) {
- this.subscribeUrl = subscribeUrl;
- this.originInvoker = originalInvoker;
- }
-
- /**
- * @param urls The list of registered information, is always not empty, The meaning is the same as the
- * return value of {@link org.apache.dubbo.registry.RegistryService#lookup(URL)}.
- */
- @Override
- public synchronized void notify(List<URL> urls) {
- logger.debug("original override urls: " + urls);
-
- List<URL> matchedUrls = getMatchedUrls(urls, subscribeUrl.addParameter(CATEGORY_KEY,
- CONFIGURATORS_CATEGORY));
- logger.debug("subscribe url: " + subscribeUrl + ", override urls: " + matchedUrls);
-
- // No matching results
- if (matchedUrls.isEmpty()) {
- return;
- }
-
- this.configurators = Configurator.toConfigurators(classifyUrls(matchedUrls, UrlUtils::isConfigurator))
- .orElse(configurators);
-
- doOverrideIfNecessary();
- }
-
- public synchronized void doOverrideIfNecessary() {
- final Invoker<?> invoker;
- if (originInvoker instanceof InvokerDelegate) {
- invoker = ((InvokerDelegate<?>) originInvoker).getInvoker();
- } else {
- invoker = originInvoker;
- }
- //The origin invoker
- URL originUrl = RegistryProtocol.this.getProviderUrl(invoker);
- String key = getCacheKey(originInvoker);
- ExporterChangeableWrapper<?> exporter = bounds.get(key);
- if (exporter == null) {
- logger.warn(new IllegalStateException("error state, exporter should not be null"));
- return;
- }
- //The current, may have been merged many times
- URL currentUrl = exporter.getInvoker().getUrl();
- //Merged with this configuration
- URL newUrl = getConfigedInvokerUrl(configurators, currentUrl);
- newUrl = getConfigedInvokerUrl(providerConfigurationListener.getConfigurators(), newUrl);
- newUrl = getConfigedInvokerUrl(serviceConfigurationListeners.get(originUrl.getServiceKey())
- .getConfigurators(), newUrl);
- if (!currentUrl.equals(newUrl)) {
- RegistryProtocol.this.reExport(originInvoker, newUrl);
- logger.info("exported provider url changed, origin url: " + originUrl +
- ", old export url: " + currentUrl + ", new export url: " + newUrl);
- }
- }
-
- private List<URL> getMatchedUrls(List<URL> configuratorUrls, URL currentSubscribe) {
- List<URL> result = new ArrayList<URL>();
- for (URL url : configuratorUrls) {
- URL overrideUrl = url;
- // Compatible with the old version
- if (url.getParameter(CATEGORY_KEY) == null && OVERRIDE_PROTOCOL.equals(url.getProtocol())) {
- overrideUrl = url.addParameter(CATEGORY_KEY, CONFIGURATORS_CATEGORY);
- }
-
- // Check whether url is to be applied to the current service
- if (UrlUtils.isMatch(currentSubscribe, overrideUrl)) {
- result.add(url);
- }
- }
- return result;
- }
- }
-
- private class ServiceConfigurationListener extends AbstractConfiguratorListener {
- private URL providerUrl;
- private OverrideListener notifyListener;
-
- public ServiceConfigurationListener(URL providerUrl, OverrideListener notifyListener) {
- this.providerUrl = providerUrl;
- this.notifyListener = notifyListener;
- this.initWith(DynamicConfiguration.getRuleKey(providerUrl) + CONFIGURATORS_SUFFIX);
- }
-
- private <T> URL overrideUrl(URL providerUrl) {
- return RegistryProtocol.getConfigedInvokerUrl(configurators, providerUrl);
- }
-
- @Override
- protected void notifyOverrides() {
- notifyListener.doOverrideIfNecessary();
- }
- }
-
- private class ProviderConfigurationListener extends AbstractConfiguratorListener {
-
- public ProviderConfigurationListener() {
- this.initWith(ApplicationModel.getApplication() + CONFIGURATORS_SUFFIX);
- }
-
- /**
- * Get existing configuration rule and override provider url before exporting.
- *
- * @param providerUrl
- * @param <T>
- * @return
- */
- private <T> URL overrideUrl(URL providerUrl) {
- return RegistryProtocol.getConfigedInvokerUrl(configurators, providerUrl);
- }
-
- @Override
- protected void notifyOverrides() {
- overrideListeners.values().forEach(listener -> ((OverrideListener) listener).doOverrideIfNecessary());
- }
- }
-
- /**
- * exporter proxy, establish the corresponding relationship between the returned exporter and the exporter
- * exported by the protocol, and can modify the relationship at the time of override.
- *
- * @param <T>
- */
- private class ExporterChangeableWrapper<T> implements Exporter<T> {
-
- private final ExecutorService executor = newSingleThreadExecutor(new NamedThreadFactory("Exporter-Unexport", true));
-
- private final Invoker<T> originInvoker;
- private Exporter<T> exporter;
- private URL subscribeUrl;
- private URL registerUrl;
-
- public ExporterChangeableWrapper(Exporter<T> exporter, Invoker<T> originInvoker) {
- this.exporter = exporter;
- this.originInvoker = originInvoker;
- }
-
- public Invoker<T> getOriginInvoker() {
- return originInvoker;
- }
-
- @Override
- public Invoker<T> getInvoker() {
- return exporter.getInvoker();
- }
-
- public void setExporter(Exporter<T> exporter) {
- this.exporter = exporter;
- }
-
- @Override
- public void unexport() {
- String key = getCacheKey(this.originInvoker);
- bounds.remove(key);
-
- Registry registry = RegistryProtocol.this.getRegistry(originInvoker);
- try {
- registry.unregister(registerUrl);
- } catch (Throwable t) {
- logger.warn(t.getMessage(), t);
- }
- try {
- NotifyListener listener = RegistryProtocol.this.overrideListeners.remove(subscribeUrl);
- registry.unsubscribe(subscribeUrl, listener);
- ExtensionLoader.getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension()
- .removeListener(subscribeUrl.getServiceKey() + CONFIGURATORS_SUFFIX,
- serviceConfigurationListeners.get(subscribeUrl.getServiceKey()));
- } catch (Throwable t) {
- logger.warn(t.getMessage(), t);
- }
-
- executor.submit(() -> {
- try {
- int timeout = ConfigurationUtils.getServerShutdownTimeout();
- if (timeout > 0) {
- logger.info("Waiting " + timeout + "ms for registry to notify all consumers before unexport. " +
- "Usually, this is called when you use dubbo API");
- Thread.sleep(timeout);
- }
- exporter.unexport();
- } catch (Throwable t) {
- logger.warn(t.getMessage(), t);
- }
- });
- }
-
- public void setSubscribeUrl(URL subscribeUrl) {
- this.subscribeUrl = subscribeUrl;
- }
-
- public void setRegisterUrl(URL registerUrl) {
- this.registerUrl = registerUrl;
- }
-
- public URL getRegisterUrl() {
- return registerUrl;
- }
- }
-
- // for unit test
- private static RegistryProtocol INSTANCE;
-
- // for unit test
- public RegistryProtocol() {
- INSTANCE = this;
- }
-
- // for unit test
- public static RegistryProtocol getRegistryProtocol() {
- if (INSTANCE == null) {
- ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(REGISTRY_PROTOCOL); // load
- }
- return INSTANCE;
- }
-}
+/*
+ * 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.apache.dubbo.registry.client;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.config.ConfigurationUtils;
+import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
+import org.apache.dubbo.common.extension.ExtensionLoader;
+import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.timer.HashedWheelTimer;
+import org.apache.dubbo.common.utils.CollectionUtils;
+import org.apache.dubbo.common.utils.NamedThreadFactory;
+import org.apache.dubbo.common.utils.StringUtils;
+import org.apache.dubbo.common.utils.UrlUtils;
+import org.apache.dubbo.registry.NotifyListener;
+import org.apache.dubbo.registry.Registry;
+import org.apache.dubbo.registry.RegistryFactory;
+import org.apache.dubbo.registry.RegistryService;
+import org.apache.dubbo.registry.integration.AbstractConfiguratorListener;
+import org.apache.dubbo.registry.integration.DynamicDirectory;
+import org.apache.dubbo.registry.integration.InterfaceCompatibleRegistryProtocol;
+import org.apache.dubbo.registry.integration.RegistryProtocolListener;
+import org.apache.dubbo.registry.retry.ReExportTask;
+import org.apache.dubbo.registry.support.SkipFailbackWrapperException;
+import org.apache.dubbo.rpc.Exporter;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.Protocol;
+import org.apache.dubbo.rpc.ProtocolServer;
+import org.apache.dubbo.rpc.ProxyFactory;
+import org.apache.dubbo.rpc.RpcException;
+import org.apache.dubbo.rpc.cluster.Cluster;
+import org.apache.dubbo.rpc.cluster.ClusterInvoker;
+import org.apache.dubbo.rpc.cluster.Configurator;
+import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
+import org.apache.dubbo.rpc.cluster.support.MergeableCluster;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+import org.apache.dubbo.rpc.model.ProviderModel;
+import org.apache.dubbo.rpc.protocol.InvokerWrapper;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import static java.util.concurrent.Executors.newSingleThreadExecutor;
+import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
+import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.EXTRA_KEYS_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX;
+import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
+import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY;
+import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP;
+import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE;
+import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST;
+import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT;
+import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
+import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY;
+import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL;
+import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY;
+import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
+import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL;
+import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY;
+import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_PROTOCOL;
+import static org.apache.dubbo.common.utils.UrlUtils.classifyUrls;
+import static org.apache.dubbo.registry.Constants.CONFIGURATORS_SUFFIX;
+import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL;
+import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_PERIOD;
+import static org.apache.dubbo.registry.Constants.PROVIDER_PROTOCOL;
+import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY;
+import static org.apache.dubbo.registry.Constants.REGISTER_KEY;
+import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY;
+import static org.apache.dubbo.registry.Constants.SIMPLIFIED_KEY;
+import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY;
+import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY;
+import static org.apache.dubbo.remoting.Constants.CHECK_KEY;
+import static org.apache.dubbo.remoting.Constants.CODEC_KEY;
+import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY;
+import static org.apache.dubbo.remoting.Constants.EXCHANGER_KEY;
+import static org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY;
+import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY;
+import static org.apache.dubbo.rpc.Constants.INTERFACES;
+import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
+import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
+import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY;
+import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
+import static org.apache.dubbo.rpc.cluster.Constants.WARMUP_KEY;
+import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY;
+
+/**
+ * TODO, replace RegistryProtocol completely in the future.
+ */
+public class RegistryProtocol implements Protocol {
+ public static final String[] DEFAULT_REGISTER_PROVIDER_KEYS = {
+ APPLICATION_KEY, CODEC_KEY, EXCHANGER_KEY, SERIALIZATION_KEY, CLUSTER_KEY, CONNECTIONS_KEY, DEPRECATED_KEY,
+ GROUP_KEY, LOADBALANCE_KEY, MOCK_KEY, PATH_KEY, TIMEOUT_KEY, TOKEN_KEY, VERSION_KEY, WARMUP_KEY,
+ WEIGHT_KEY, TIMESTAMP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY
+ };
+
+ public static final String[] DEFAULT_REGISTER_CONSUMER_KEYS = {
+ APPLICATION_KEY, VERSION_KEY, GROUP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY
+ };
+
+ private final static Logger logger = LoggerFactory.getLogger(InterfaceCompatibleRegistryProtocol.class);
+ private final Map<URL, NotifyListener> overrideListeners = new ConcurrentHashMap<>();
+ private final Map<String, ServiceConfigurationListener> serviceConfigurationListeners = new ConcurrentHashMap<>();
+ private final ProviderConfigurationListener providerConfigurationListener = new ProviderConfigurationListener();
+ //To solve the problem of RMI repeated exposure port conflicts, the services that have been exposed are no longer exposed.
+ //providerurl <--> exporter
+ private final ConcurrentMap<String, ExporterChangeableWrapper<?>> bounds = new ConcurrentHashMap<>();
+ protected Protocol protocol;
+ protected RegistryFactory registryFactory;
+ protected ProxyFactory proxyFactory;
+
+ private ConcurrentMap<URL, ReExportTask> reExportFailedTasks = new ConcurrentHashMap<>();
+ private HashedWheelTimer retryTimer = new HashedWheelTimer(new NamedThreadFactory("DubboReexportTimer", true), DEFAULT_REGISTRY_RETRY_PERIOD, TimeUnit.MILLISECONDS, 128);
+
+ //Filter the parameters that do not need to be output in url(Starting with .)
+ private static String[] getFilteredKeys(URL url) {
+ Map<String, String> params = url.getParameters();
+ if (CollectionUtils.isNotEmptyMap(params)) {
+ return params.keySet().stream()
+ .filter(k -> k.startsWith(HIDE_KEY_PREFIX))
+ .toArray(String[]::new);
+ } else {
+ return new String[0];
+ }
+ }
+
+ public void setProtocol(Protocol protocol) {
+ this.protocol = protocol;
+ }
+
+ public void setRegistryFactory(RegistryFactory registryFactory) {
+ this.registryFactory = registryFactory;
+ }
+
+ public void setProxyFactory(ProxyFactory proxyFactory) {
+ this.proxyFactory = proxyFactory;
+ }
+
+ @Override
+ public int getDefaultPort() {
+ return 9090;
+ }
+
+ public Map<URL, NotifyListener> getOverrideListeners() {
+ return overrideListeners;
+ }
+
+ private void register(URL registryUrl, URL registeredProviderUrl) {
+ Registry registry = registryFactory.getRegistry(registryUrl);
+ registry.register(registeredProviderUrl);
+ }
+
+ private void registerStatedUrl(URL registryUrl, URL registeredProviderUrl, boolean registered) {
+ ProviderModel model = ApplicationModel.getProviderModel(registeredProviderUrl.getServiceKey());
+ model.addStatedUrl(new ProviderModel.RegisterStatedURL(
+ registeredProviderUrl,
+ registryUrl,
+ registered));
+ }
+
+ @Override
+ public <T> Exporter<T> export(final Invoker<T> originInvoker) throws RpcException {
+ URL registryUrl = getRegistryUrl(originInvoker);
+ // url to export locally
+ URL providerUrl = getProviderUrl(originInvoker);
+
+ // Subscribe the override data
+ // FIXME When the provider subscribes, it will affect the scene : a certain JVM exposes the service and call
+ // the same service. Because the subscribed is cached key with the name of the service, it causes the
+ // subscription information to cover.
+ final URL overrideSubscribeUrl = getSubscribedOverrideUrl(providerUrl);
+ final OverrideListener overrideSubscribeListener = new OverrideListener(overrideSubscribeUrl, originInvoker);
+ overrideListeners.put(overrideSubscribeUrl, overrideSubscribeListener);
+
+ providerUrl = overrideUrlWithConfig(providerUrl, overrideSubscribeListener);
+ //export invoker
+ final ExporterChangeableWrapper<T> exporter = doLocalExport(originInvoker, providerUrl);
+
+ // url to registry
+ final Registry registry = getRegistry(originInvoker);
+ final URL registeredProviderUrl = getUrlToRegistry(providerUrl, registryUrl);
+
+ // decide if we need to delay publish
+ boolean register = providerUrl.getParameter(REGISTER_KEY, true);
+ if (register) {
+ register(registryUrl, registeredProviderUrl);
+ }
+
+ // register stated url on provider model
+ registerStatedUrl(registryUrl, registeredProviderUrl, register);
+
+
+ exporter.setRegisterUrl(registeredProviderUrl);
+ exporter.setSubscribeUrl(overrideSubscribeUrl);
+
+ // Deprecated! Subscribe to override rules in 2.6.x or before.
+ registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener);
+
+ notifyExport(exporter);
+ //Ensure that a new exporter instance is returned every time export
+ return new DestroyableExporter<>(exporter);
+ }
+
+ private <T> void notifyExport(ExporterChangeableWrapper<T> exporter) {
+ List<RegistryProtocolListener> listeners = ExtensionLoader.getExtensionLoader(RegistryProtocolListener.class)
+ .getActivateExtension(exporter.getOriginInvoker().getUrl(), "registry.protocol.listener");
+ if (CollectionUtils.isNotEmpty(listeners)) {
+ for (RegistryProtocolListener listener : listeners) {
+ listener.onExport(this, exporter);
+ }
+ }
+ }
+
+ private URL overrideUrlWithConfig(URL providerUrl, OverrideListener listener) {
+ providerUrl = providerConfigurationListener.overrideUrl(providerUrl);
+ ServiceConfigurationListener serviceConfigurationListener = new ServiceConfigurationListener(providerUrl, listener);
+ serviceConfigurationListeners.put(providerUrl.getServiceKey(), serviceConfigurationListener);
+ return serviceConfigurationListener.overrideUrl(providerUrl);
+ }
+
+ @SuppressWarnings("unchecked")
+ private <T> ExporterChangeableWrapper<T> doLocalExport(final Invoker<T> originInvoker, URL providerUrl) {
+ String key = getCacheKey(originInvoker);
+
+ return (ExporterChangeableWrapper<T>) bounds.computeIfAbsent(key, s -> {
+ Invoker<?> invokerDelegate = new InvokerDelegate<>(originInvoker, providerUrl);
+ return new ExporterChangeableWrapper<>((Exporter<T>) protocol.export(invokerDelegate), originInvoker);
+ });
+ }
+
+ public <T> void reExport(Exporter<T> exporter, URL newInvokerUrl) {
+ if (exporter instanceof ExporterChangeableWrapper) {
+ ExporterChangeableWrapper<T> exporterWrapper = (ExporterChangeableWrapper<T>) exporter;
+ Invoker<T> originInvoker = exporterWrapper.getOriginInvoker();
+ reExport(originInvoker, newInvokerUrl);
+ }
+ }
+
+ /**
+ * Reexport the invoker of the modified url
+ *
+ * @param originInvoker
+ * @param newInvokerUrl
+ * @param <T>
+ */
+ @SuppressWarnings("unchecked")
+ public <T> void reExport(final Invoker<T> originInvoker, URL newInvokerUrl) {
+ String key = getCacheKey(originInvoker);
+ ExporterChangeableWrapper<T> exporter = (ExporterChangeableWrapper<T>) bounds.get(key);
+ URL registeredUrl = exporter.getRegisterUrl();
+
+ URL registryUrl = getRegistryUrl(originInvoker);
+ URL newProviderUrl = getUrlToRegistry(newInvokerUrl, registryUrl);
+
+ // update local exporter
+ Invoker<T> invokerDelegate = new InvokerDelegate<T>(originInvoker, newInvokerUrl);
+ exporter.setExporter(protocol.export(invokerDelegate));
+
+ // update registry
+ if (!newProviderUrl.equals(registeredUrl)) {
+ try {
+ doReExport(originInvoker, exporter, registryUrl, registeredUrl, newProviderUrl);
+ } catch (Exception e) {
+ ReExportTask oldTask = reExportFailedTasks.get(registeredUrl);
+ if (oldTask != null) {
+ return;
+ }
... 7998 lines suppressed ...