repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/service/DemoService.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/service/DemoService.java | /*
* 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.service;
public interface DemoService {
String sayHello(String str);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/service/DemoService2.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/service/DemoService2.java | /*
* 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.service;
public interface DemoService2 {
String sayHello(String str);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DemoService.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DemoService.java | /*
* 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;
public interface DemoService {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DynamicDirectoryTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DynamicDirectoryTest.java | /*
* 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.url.component.ServiceConfigURL;
import org.apache.dubbo.registry.Registry;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY;
import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY;
import static org.apache.dubbo.registry.Constants.SIMPLIFIED_KEY;
import static org.apache.dubbo.registry.integration.RegistryProtocol.DEFAULT_REGISTER_CONSUMER_KEYS;
import static org.apache.dubbo.remoting.Constants.CHECK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
class DynamicDirectoryTest {
/**
* verify simplified consumer url information that needs to be registered
*/
@Test
void testSimplifiedUrl() {
// verify that the consumer url information that needs to be registered is not simplified by default
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "true");
parameters.put(REGISTER_IP_KEY, "172.23.236.180");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURLWithoutSimplified = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
attributes.put("key1", "value1");
URL urlWithoutSimplified = serviceConfigURLWithoutSimplified.addAttributes(attributes);
DemoDynamicDirectory<DemoService> dynamicDirectoryWithoutSimplified =
new DemoDynamicDirectory<>(DemoService.class, urlWithoutSimplified);
URL registeredConsumerUrlWithoutSimplified =
new ServiceConfigURL("dubbo", "127.0.0.1", 2181, DemoService.class.getName(), parameters);
dynamicDirectoryWithoutSimplified.setRegisteredConsumerUrl(registeredConsumerUrlWithoutSimplified);
URL urlForNotSimplified = registeredConsumerUrlWithoutSimplified.addParameters(
CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false));
Assertions.assertEquals(urlForNotSimplified, dynamicDirectoryWithoutSimplified.getRegisteredConsumerUrl());
// verify simplified consumer url information that needs to be registered
parameters.put(SIMPLIFIED_KEY, "true");
ServiceConfigURL serviceConfigURLWithSimplified = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
URL urlWithSimplified = serviceConfigURLWithSimplified.addAttributes(attributes);
DemoDynamicDirectory<DemoService> dynamicDirectoryWithSimplified =
new DemoDynamicDirectory<>(DemoService.class, urlWithSimplified);
URL registeredConsumerUrlWithSimplified =
new ServiceConfigURL("dubbo", "127.0.0.1", 2181, DemoService.class.getName(), parameters);
dynamicDirectoryWithSimplified.setRegisteredConsumerUrl(registeredConsumerUrlWithSimplified);
URL urlForSimplified = URL.valueOf(registeredConsumerUrlWithSimplified, DEFAULT_REGISTER_CONSUMER_KEYS, null)
.addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false));
Assertions.assertEquals(urlForSimplified, dynamicDirectoryWithSimplified.getRegisteredConsumerUrl());
}
@Test
void testSubscribe() {
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "true");
parameters.put(REGISTER_IP_KEY, "172.23.236.180");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigUrl = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
attributes.put("key1", "value1");
URL url = serviceConfigUrl.addAttributes(attributes);
DemoDynamicDirectory<DemoService> demoDynamicDirectory = new DemoDynamicDirectory<>(DemoService.class, url);
URL subscribeUrl = new ServiceConfigURL("dubbo", "127.0.0.1", 20881, DemoService.class.getName(), parameters);
Registry registry = mock(Registry.class);
demoDynamicDirectory.setRegistry(registry);
demoDynamicDirectory.subscribe(subscribeUrl);
verify(registry, times(1)).subscribe(subscribeUrl, demoDynamicDirectory);
Assertions.assertEquals(subscribeUrl, demoDynamicDirectory.getSubscribeUrl());
}
static class DemoDynamicDirectory<T> extends DynamicDirectory<T> {
public DemoDynamicDirectory(Class<T> serviceType, URL url) {
super(serviceType, url);
}
@Override
protected void destroyAllInvokers() {}
@Override
protected void refreshOverrideAndInvoker(List<URL> urls) {}
@Override
public boolean isAvailable() {
return false;
}
@Override
public void notify(List<URL> urls) {}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/CountRegistryProtocolListener.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/CountRegistryProtocolListener.java | /*
* 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.rpc.Exporter;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import java.util.concurrent.atomic.AtomicInteger;
public class CountRegistryProtocolListener implements RegistryProtocolListener {
private static final AtomicInteger referCounter = new AtomicInteger(0);
@Override
public void onExport(RegistryProtocol registryProtocol, Exporter<?> exporter) {}
@Override
public void onRefer(RegistryProtocol registryProtocol, ClusterInvoker<?> invoker, URL url, URL registryURL) {
referCounter.incrementAndGet();
}
@Override
public void onDestroy() {}
public static AtomicInteger getReferCounter() {
return referCounter;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/RegistryProtocolTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/RegistryProtocolTest.java | /*
* 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.config.CompositeConfiguration;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.registry.client.migration.MigrationRuleListener;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.support.FailoverCluster;
import org.apache.dubbo.rpc.cluster.support.wrapper.MockClusterWrapper;
import org.apache.dubbo.rpc.cluster.support.wrapper.ScopeClusterWrapper;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
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.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_PROTOCOL_LISTENER_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY;
import static org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN;
import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY;
import static org.apache.dubbo.remoting.Constants.CHECK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.CONSUMER_URL_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RegistryProtocolTest {
@AfterEach
public void tearDown() throws IOException {
Mockito.framework().clearInlineMocks();
ApplicationModel.defaultModel().destroy();
}
/**
* verify the generated consumer url information
*/
@Test
void testConsumerUrlWithoutProtocol() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "false");
parameters.put(REGISTER_IP_KEY, "172.23.236.180");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
attributes.put("key1", "value1");
URL url = serviceConfigURL.addAttributes(attributes);
RegistryFactory registryFactory = mock(RegistryFactory.class);
Registry registry = mock(Registry.class);
RegistryProtocol registryProtocol = new RegistryProtocol();
MigrationRuleListener migrationRuleListener = mock(MigrationRuleListener.class);
List<RegistryProtocolListener> registryProtocolListeners = new ArrayList<>();
registryProtocolListeners.add(migrationRuleListener);
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader<RegistryProtocolListener> extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class))
.thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY))
.thenReturn(registryProtocolListeners);
url = url.setScopeModel(moduleModel);
when(registryFactory.getRegistry(registryProtocol.getRegistryUrl(url))).thenReturn(registry);
Cluster cluster = mock(Cluster.class);
Invoker<?> invoker = registryProtocol.doRefer(cluster, registry, DemoService.class, url, parameters);
Assertions.assertTrue(invoker instanceof MigrationInvoker);
URL consumerUrl = ((MigrationInvoker<?>) invoker).getConsumerUrl();
Assertions.assertTrue((consumerUrl != null));
// verify that the protocol header of consumerUrl is set to "consumer"
Assertions.assertEquals("consumer", consumerUrl.getProtocol());
Assertions.assertEquals(parameters.get(REGISTER_IP_KEY), consumerUrl.getHost());
Assertions.assertFalse(consumerUrl.getAttributes().containsKey(REFER_KEY));
Assertions.assertEquals("value1", consumerUrl.getAttribute("key1"));
}
/**
* verify that when the protocol is configured, the protocol of consumer url is the configured protocol
*/
@Test
void testConsumerUrlWithProtocol() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "false");
parameters.put(REGISTER_IP_KEY, "172.23.236.180");
parameters.put(PROTOCOL_KEY, "tri");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
attributes.put("key1", "value1");
URL url = serviceConfigURL.addAttributes(attributes);
RegistryFactory registryFactory = mock(RegistryFactory.class);
RegistryProtocol registryProtocol = new RegistryProtocol();
Registry registry = mock(Registry.class);
MigrationRuleListener migrationRuleListener = mock(MigrationRuleListener.class);
List<RegistryProtocolListener> registryProtocolListeners = new ArrayList<>();
registryProtocolListeners.add(migrationRuleListener);
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader<RegistryProtocolListener> extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class))
.thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY))
.thenReturn(registryProtocolListeners);
url = url.setScopeModel(moduleModel);
when(registryFactory.getRegistry(registryProtocol.getRegistryUrl(url))).thenReturn(registry);
Cluster cluster = mock(Cluster.class);
Invoker<?> invoker = registryProtocol.doRefer(cluster, registry, DemoService.class, url, parameters);
Assertions.assertTrue(invoker instanceof MigrationInvoker);
URL consumerUrl = ((MigrationInvoker<?>) invoker).getConsumerUrl();
Assertions.assertTrue((consumerUrl != null));
// verify that the protocol of consumer url
Assertions.assertEquals("tri", consumerUrl.getProtocol());
Assertions.assertEquals(parameters.get(REGISTER_IP_KEY), consumerUrl.getHost());
Assertions.assertFalse(consumerUrl.getAttributes().containsKey(REFER_KEY));
Assertions.assertEquals("value1", consumerUrl.getAttribute("key1"));
}
/**
* verify that if multiple groups are not configured, the service reference of the registration center
* the default is FailoverCluster
*
* @see FailoverCluster
*/
@Test
void testReferWithoutGroup() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "false");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
URL url = serviceConfigURL.addAttributes(attributes);
RegistryFactory registryFactory = mock(RegistryFactory.class);
Registry registry = mock(Registry.class);
MigrationRuleListener migrationRuleListener = mock(MigrationRuleListener.class);
List<RegistryProtocolListener> registryProtocolListeners = new ArrayList<>();
registryProtocolListeners.add(migrationRuleListener);
RegistryProtocol registryProtocol = new RegistryProtocol();
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class))
.thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY))
.thenReturn(registryProtocolListeners);
Mockito.when(moduleModel.getExtensionLoader(RegistryFactory.class)).thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getAdaptiveExtension()).thenReturn(registryFactory);
url = url.setScopeModel(moduleModel);
when(registryFactory.getRegistry(registryProtocol.getRegistryUrl(url))).thenReturn(registry);
Invoker<?> invoker = registryProtocol.refer(DemoService.class, url);
Assertions.assertTrue(invoker instanceof MigrationInvoker);
Assertions.assertTrue(((MigrationInvoker<?>) invoker).getCluster() instanceof ScopeClusterWrapper);
Assertions.assertTrue(
((ScopeClusterWrapper) ((MigrationInvoker<?>) invoker).getCluster()).getCluster()
instanceof MockClusterWrapper);
Assertions.assertTrue(
((MockClusterWrapper) ((ScopeClusterWrapper) ((MigrationInvoker<?>) invoker).getCluster()).getCluster())
.getCluster()
instanceof FailoverCluster);
}
/**
* verify that if multiple groups are configured, the service reference of the registration center
*
* @see MergeableCluster
*/
@Test
void testReferWithGroup() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "false");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
refer.put(GROUP_KEY, "group1,group2");
attributes.put(REFER_KEY, refer);
URL url = serviceConfigURL.addAttributes(attributes);
RegistryFactory registryFactory = mock(RegistryFactory.class);
Registry registry = mock(Registry.class);
MigrationRuleListener migrationRuleListener = mock(MigrationRuleListener.class);
List<RegistryProtocolListener> registryProtocolListeners = new ArrayList<>();
registryProtocolListeners.add(migrationRuleListener);
RegistryProtocol registryProtocol = new RegistryProtocol();
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class))
.thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY))
.thenReturn(registryProtocolListeners);
Mockito.when(moduleModel.getExtensionLoader(RegistryFactory.class)).thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getAdaptiveExtension()).thenReturn(registryFactory);
url = url.setScopeModel(moduleModel);
when(registryFactory.getRegistry(registryProtocol.getRegistryUrl(url))).thenReturn(registry);
Invoker<?> invoker = registryProtocol.refer(DemoService.class, url);
Assertions.assertTrue(invoker instanceof MigrationInvoker);
Assertions.assertTrue(((MigrationInvoker<?>) invoker).getCluster() instanceof ScopeClusterWrapper);
// Assertions.assertTrue(((ScopeClusterWrapper) ((MigrationInvoker<?>)
// invoker).getCluster()).getCluster() instanceof MockClusterWrapper);
// Assertions.assertTrue(((MockClusterWrapper) ((ScopeClusterWrapper) ((MigrationInvoker<?>)
// invoker).getCluster()).getCluster()).getCluster() instanceof MergeableCluster);
}
/**
* verify that the default RegistryProtocolListener will be executed
*
* @see MigrationRuleListener
*/
@Test
void testInterceptInvokerForMigrationRuleListener() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "false");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
refer.put(GROUP_KEY, "group1,group2");
attributes.put(REFER_KEY, refer);
URL url = serviceConfigURL.addAttributes(attributes);
MigrationInvoker<?> clusterInvoker = mock(MigrationInvoker.class);
Map<String, Object> consumerAttribute = new HashMap<>(url.getAttributes());
consumerAttribute.remove(REFER_KEY);
URL consumerUrl = new ServiceConfigURL(
parameters.get(PROTOCOL_KEY) == null ? DUBBO : parameters.get(PROTOCOL_KEY),
null,
null,
parameters.get(REGISTER_IP_KEY),
0,
url.getPath(),
parameters,
consumerAttribute);
url = url.putAttribute(CONSUMER_URL_KEY, consumerUrl);
MigrationRuleListener migrationRuleListener = mock(MigrationRuleListener.class);
List<RegistryProtocolListener> registryProtocolListeners = new ArrayList<>();
registryProtocolListeners.add(migrationRuleListener);
RegistryProtocol registryProtocol = new RegistryProtocol();
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader<RegistryProtocolListener> extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class))
.thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY))
.thenReturn(registryProtocolListeners);
url = url.setScopeModel(moduleModel);
registryProtocol.interceptInvoker(clusterInvoker, url, consumerUrl);
verify(migrationRuleListener, times(1)).onRefer(registryProtocol, clusterInvoker, consumerUrl, url);
}
/**
* Verify that if registry.protocol.listener is configured,
* whether the corresponding RegistryProtocolListener will be executed normally
*
* @see CountRegistryProtocolListener
*/
@Test
void testInterceptInvokerForCustomRegistryProtocolListener() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "false");
parameters.put(REGISTRY_PROTOCOL_LISTENER_KEY, "count");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
refer.put(GROUP_KEY, "group1,group2");
attributes.put(REFER_KEY, refer);
URL url = serviceConfigURL.addAttributes(attributes);
RegistryProtocol registryProtocol = new RegistryProtocol();
MigrationInvoker<?> clusterInvoker = mock(MigrationInvoker.class);
Map<String, Object> consumerAttribute = new HashMap<>(url.getAttributes());
consumerAttribute.remove(REFER_KEY);
URL consumerUrl = new ServiceConfigURL(
parameters.get(PROTOCOL_KEY) == null ? DUBBO : parameters.get(PROTOCOL_KEY),
null,
null,
parameters.get(REGISTER_IP_KEY),
0,
url.getPath(),
parameters,
consumerAttribute);
url = url.putAttribute(CONSUMER_URL_KEY, consumerUrl);
List<RegistryProtocolListener> registryProtocolListeners = new ArrayList<>();
registryProtocolListeners.add(new CountRegistryProtocolListener());
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader<RegistryProtocolListener> extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class))
.thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY))
.thenReturn(registryProtocolListeners);
url = url.setScopeModel(moduleModel);
registryProtocol.interceptInvoker(clusterInvoker, url, consumerUrl);
Assertions.assertEquals(
1, CountRegistryProtocolListener.getReferCounter().get());
}
/**
* verify the registered consumer url
*/
@Test
void testRegisterConsumerUrl() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "true");
parameters.put(REGISTER_IP_KEY, "172.23.236.180");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
attributes.put("key1", "value1");
URL url = serviceConfigURL.addAttributes(attributes);
RegistryFactory registryFactory = mock(RegistryFactory.class);
Registry registry = mock(Registry.class);
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryFactory.class)).thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getAdaptiveExtension()).thenReturn(registryFactory);
url = url.setScopeModel(moduleModel);
RegistryProtocol registryProtocol = new RegistryProtocol();
when(registryFactory.getRegistry(registryProtocol.getRegistryUrl(url))).thenReturn(registry);
Cluster cluster = mock(Cluster.class);
Invoker<?> invoker = registryProtocol.doRefer(cluster, registry, DemoService.class, url, parameters);
Assertions.assertTrue(invoker instanceof MigrationInvoker);
URL consumerUrl = ((MigrationInvoker<?>) invoker).getConsumerUrl();
Assertions.assertTrue((consumerUrl != null));
Map<String, String> urlParameters = consumerUrl.getParameters();
URL urlToRegistry = new ServiceConfigURL(
urlParameters.get(PROTOCOL_KEY) == null ? CONSUMER : urlParameters.get(PROTOCOL_KEY),
urlParameters.remove(REGISTER_IP_KEY),
0,
consumerUrl.getPath(),
urlParameters);
URL registeredConsumerUrl = urlToRegistry
.addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false))
.setScopeModel(moduleModel);
verify(registry, times(1)).register(registeredConsumerUrl);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InstanceAddressURLTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InstanceAddressURLTest.java | /*
* 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.CollectionUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.ProviderFirstParams;
import org.apache.dubbo.rpc.RpcServiceContext;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.in;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class InstanceAddressURLTest {
private static URL url = URL.valueOf(
"dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?"
+ "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=1000&deprecated=false&dubbo=2.0.2"
+ "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService"
+ "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&a.timeout=7777&pid=66666&release=&revision=1.0.0&service-name-mapping=true"
+ "&side=provider&timeout=1000×tamp=1629970909999&version=1.0.0&dubbo.tag=provider¶ms-filter=-default");
private static URL url2 = URL.valueOf(
"dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService2?"
+ "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2"
+ "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService2"
+ "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true"
+ "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0&dubbo.tag=provider2&uniqueKey=unique¶ms-filter=-default");
private static URL consumerURL = URL.valueOf("dubbo://30.225.21.30/org.apache.dubbo.registry.service.DemoService?"
+ "REGISTRY_CLUSTER=registry1&application=demo-consumer&dubbo=2.0.2"
+ "&group=greeting&interface=org.apache.dubbo.registry.service.DemoService"
+ "&version=1.0.0&timeout=9000&a.timeout=8888&dubbo.tag=consumer&protocol=dubbo");
private DefaultServiceInstance createInstance() {
DefaultServiceInstance instance =
new DefaultServiceInstance("demo-provider", "127.0.0.1", 8080, ApplicationModel.defaultModel());
Map<String, String> metadata = instance.getMetadata();
metadata.put("key1", "value1");
metadata.put("key2", "value2");
return instance;
}
private MetadataInfo createMetaDataInfo() {
MetadataInfo metadataInfo = new MetadataInfo("demo");
// export normal url again
metadataInfo.addService(url);
metadataInfo.addService(url2);
return metadataInfo;
}
private InstanceAddressURL instanceURL;
private transient volatile Set<String> providerFirstParams;
@BeforeEach
public void setUp() {
DefaultServiceInstance instance = createInstance();
MetadataInfo metadataInfo = createMetaDataInfo();
instanceURL = new InstanceAddressURL(instance, metadataInfo);
Set<ProviderFirstParams> providerFirstParams = ApplicationModel.defaultModel()
.getExtensionLoader(ProviderFirstParams.class)
.getSupportedExtensionInstances();
if (CollectionUtils.isEmpty(providerFirstParams)) {
this.providerFirstParams = null;
} else {
if (providerFirstParams.size() == 1) {
this.providerFirstParams = Collections.unmodifiableSet(
providerFirstParams.iterator().next().params());
} else {
Set<String> params = new HashSet<>();
for (ProviderFirstParams paramsFilter : providerFirstParams) {
if (paramsFilter.params() == null) {
break;
}
params.addAll(paramsFilter.params());
}
this.providerFirstParams = Collections.unmodifiableSet(params);
}
}
instanceURL.setProviderFirstParams(this.providerFirstParams);
}
@Test
void test1() {
// test reading of keys in instance and metadata work fine
assertEquals("value1", instanceURL.getParameter("key1")); // return instance key
assertNull(instanceURL.getParameter("delay")); // no service key specified
RpcServiceContext.getServiceContext().setConsumerUrl(consumerURL);
assertEquals("1000", instanceURL.getParameter("delay"));
assertEquals("1000", instanceURL.getServiceParameter(consumerURL.getProtocolServiceKey(), "delay"));
assertEquals("9000", instanceURL.getMethodParameter("sayHello", "timeout"));
assertEquals(
"9000",
instanceURL.getServiceMethodParameter(consumerURL.getProtocolServiceKey(), "sayHello", "timeout"));
assertNull(instanceURL.getParameter("uniqueKey"));
assertNull(instanceURL.getServiceParameter(consumerURL.getProtocolServiceKey(), "uniqueKey"));
assertEquals("unique", instanceURL.getServiceParameter(url2.getProtocolServiceKey(), "uniqueKey"));
// test some consumer keys have higher priority
assertEquals(
"8888", instanceURL.getServiceMethodParameter(consumerURL.getProtocolServiceKey(), "a", "timeout"));
assertEquals("9000", instanceURL.getParameter("timeout"));
// test some provider keys have higher priority
assertEquals("provider", instanceURL.getParameter(TAG_KEY));
assertEquals(instanceURL.getVersion(), instanceURL.getParameter(VERSION_KEY));
assertEquals(instanceURL.getGroup(), instanceURL.getParameter(GROUP_KEY));
assertEquals(instanceURL.getApplication(), instanceURL.getParameter(APPLICATION_KEY));
assertEquals("demo-consumer", instanceURL.getParameter(APPLICATION_KEY));
assertEquals(instanceURL.getRemoteApplication(), instanceURL.getParameter(REMOTE_APPLICATION_KEY));
assertEquals("demo-provider", instanceURL.getParameter(REMOTE_APPLICATION_KEY));
assertEquals(instanceURL.getSide(), instanceURL.getParameter(SIDE_KEY));
// assertThat(Arrays.asList("7000", "8888"), hasItem(instanceURL.getAnyMethodParameter("timeout")));
assertThat(instanceURL.getAnyMethodParameter("timeout"), in(Arrays.asList("7000", "8888")));
Map<String, String> expectedAllParams = new HashMap<>();
expectedAllParams.putAll(instanceURL.getInstance().getMetadata());
expectedAllParams.putAll(instanceURL
.getMetadataInfo()
.getServiceInfo(consumerURL.getProtocolServiceKey())
.getAllParams());
Map<String, String> consumerURLParameters = consumerURL.getParameters();
providerFirstParams.forEach(consumerURLParameters::remove);
expectedAllParams.putAll(consumerURLParameters);
assertEquals(expectedAllParams.size(), instanceURL.getParameters().size());
assertEquals(url.getParameter(TAG_KEY), instanceURL.getParameters().get(TAG_KEY));
assertEquals(
consumerURL.getParameter(TIMEOUT_KEY),
instanceURL.getParameters().get(TIMEOUT_KEY));
assertTrue(instanceURL.hasServiceMethodParameter(url.getProtocolServiceKey(), "a"));
assertTrue(instanceURL.hasServiceMethodParameter(url.getProtocolServiceKey(), "sayHello"));
assertTrue(instanceURL.hasMethodParameter("a", TIMEOUT_KEY));
assertTrue(instanceURL.hasMethodParameter(null, TIMEOUT_KEY));
assertEquals("8888", instanceURL.getMethodParameter("a", TIMEOUT_KEY));
assertTrue(instanceURL.hasMethodParameter("a", null));
assertFalse(instanceURL.hasMethodParameter("notExistMethod", null));
// keys added to instance url are shared among services.
instanceURL.addParameter("newKey", "newValue");
assertEquals("newValue", instanceURL.getParameter("newKey"));
assertEquals("newValue", instanceURL.getParameters().get("newKey"));
assertEquals(
"newValue",
instanceURL.getServiceParameters(url.getProtocolServiceKey()).get("newKey"));
}
@Test
void test2() {
RpcServiceContext.getServiceContext().setConsumerUrl(null);
Assertions.assertNull(instanceURL.getScopeModel());
ModuleModel moduleModel = Mockito.mock(ModuleModel.class);
RpcServiceContext.getServiceContext().setConsumerUrl(URL.valueOf("").setScopeModel(moduleModel));
Assertions.assertEquals(moduleModel, instanceURL.getScopeModel());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryCacheTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryCacheTest.java | /*
* 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.config.ApplicationConfig;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.client.support.MockServiceDiscovery;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_INFO_CACHE_EXPIRE_KEY;
import static org.awaitility.Awaitility.await;
class ServiceDiscoveryCacheTest {
@Test
void test() throws InterruptedException {
ApplicationModel applicationModel = FrameworkModel.defaultModel().newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("Test"));
URL registryUrl = URL.valueOf("mock://127.0.0.1:12345").addParameter(METADATA_INFO_CACHE_EXPIRE_KEY, 10);
MockServiceDiscovery mockServiceDiscovery =
Mockito.spy(new MockServiceDiscovery(applicationModel, registryUrl));
mockServiceDiscovery.register(URL.valueOf("mock://127.0.0.1:12345")
.setServiceInterface("org.apache.dubbo.registry.service.DemoService"));
mockServiceDiscovery.register();
ServiceInstance localInstance = mockServiceDiscovery.getLocalInstance();
Assertions.assertEquals(
localInstance.getServiceMetadata(),
mockServiceDiscovery.getLocalMetadata(
localInstance.getServiceMetadata().getRevision()));
List<MetadataInfo> instances = new LinkedList<>();
instances.add(localInstance.getServiceMetadata().clone());
for (int i = 0; i < 15; i++) {
Thread.sleep(1);
mockServiceDiscovery.register(URL.valueOf("mock://127.0.0.1:12345")
.setServiceInterface("org.apache.dubbo.registry.service.DemoService" + i));
mockServiceDiscovery.update();
instances.add(
mockServiceDiscovery.getLocalInstance().getServiceMetadata().clone());
}
for (MetadataInfo instance : instances) {
Assertions.assertEquals(instance, mockServiceDiscovery.getLocalMetadata(instance.getRevision()));
}
for (int i = 0; i < 5; i++) {
Thread.sleep(1);
mockServiceDiscovery.register(URL.valueOf("mock://127.0.0.1:12345")
.setServiceInterface("org.apache.dubbo.registry.service.DemoService-new" + i));
mockServiceDiscovery.update();
instances.add(
mockServiceDiscovery.getLocalInstance().getServiceMetadata().clone());
}
await().until(() -> Objects.isNull(
mockServiceDiscovery.getLocalMetadata(instances.get(4).getRevision())));
for (int i = 0; i < 5; i++) {
Assertions.assertNull(
mockServiceDiscovery.getLocalMetadata(instances.get(i).getRevision()));
}
applicationModel.destroy();
}
/**
* to fix #14126
*/
@Test
void testUpdateWhenFirstDoRegisterFail() throws InterruptedException {
ApplicationModel applicationModel = FrameworkModel.defaultModel().newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("Test"));
URL registryUrl = URL.valueOf("mock://127.0.0.1:12345").addParameter(METADATA_INFO_CACHE_EXPIRE_KEY, 10);
MockServiceDiscovery mockServiceDiscovery =
Mockito.spy(new MockServiceDiscovery(applicationModel, registryUrl));
mockServiceDiscovery.register(URL.valueOf("mock://127.0.0.1:12345")
.setServiceInterface("org.apache.dubbo.registry.service.DemoService"));
Thread.sleep(100);
Mockito.doThrow(new RuntimeException())
.when(mockServiceDiscovery)
.doRegister(Mockito.any(ServiceInstance.class));
Assertions.assertThrows(RuntimeException.class, mockServiceDiscovery::update);
Thread.sleep(100);
Mockito.doNothing().when(mockServiceDiscovery).doRegister(Mockito.any(ServiceInstance.class));
Assertions.assertDoesNotThrow(mockServiceDiscovery::update);
Thread.sleep(100);
Assertions.assertDoesNotThrow(mockServiceDiscovery::update);
applicationModel.destroy();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java | /*
* 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.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metadata.AbstractServiceNameMapping;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.client.event.listener.MockServiceInstancesChangedListener;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDED_BY;
import static org.apache.dubbo.metadata.ServiceNameMapping.toStringKeys;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ServiceDiscoveryRegistryTest {
public static final String APP_NAME1 = "app1";
public static final String APP_NAME2 = "app2";
public static final String APP_NAME3 = "app3";
private static AbstractServiceNameMapping mapping = mock(AbstractServiceNameMapping.class);
private static Lock lock = new ReentrantLock();
private static URL registryURL =
URL.valueOf("zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService");
private static URL url =
URL.valueOf("consumer://127.0.0.1/TestService?interface=TestService1&check=false&protocol=dubbo");
private static NotifyListener testServiceListener = mock(NotifyListener.class);
private static List<ServiceInstance> instanceList1 = new ArrayList<>();
private static List<ServiceInstance> instanceList2 = new ArrayList<>();
private ServiceDiscoveryRegistry serviceDiscoveryRegistry;
private ServiceDiscovery serviceDiscovery;
private MockServiceInstancesChangedListener instanceListener;
private ServiceNameMapping serviceNameMapping;
@BeforeAll
public static void setUp() {
instanceList1.add(new DefaultServiceInstance());
instanceList1.add(new DefaultServiceInstance());
instanceList1.add(new DefaultServiceInstance());
instanceList2.add(new DefaultServiceInstance());
instanceList2.add(new DefaultServiceInstance());
}
@AfterEach
public void teardown() {
FrameworkModel.destroyAll();
}
@BeforeEach
public void init() {
serviceDiscovery = mock(ServiceDiscovery.class);
instanceListener = spy(new MockServiceInstancesChangedListener(Collections.emptySet(), serviceDiscovery));
doNothing().when(instanceListener).onEvent(any());
when(serviceDiscovery.createListener(any())).thenReturn(instanceListener);
when(serviceDiscovery.getInstances(any())).thenReturn(Collections.emptyList());
when(serviceDiscovery.getUrl()).thenReturn(url);
ApplicationModel applicationModel = spy(ApplicationModel.defaultModel());
when(applicationModel.getDefaultExtension(ServiceNameMapping.class)).thenReturn(mapping);
registryURL = registryURL.setScopeModel(applicationModel);
serviceDiscoveryRegistry = new ServiceDiscoveryRegistry(registryURL, serviceDiscovery, mapping);
when(mapping.getMappingLock(any())).thenReturn(lock);
when(testServiceListener.getConsumerUrl()).thenReturn(url);
}
/**
* Test subscribe
* - Normal case
* - Exceptional case
* - check=true
* - check=false
*/
@Test
void testDoSubscribe() {
ApplicationModel applicationModel = spy(ApplicationModel.defaultModel());
when(applicationModel.getDefaultExtension(ServiceNameMapping.class)).thenReturn(mapping);
// Exceptional case, no interface-app mapping found
when(mapping.getAndListen(any(), any(), any())).thenReturn(Collections.emptySet());
// when check = false
try {
registryURL = registryURL.setScopeModel(applicationModel);
serviceDiscoveryRegistry = new ServiceDiscoveryRegistry(registryURL, serviceDiscovery, mapping);
serviceDiscoveryRegistry.doSubscribe(url, testServiceListener);
} finally {
registryURL = registryURL.setScopeModel(null);
serviceDiscoveryRegistry.unsubscribe(url, testServiceListener);
}
// // when check = true
URL checkURL = url.addParameter(CHECK_KEY, true);
checkURL.setScopeModel(url.getApplicationModel());
// Exception exceptionShouldHappen = null;
// try {
// serviceDiscoveryRegistry.doSubscribe(checkURL, testServiceListener);
// } catch (IllegalStateException e) {
// exceptionShouldHappen = e;
// } finally {
// serviceDiscoveryRegistry.unsubscribe(checkURL, testServiceListener);
// }
// if (exceptionShouldHappen == null) {
// fail();
// }
// Normal case
Set<String> singleApp = new HashSet<>();
singleApp.add(APP_NAME1);
when(mapping.getAndListen(any(), any(), any())).thenReturn(singleApp);
try {
serviceDiscoveryRegistry.doSubscribe(checkURL, testServiceListener);
} finally {
serviceDiscoveryRegistry.unsubscribe(checkURL, testServiceListener);
}
// test provider case
checkURL = url.addParameter(PROVIDED_BY, APP_NAME1);
try {
serviceDiscoveryRegistry.doSubscribe(checkURL, testServiceListener);
} finally {
serviceDiscoveryRegistry.unsubscribe(checkURL, testServiceListener);
}
}
/**
* Test instance listener registration
* - one app
* - multi apps
* - repeat same multi apps, instance listener shared
* - protocol included in key
* - instance listener gets notified
* - instance listener and service listener rightly mapped
*/
@Test
void testSubscribeURLs() {
// interface to single app mapping
Set<String> singleApp = new TreeSet<>();
singleApp.add(APP_NAME1);
serviceDiscoveryRegistry.subscribeURLs(url, testServiceListener, singleApp);
assertEquals(1, serviceDiscoveryRegistry.getServiceListeners().size());
verify(testServiceListener, times(1)).addServiceListener(instanceListener);
verify(instanceListener, never()).onEvent(any());
verify(serviceDiscovery, times(1)).addServiceInstancesChangedListener(instanceListener);
// interface to multiple apps mapping
Set<String> multiApps = new TreeSet<>();
multiApps.add(APP_NAME1);
multiApps.add(APP_NAME2);
MockServiceInstancesChangedListener multiAppsInstanceListener =
spy(new MockServiceInstancesChangedListener(multiApps, serviceDiscovery));
doNothing().when(multiAppsInstanceListener).onEvent(any());
List<URL> urls = new ArrayList<>();
urls.add(URL.valueOf("dubbo://127.0.0.1:20880/TestService"));
doReturn(urls).when(multiAppsInstanceListener).getAddresses(any(), any());
when(serviceDiscovery.createListener(multiApps)).thenReturn(multiAppsInstanceListener);
when(serviceDiscovery.getInstances(APP_NAME1)).thenReturn(instanceList1);
when(serviceDiscovery.getInstances(APP_NAME2)).thenReturn(instanceList2);
serviceDiscoveryRegistry.subscribeURLs(url, testServiceListener, multiApps);
assertEquals(2, serviceDiscoveryRegistry.getServiceListeners().size());
assertEquals(
instanceListener, serviceDiscoveryRegistry.getServiceListeners().get(toStringKeys(singleApp)));
assertEquals(
multiAppsInstanceListener,
serviceDiscoveryRegistry.getServiceListeners().get(toStringKeys(multiApps)));
verify(testServiceListener, times(1)).addServiceListener(multiAppsInstanceListener);
verify(multiAppsInstanceListener, times(2)).onEvent(any());
verify(multiAppsInstanceListener, times(1)).addListenerAndNotify(any(), eq(testServiceListener));
verify(serviceDiscovery, times(1)).addServiceInstancesChangedListener(multiAppsInstanceListener);
ArgumentCaptor<List<URL>> captor = ArgumentCaptor.forClass(List.class);
verify(testServiceListener).notify(captor.capture());
assertEquals(urls, captor.getValue());
// different interface mapping to the same apps
NotifyListener testServiceListener2 = mock(NotifyListener.class);
URL url2 = URL.valueOf("tri://127.0.0.1/TestService2?interface=TestService2&check=false&protocol=tri");
when(testServiceListener2.getConsumerUrl()).thenReturn(url2);
serviceDiscoveryRegistry.subscribeURLs(url2, testServiceListener2, multiApps);
// check instance listeners not changed, methods not called
assertEquals(2, serviceDiscoveryRegistry.getServiceListeners().size());
assertEquals(
multiAppsInstanceListener,
serviceDiscoveryRegistry.getServiceListeners().get(toStringKeys(multiApps)));
verify(multiAppsInstanceListener, times(1)).addListenerAndNotify(any(), eq(testServiceListener));
// still called once, not executed this time
verify(serviceDiscovery, times(2)).addServiceInstancesChangedListener(multiAppsInstanceListener);
// check different protocol
Map<String, Set<ServiceInstancesChangedListener.NotifyListenerWithKey>> serviceListeners =
multiAppsInstanceListener.getServiceListeners();
assertEquals(2, serviceListeners.size());
assertEquals(1, serviceListeners.get(url.getServiceKey()).size());
assertEquals(1, serviceListeners.get(url2.getServiceKey()).size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(
url2.getServiceInterface(), url2.getVersion(), url2.getGroup(), url2.getParameter(PROTOCOL_KEY, DUBBO));
assertTrue(serviceListeners
.get(url2.getServiceKey())
.contains(new ServiceInstancesChangedListener.NotifyListenerWithKey(
protocolServiceKey, testServiceListener2)));
}
/**
* repeat of {@link this#testSubscribeURLs()} with multi threads
*/
@Test
void testConcurrencySubscribe() {
// TODO
}
@Test
void testUnsubscribe() {
// do subscribe to prepare for unsubscribe verification
Set<String> multiApps = new TreeSet<>();
multiApps.add(APP_NAME1);
multiApps.add(APP_NAME2);
NotifyListener testServiceListener2 = mock(NotifyListener.class);
URL url2 = URL.valueOf("consumer://127.0.0.1/TestService2?interface=TestService1&check=false&protocol=tri");
when(testServiceListener2.getConsumerUrl()).thenReturn(url2);
serviceDiscoveryRegistry.subscribeURLs(url, testServiceListener, multiApps);
serviceDiscoveryRegistry.subscribeURLs(url2, testServiceListener2, multiApps);
assertEquals(1, serviceDiscoveryRegistry.getServiceListeners().size());
// do unsubscribe
when(mapping.getMapping(url2)).thenReturn(multiApps);
serviceDiscoveryRegistry.doUnsubscribe(url2, testServiceListener2);
assertEquals(1, serviceDiscoveryRegistry.getServiceListeners().size());
ServiceInstancesChangedListener instancesChangedListener = serviceDiscoveryRegistry
.getServiceListeners()
.entrySet()
.iterator()
.next()
.getValue();
assertTrue(instancesChangedListener.hasListeners());
when(mapping.getMapping(url)).thenReturn(multiApps);
serviceDiscoveryRegistry.doUnsubscribe(url, testServiceListener);
assertEquals(0, serviceDiscoveryRegistry.getServiceListeners().size());
assertFalse(instancesChangedListener.hasListeners());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactoryTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactoryTest.java | /*
* 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.config.ApplicationConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link AbstractServiceDiscoveryFactory}
*/
class AbstractServiceDiscoveryFactoryTest {
@Test
void testGetServiceDiscoveryWithCache() {
ApplicationModel.defaultModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("AbstractServiceDiscoveryFactoryTest"));
URL url = URL.valueOf("mock://127.0.0.1:8888");
ServiceDiscoveryFactory factory = ServiceDiscoveryFactory.getExtension(url);
ServiceDiscovery serviceDiscovery1 = factory.getServiceDiscovery(url);
ServiceDiscovery serviceDiscovery2 = factory.getServiceDiscovery(url);
Assertions.assertEquals(serviceDiscovery1, serviceDiscovery2);
url = url.setPath("test");
ServiceDiscovery serviceDiscovery3 = factory.getServiceDiscovery(url);
Assertions.assertNotEquals(serviceDiscovery2, serviceDiscovery3);
AbstractServiceDiscoveryFactory abstractServiceDiscoveryFactory = (AbstractServiceDiscoveryFactory) factory;
List<ServiceDiscovery> allServiceDiscoveries = abstractServiceDiscoveryFactory.getAllServiceDiscoveries();
Assertions.assertEquals(2, allServiceDiscoveries.size());
Assertions.assertTrue(allServiceDiscoveries.contains(serviceDiscovery1));
Assertions.assertTrue(allServiceDiscoveries.contains(serviceDiscovery3));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java | /*
* 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.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_STORAGE_TYPE_PROPERTY_NAME;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getEndpoint;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.setEndpoints;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
/**
* {@link DefaultServiceInstance} Test
*
* @since 2.7.5
*/
class DefaultServiceInstanceTest {
public DefaultServiceInstance instance;
public static DefaultServiceInstance createInstance() {
DefaultServiceInstance instance =
new DefaultServiceInstance("A", "127.0.0.1", 20880, ApplicationModel.defaultModel());
Map<String, String> metadata = instance.getMetadata();
metadata.put(METADATA_STORAGE_TYPE_PROPERTY_NAME, "remote");
metadata.put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, "111");
metadata.put("site", "dubbo");
Map<String, Integer> protocolPorts = new HashMap<>();
protocolPorts.put("rest", 8080);
protocolPorts.put("dubbo", 20880);
setEndpoints(instance, protocolPorts);
return instance;
}
@BeforeEach
public void init() {
instance = createInstance();
}
@Test
void testSetAndGetValues() {
instance.setEnabled(false);
instance.setHealthy(false);
assertEquals("A", instance.getServiceName());
assertEquals("127.0.0.1", instance.getHost());
assertEquals(20880, instance.getPort());
assertFalse(instance.isEnabled());
assertFalse(instance.isHealthy());
assertFalse(instance.getMetadata().isEmpty());
}
@Test
void testInstanceOperations() {
// test multiple protocols
assertEquals(2, instance.getEndpoints().size());
DefaultServiceInstance.Endpoint endpoint = getEndpoint(instance, "rest");
DefaultServiceInstance copyInstance = instance.copyFrom(endpoint);
assertEquals(8080, endpoint.getPort());
assertEquals("rest", endpoint.getProtocol());
assertEquals(endpoint.getPort(), copyInstance.getPort());
// test all params
Map<String, String> allParams = instance.getAllParams();
assertEquals(instance.getMetadata().size(), allParams.size());
assertEquals("dubbo", allParams.get("site"));
instance.putExtendParam("key", "value");
Map<String, String> allParams2 = instance.getAllParams();
assertNotSame(allParams, allParams2);
assertEquals(instance.getMetadata().size() + instance.getExtendParams().size(), allParams2.size());
assertEquals("value", allParams2.get("key"));
// test equals
DefaultServiceInstance instance2 =
new DefaultServiceInstance("A", "127.0.0.1", 20880, ApplicationModel.defaultModel());
instance2.setMetadata(new HashMap<>(instance.getMetadata()));
instance2.getMetadata().put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, "222");
// assert instances with different revision and extend params are equal
assertEquals(instance, instance2);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/support/MockServiceDiscovery.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/support/MockServiceDiscovery.java | /*
* 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.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.AbstractServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.metadata.store.MetaCacheManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class MockServiceDiscovery extends AbstractServiceDiscovery {
public MockServiceDiscovery(ApplicationModel applicationModel, URL registryURL) {
super(applicationModel, registryURL);
}
public MockServiceDiscovery(String serviceName, URL registryURL) {
super(serviceName, registryURL);
}
@Override
public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {}
@Override
public void doUnregister(ServiceInstance serviceInstance) {}
@Override
public void doDestroy() throws Exception {}
@Override
public Set<String> getServices() {
return null;
}
@Override
public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException {
return Collections.emptyList();
}
public MetaCacheManager getMetaCacheManager() {
return metaCacheManager;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/support/MockServiceDiscoveryFactory.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/support/MockServiceDiscoveryFactory.java | /*
* 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.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.AbstractServiceDiscoveryFactory;
import org.apache.dubbo.registry.client.ServiceDiscovery;
public class MockServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory {
@Override
protected ServiceDiscovery createDiscovery(URL registryURL) {
return new MockServiceDiscovery(applicationModel, registryURL);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilderTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilderTest.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilderTest.serviceInstance;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link StandardMetadataServiceURLBuilder} Test
*/
class StandardMetadataServiceURLBuilderTest {
@BeforeAll
public static void setUp() {
ApplicationConfig applicationConfig = new ApplicationConfig("demo");
applicationConfig.setMetadataServicePort(7001);
ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig);
}
@AfterAll
public static void clearUp() {
ApplicationModel.reset();
}
@Test
void testBuild() {
ExtensionLoader<MetadataServiceURLBuilder> loader =
ApplicationModel.defaultModel().getExtensionLoader(MetadataServiceURLBuilder.class);
MetadataServiceURLBuilder builder = loader.getExtension(StandardMetadataServiceURLBuilder.NAME);
// test generateUrlWithoutMetadata
List<URL> urls =
builder.build(new DefaultServiceInstance("test", "127.0.0.1", 8080, ApplicationModel.defaultModel()));
assertEquals(1, urls.size());
URL url = urls.get(0);
assertEquals("dubbo", url.getProtocol());
assertEquals("127.0.0.1", url.getHost());
assertEquals(7001, url.getPort());
assertEquals(MetadataService.class.getName(), url.getServiceInterface());
assertEquals("test", url.getGroup());
assertEquals("consumer", url.getSide());
assertEquals("1.0.0", url.getVersion());
// assertEquals(url.getParameters().get("getAndListenInstanceMetadata.1.callback"), "true");
assertEquals("false", url.getParameters().get("reconnect"));
assertEquals("5000", url.getParameters().get("timeout"));
assertEquals(ApplicationModel.defaultModel(), url.getApplicationModel());
// test generateWithMetadata
urls = builder.build(serviceInstance);
assertEquals(1, urls.size());
url = urls.get(0);
assertEquals("rest", url.getProtocol());
assertEquals("127.0.0.1", url.getHost());
assertEquals(20880, url.getPort());
assertEquals(MetadataService.class.getName(), url.getServiceInterface());
assertEquals("test", url.getGroup());
assertEquals("consumer", url.getSide());
assertEquals("1.0.0", url.getVersion());
assertEquals("dubbo-provider-demo", url.getApplication());
assertEquals("5000", url.getParameters().get("timeout"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMappingTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMappingTest.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.MetadataReportInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
class MetadataServiceNameMappingTest {
private MetadataServiceNameMapping mapping;
private URL url;
private ConfigManager configManager;
private MetadataReport metadataReport;
private ApplicationModel applicationModel;
private Map<String, MetadataReport> metadataReportList = new HashMap<>();
@BeforeEach
public void setUp() {
applicationModel = ApplicationModel.defaultModel();
configManager = mock(ConfigManager.class);
metadataReport = mock(MetadataReport.class);
metadataReportList.put("default", metadataReport);
mapping = new MetadataServiceNameMapping(applicationModel);
mapping.setApplicationModel(applicationModel);
url = URL.valueOf("dubbo://127.0.0.1:20880/TestService?version=1.0.0");
}
@AfterEach
public void teardown() {
applicationModel.destroy();
}
@Test
void testMap() {
ApplicationModel mockedApplicationModel = spy(applicationModel);
when(configManager.getMetadataConfigs()).thenReturn(Collections.emptyList());
Mockito.when(mockedApplicationModel.getApplicationConfigManager()).thenReturn(configManager);
Mockito.when(mockedApplicationModel.getCurrentConfig()).thenReturn(new ApplicationConfig("test"));
// metadata report config not found
mapping.setApplicationModel(mockedApplicationModel);
boolean result = mapping.map(url);
assertFalse(result);
when(configManager.getMetadataConfigs()).thenReturn(Arrays.asList(new MetadataReportConfig()));
MetadataReportInstance reportInstance = mock(MetadataReportInstance.class);
Mockito.when(reportInstance.getMetadataReports(true)).thenReturn(metadataReportList);
mapping.metadataReportInstance = reportInstance;
when(metadataReport.registerServiceAppMapping(any(), any(), any())).thenReturn(true);
// metadata report directly
result = mapping.map(url);
assertTrue(result);
// metadata report using cas and retry, succeeded after retried 10 times
when(metadataReport.registerServiceAppMapping(any(), any(), any())).thenReturn(false);
when(metadataReport.getConfigItem(any(), any())).thenReturn(new ConfigItem());
when(metadataReport.registerServiceAppMapping(any(), any(), any(), any()))
.thenAnswer(new Answer<Boolean>() {
private int counter = 0;
@Override
public Boolean answer(InvocationOnMock invocationOnMock) {
if (++counter == 10) {
return true;
}
return false;
}
});
assertTrue(mapping.map(url));
// metadata report using cas and retry, failed after 11 times retry
when(metadataReport.registerServiceAppMapping(any(), any(), any(), any()))
.thenReturn(false);
Exception exceptionExpected = null;
assertFalse(mapping.map(url));
}
/**
* This test currently doesn't make any sense
*/
@Test
void testGet() {
Set<String> set = new HashSet<>();
set.add("app1");
MetadataReportInstance reportInstance = mock(MetadataReportInstance.class);
Mockito.when(reportInstance.getMetadataReport(any())).thenReturn(metadataReport);
when(metadataReport.getServiceAppMapping(any(), any())).thenReturn(set);
mapping.metadataReportInstance = reportInstance;
Set<String> result = mapping.get(url);
assertEquals(set, result);
}
/**
* Same situation as testGet, so left empty.
*/
@Test
void testGetAndListen() {
// TODO
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizerTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizerTest.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* Test for https://github.com/apache/dubbo/issues/8698
*/
class ServiceInstanceHostPortCustomizerTest {
private static ServiceInstanceHostPortCustomizer serviceInstanceHostPortCustomizer;
@BeforeAll
public static void setUp() {
serviceInstanceHostPortCustomizer = new ServiceInstanceHostPortCustomizer();
}
@AfterAll
public static void clearUp() {
ApplicationModel.reset();
}
@Test
void customizePreferredProtocol() throws ExecutionException, InterruptedException {
ScopeBeanFactory beanFactory = mock(ScopeBeanFactory.class);
MetadataService metadataService = mock(MetadataService.class);
when(beanFactory.getBean(MetadataService.class)).thenReturn(metadataService);
ApplicationModel applicationModel = spy(ApplicationModel.defaultModel());
when(applicationModel.getBeanFactory()).thenReturn(beanFactory);
// test protocol set
ApplicationConfig applicationConfig = new ApplicationConfig("aa");
// when(applicationModel.getCurrentConfig()).thenReturn(applicationConfig);
doReturn(applicationConfig).when(applicationModel).getCurrentConfig();
DefaultServiceInstance serviceInstance1 =
new DefaultServiceInstance("without-preferredProtocol", applicationModel);
MetadataInfo metadataInfo = new MetadataInfo();
metadataInfo.addService(URL.valueOf("tri://127.1.1.1:50052/org.apache.dubbo.demo.GreetingService"));
serviceInstance1.setServiceMetadata(metadataInfo);
serviceInstanceHostPortCustomizer.customize(serviceInstance1, applicationModel);
Assertions.assertEquals("127.1.1.1", serviceInstance1.getHost());
Assertions.assertEquals(50052, serviceInstance1.getPort());
// pick the preferredProtocol
applicationConfig.setProtocol("tri");
metadataInfo.addService(URL.valueOf("dubbo://127.1.2.3:20889/org.apache.dubbo.demo.HelloService"));
serviceInstanceHostPortCustomizer.customize(serviceInstance1, applicationModel);
Assertions.assertEquals("127.1.1.1", serviceInstance1.getHost());
Assertions.assertEquals(50052, serviceInstance1.getPort());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizerTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizerTest.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.IOException;
import java.util.List;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.ENDPOINTS;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class ProtocolPortsMetadataCustomizerTest {
public DefaultServiceInstance instance;
private MetadataService mockedMetadataService;
private ApplicationModel mockedApplicationModel;
private ScopeBeanFactory mockedBeanFactory;
public static DefaultServiceInstance createInstance() {
return new DefaultServiceInstance("A", "127.0.0.1", 20880, ApplicationModel.defaultModel());
}
@AfterAll
public static void clearUp() {
ApplicationModel.reset();
}
@BeforeEach
public void init() {
instance = createInstance();
URL dubboUrl = URL.valueOf(
"dubbo://30.10.104.63:20880/org.apache.dubbo.demo.GreetingService?"
+ "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.demo.GreetingService&metadata-type=remote&methods=hello&pid=55805&release=&revision=1.0.0&service-name-mapping=true&side=provider&timeout=5000×tamp=1630229110058&version=1.0.0");
URL triURL = URL.valueOf(
"tri://30.10.104.63:50332/org.apache.dubbo.demo.GreetingService?"
+ "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.demo.GreetingService&metadata-type=remote&methods=hello&pid=55805&release=&revision=1.0.0&service-name-mapping=true&side=provider&timeout=5000×tamp=1630229110058&version=1.0.0");
MetadataInfo metadataInfo = new MetadataInfo();
metadataInfo.addService(dubboUrl);
metadataInfo.addService(triURL);
instance.setServiceMetadata(metadataInfo);
mockedMetadataService = Mockito.mock(MetadataService.class);
}
@AfterEach
public void tearDown() throws IOException {
Mockito.framework().clearInlineMocks();
}
@Test
void test() {
ProtocolPortsMetadataCustomizer customizer = new ProtocolPortsMetadataCustomizer();
customizer.customize(instance, ApplicationModel.defaultModel());
String endpoints = instance.getMetadata().get(ENDPOINTS);
assertNotNull(endpoints);
List<DefaultServiceInstance.Endpoint> endpointList =
JsonUtils.toJavaList(endpoints, DefaultServiceInstance.Endpoint.class);
assertEquals(2, endpointList.size());
MatcherAssert.assertThat(endpointList, hasItem(hasProperty("protocol", equalTo("dubbo"))));
MatcherAssert.assertThat(endpointList, hasItem(hasProperty("port", equalTo(20880))));
MatcherAssert.assertThat(endpointList, hasItem(hasProperty("protocol", equalTo("tri"))));
MatcherAssert.assertThat(endpointList, hasItem(hasProperty("port", equalTo(50332))));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilderTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilderTest.java | /*
* 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.metadata;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
/**
* {@link MetadataServiceURLBuilder} Test
*
* @since 2.7.5
*/
class MetadataServiceURLBuilderTest {
static ServiceInstance serviceInstance =
new DefaultServiceInstance("test", "127.0.0.1", 8080, ApplicationModel.defaultModel());
static {
serviceInstance
.getMetadata()
.put(
"dubbo.metadata-service.urls",
"[ \"dubbo://192.168.0.102:20881/com.alibaba.cloud.dubbo.service.DubboMetadataService?anyhost=true&application=spring-cloud-alibaba-dubbo-provider&bind.ip=192.168.0.102&bind.port=20881&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=spring-cloud-alibaba-dubbo-provider&interface=com.alibaba.cloud.dubbo.service.DubboMetadataService&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs&pid=17134&qos.enable=false®ister=true&release=2.7.3&revision=1.0.0&side=provider×tamp=1564826098503&version=1.0.0\" ]");
serviceInstance
.getMetadata()
.put(
"dubbo.metadata-service.url-params",
"{\"application\":\"dubbo-provider-demo\",\"protocol\":\"rest\",\"group\":\"dubbo-provider-demo\",\"version\":\"1.0.0\",\"timestamp\":\"1564845042651\",\"dubbo\":\"2.0.2\",\"host\":\"192.168.0.102\",\"port\":\"20880\"}");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizerTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizerTest.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
class ServiceInstanceMetadataCustomizerTest {
private static ServiceInstanceMetadataCustomizer serviceInstanceMetadataCustomizer;
@BeforeAll
public static void setUp() {
serviceInstanceMetadataCustomizer = new ServiceInstanceMetadataCustomizer();
}
@AfterAll
public static void clearUp() {
ApplicationModel.reset();
}
/**
* Only 'include' policy spicified in Customized Filter will take effect
*/
@Test
void testCustomizeWithIncludeFilters() {
ApplicationModel applicationModel = spy(ApplicationModel.defaultModel());
ApplicationConfig applicationConfig = new ApplicationConfig("aa");
doReturn(applicationConfig).when(applicationModel).getCurrentConfig();
DefaultServiceInstance serviceInstance1 =
new DefaultServiceInstance("ServiceInstanceMetadataCustomizerTest", applicationModel);
MetadataInfo metadataInfo = new MetadataInfo();
metadataInfo.addService(
URL.valueOf(
"tri://127.1.1.1:50052/org.apache.dubbo.demo.GreetingService?application=ServiceInstanceMetadataCustomizerTest&env=test&side=provider&group=test"));
serviceInstance1.setServiceMetadata(metadataInfo);
serviceInstanceMetadataCustomizer.customize(serviceInstance1, applicationModel);
Assertions.assertEquals(1, serviceInstance1.getMetadata().size());
Assertions.assertEquals("provider", serviceInstance1.getMetadata(SIDE_KEY));
Assertions.assertNull(serviceInstance1.getMetadata("env"));
Assertions.assertNull(serviceInstance1.getMetadata("application"));
}
/**
* Only 'exclude' policies specified in Exclude Filters will take effect
*/
@Test
void testCustomizeWithExcludeFilters() {
ApplicationModel applicationModel = spy(ApplicationModel.defaultModel());
ApplicationConfig applicationConfig = new ApplicationConfig("aa");
doReturn(applicationConfig).when(applicationModel).getCurrentConfig();
DefaultServiceInstance serviceInstance1 =
new DefaultServiceInstance("ServiceInstanceMetadataCustomizerTest", applicationModel);
MetadataInfo metadataInfo = new MetadataInfo();
metadataInfo.addService(
URL.valueOf(
"tri://127.1.1.1:50052/org.apache.dubbo.demo.GreetingService?application=ServiceInstanceMetadataCustomizerTest&env=test&side=provider&group=test¶ms-filter=-customized,-dubbo"));
serviceInstance1.setServiceMetadata(metadataInfo);
serviceInstanceMetadataCustomizer.customize(serviceInstance1, applicationModel);
Assertions.assertEquals(2, serviceInstance1.getMetadata().size());
Assertions.assertEquals("ServiceInstanceMetadataCustomizerTest", serviceInstance1.getMetadata("application"));
Assertions.assertEquals("test", serviceInstance1.getMetadata("env"));
Assertions.assertNull(serviceInstance1.getMetadata("side"));
Assertions.assertNull(serviceInstance1.getMetadata("group"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/SpringCloudMetadataServiceURLBuilderTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/SpringCloudMetadataServiceURLBuilderTest.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilderTest.serviceInstance;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link SpringCloudMetadataServiceURLBuilder} Test
*
* @since 2.7.5
*/
class SpringCloudMetadataServiceURLBuilderTest {
private SpringCloudMetadataServiceURLBuilder builder = new SpringCloudMetadataServiceURLBuilder();
@Test
void testBuild() {
List<URL> urls =
builder.build(new DefaultServiceInstance("127.0.0.1", "test", 8080, ApplicationModel.defaultModel()));
assertEquals(0, urls.size());
urls = builder.build(serviceInstance);
assertEquals(1, urls.size());
URL url = urls.get(0);
assertEquals("192.168.0.102", url.getHost());
assertEquals(20881, url.getPort());
assertEquals("com.alibaba.cloud.dubbo.service.DubboMetadataService", url.getServiceInterface());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/MetaCacheManagerTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/MetaCacheManagerTest.java | /*
* 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.metadata.store;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class MetaCacheManagerTest {
@BeforeEach
public void setup() throws URISyntaxException {
String directory = getDirectoryOfClassPath();
SystemPropertyConfigUtils.setSystemProperty(CommonConstants.DubboProperty.DUBBO_META_CACHE_FILEPATH, directory);
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_META_CACHE_FILENAME, "test-metadata.dubbo.cache");
}
@AfterEach
public void clear() throws URISyntaxException {
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_META_CACHE_FILEPATH);
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_META_CACHE_FILENAME);
}
@Test
void testCache() {
// ScheduledExecutorService cacheRefreshExecutor = Executors.newSingleThreadScheduledExecutor(new
// NamedThreadFactory("Dubbo-cache-refresh"));
// ExecutorRepository executorRepository = Mockito.mock(ExecutorRepository.class);
// when(executorRepository.getCacheRefreshExecutor()).thenReturn(cacheRefreshExecutor);
// ExtensionAccessor extensionAccessor = Mockito.mock(ExtensionAccessor.class);
// when(extensionAccessor.getDefaultExtension(ExecutorRepository.class)).thenReturn(executorRepository);
MetaCacheManager cacheManager = new MetaCacheManager();
try {
// cacheManager.setExtensionAccessor(extensionAccessor);
MetadataInfo metadataInfo = cacheManager.get("1");
assertNull(metadataInfo);
metadataInfo = cacheManager.get("2");
assertNull(metadataInfo);
metadataInfo = cacheManager.get("065787862412c2cc0a1b9577bc194c9a");
assertNotNull(metadataInfo);
assertEquals("demo", metadataInfo.getApp());
Map<String, MetadataInfo> newMetadatas = new HashMap<>();
MetadataInfo metadataInfo2 = JsonUtils.toJavaObject(
"{\"app\":\"demo2\",\"services\":{\"greeting/org.apache.dubbo.registry.service.DemoService2:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService2\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService2\",\"params\":{\"application\":\"demo-provider2\",\"sayHello.timeout\":\"7000\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}},\"greeting/org.apache.dubbo.registry.service.DemoService:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService\",\"params\":{\"application\":\"demo-provider2\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}}}}\n",
MetadataInfo.class);
assertNotEquals("2", metadataInfo2.calRevision());
newMetadatas.put("2", metadataInfo2);
MetadataInfo metadataInfo3 = JsonUtils.toJavaObject(
"{\"app\":\"demo3\",\"services\":{\"greeting/org.apache.dubbo.registry.service.DemoService3:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService3\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService3\",\"params\":{\"application\":\"demo-provider3\",\"sayHello.timeout\":\"7000\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}},\"greeting/org.apache.dubbo.registry.service.DemoService:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService\",\"params\":{\"application\":\"demo-provider3\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}}}}\n",
MetadataInfo.class);
assertEquals("84f10ebf1226b496c9ff102f311918e4", metadataInfo3.calRevision());
newMetadatas.put("84f10ebf1226b496c9ff102f311918e4", metadataInfo3);
cacheManager.update(newMetadatas);
metadataInfo = cacheManager.get("1");
assertNull(metadataInfo);
metadataInfo = cacheManager.get("065787862412c2cc0a1b9577bc194c9a");
assertNotNull(metadataInfo);
assertEquals("demo", metadataInfo.getApp());
metadataInfo = cacheManager.get("2");
assertNull(metadataInfo);
metadataInfo = cacheManager.get("84f10ebf1226b496c9ff102f311918e4");
assertNotNull(metadataInfo);
assertEquals("demo3", metadataInfo.getApp());
assertTrue(metadataInfo
.getServices()
.containsKey("greeting/org.apache.dubbo.registry.service.DemoService3:1.0.0:dubbo"));
} finally {
cacheManager.destroy();
}
}
@Test
void testCacheDump() {
System.setProperty("dubbo.meta.cache.fileName", "not-exist.dubbo.cache");
MetadataInfo metadataInfo3 = JsonUtils.toJavaObject(
"{\"app\":\"demo3\",\"services\":{\"greeting/org.apache.dubbo.registry.service.DemoService2:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService2\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService2\",\"params\":{\"application\":\"demo-provider2\",\"sayHello.timeout\":\"7000\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}},\"greeting/org.apache.dubbo.registry.service.DemoService:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService\",\"params\":{\"application\":\"demo-provider2\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}}}}\n",
MetadataInfo.class);
MetaCacheManager cacheManager = new MetaCacheManager();
try {
assertEquals("97370ff779b6b6ebb7012bae61710de2", metadataInfo3.calRevision());
cacheManager.put("97370ff779b6b6ebb7012bae61710de2", metadataInfo3);
try {
MetaCacheManager.CacheRefreshTask<MetadataInfo> task = new MetaCacheManager.CacheRefreshTask<>(
cacheManager.getCacheStore(), cacheManager.getCache(), cacheManager, 0);
task.run();
} catch (Exception e) {
fail();
} finally {
cacheManager.destroy();
}
MetaCacheManager newCacheManager = null;
try {
newCacheManager = new MetaCacheManager();
MetadataInfo metadataInfo = newCacheManager.get("97370ff779b6b6ebb7012bae61710de2");
assertNotNull(metadataInfo);
assertEquals("demo3", metadataInfo.getApp());
} finally {
newCacheManager.destroy();
}
} finally {
cacheManager.destroy();
}
}
private String getDirectoryOfClassPath() throws URISyntaxException {
URL resource = this.getClass().getResource("/log4j2-test.xml");
String path = Paths.get(resource.toURI()).toFile().getAbsolutePath();
int index = path.indexOf("log4j2-test.xml");
String directoryPath = path.substring(0, index);
return directoryPath;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter.java | /*
* 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.metadata.store;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metadata.MetadataParamsFilter;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
@Activate
public class ExcludedParamsFilter implements MetadataParamsFilter {
@Override
public String[] serviceParamsIncluded() {
return new String[0];
}
@Override
public String[] serviceParamsExcluded() {
return new String[0];
}
/**
* Not included in this test
*/
@Override
public String[] instanceParamsIncluded() {
return new String[0];
}
@Override
public String[] instanceParamsExcluded() {
return new String[] {SIDE_KEY};
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/CustomizedParamsFilter.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/CustomizedParamsFilter.java | /*
* 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.metadata.store;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metadata.MetadataParamsFilter;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
@Activate
public class CustomizedParamsFilter implements MetadataParamsFilter {
@Override
public String[] serviceParamsIncluded() {
return new String[] {APPLICATION_KEY, TIMEOUT_KEY, GROUP_KEY, VERSION_KEY};
}
@Override
public String[] serviceParamsExcluded() {
return new String[0];
}
/**
* Not included in this test
*/
@Override
public String[] instanceParamsIncluded() {
return new String[] {SIDE_KEY};
}
@Override
public String[] instanceParamsExcluded() {
return new String[0];
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter2.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter2.java | /*
* 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.metadata.store;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metadata.MetadataParamsFilter;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
@Activate
public class ExcludedParamsFilter2 implements MetadataParamsFilter {
@Override
public String[] serviceParamsIncluded() {
return new String[0];
}
@Override
public String[] serviceParamsExcluded() {
return new String[0];
}
/**
* Not included in this test
*/
@Override
public String[] instanceParamsIncluded() {
return new String[0];
}
@Override
public String[] instanceParamsExcluded() {
return new String[] {GROUP_KEY, "params-filter"};
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerWithoutEmptyProtectTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerWithoutEmptyProtectTest.java | /*
* 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.event.listener;
import org.apache.dubbo.common.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.LRUCache;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.InstanceAddressURL;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.metadata.store.MetaCacheManager;
import org.apache.dubbo.registry.client.support.MockServiceDiscovery;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.reflect.Field;
import java.util.ArrayList;
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 org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY;
import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty;
import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
/**
* {@link ServiceInstancesChangedListener} Test
*
* @since 2.7.5
*/
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ServiceInstancesChangedListenerWithoutEmptyProtectTest {
static List<ServiceInstance> app1Instances;
static List<ServiceInstance> app2Instances;
static List<ServiceInstance> app1FailedInstances;
static List<ServiceInstance> app1FailedInstances2;
static List<ServiceInstance> app1InstancesWithNoRevision;
static List<ServiceInstance> app1InstancesMultipleProtocols;
static String metadata_111 = "{\"app\":\"app1\",\"revision\":\"111\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app1\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
static String metadata_222 = "{\"app\":\"app2\",\"revision\":\"222\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}},"
+ "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
static String metadata_333 = "{\"app\":\"app2\",\"revision\":\"333\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}},"
+ "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}},"
+ "\"org.apache.dubbo.demo.DemoService3:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService3\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService3\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService3\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
// failed
static String metadata_444 = "{\"app\":\"app1\",\"revision\":\"444\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
// only triple protocol enabled
static String metadata_555_triple = "{\"app\":\"app1\",\"revision\":\"555\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"tri\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
static String service1 = "org.apache.dubbo.demo.DemoService";
static String service2 = "org.apache.dubbo.demo.DemoService2";
static String service3 = "org.apache.dubbo.demo.DemoService3";
static URL consumerURL = URL.valueOf(
"dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo®istry_cluster=default");
static URL consumerURL2 = URL.valueOf(
"dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService2?interface=org.apache.dubbo.demo.DemoService2&protocol=dubbo®istry_cluster=default");
static URL consumerURL3 = URL.valueOf(
"dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService3?interface=org.apache.dubbo.demo.DemoService3&protocol=dubbo®istry_cluster=default");
static URL multipleProtocolsConsumerURL = URL.valueOf(
"dubbo,tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo,tri®istry_cluster=default");
static URL noProtocolConsumerURL = URL.valueOf(
"consumer://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService®istry_cluster=default");
static URL singleProtocolsConsumerURL = URL.valueOf(
"tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=tri®istry_cluster=default");
static URL registryURL = URL.valueOf("dubbo://127.0.0.1:2181/org.apache.dubbo.demo.RegistryService");
static MetadataInfo metadataInfo_111;
static MetadataInfo metadataInfo_222;
static MetadataInfo metadataInfo_333;
static MetadataInfo metadataInfo_444;
static MetadataInfo metadataInfo_555_tri;
static MetadataService metadataService;
static ServiceDiscovery serviceDiscovery;
static ServiceInstancesChangedListener listener = null;
@BeforeAll
public static void setUp() {
metadataService = Mockito.mock(MetadataService.class);
List<Object> urlsSameRevision = new ArrayList<>();
urlsSameRevision.add("127.0.0.1:20880?revision=111");
urlsSameRevision.add("127.0.0.2:20880?revision=111");
urlsSameRevision.add("127.0.0.3:20880?revision=111");
List<Object> urlsDifferentRevision = new ArrayList<>();
urlsDifferentRevision.add("30.10.0.1:20880?revision=222");
urlsDifferentRevision.add("30.10.0.2:20880?revision=222");
urlsDifferentRevision.add("30.10.0.3:20880?revision=333");
urlsDifferentRevision.add("30.10.0.4:20880?revision=333");
List<Object> urlsFailedRevision = new ArrayList<>();
urlsFailedRevision.add("30.10.0.5:20880?revision=222");
urlsFailedRevision.add("30.10.0.6:20880?revision=222");
urlsFailedRevision.add("30.10.0.7:20880?revision=444"); // revision will fail
urlsFailedRevision.add("30.10.0.8:20880?revision=444"); // revision will fail
List<Object> urlsFailedRevision2 = new ArrayList<>();
urlsFailedRevision2.add("30.10.0.1:20880?revision=222");
urlsFailedRevision2.add("30.10.0.2:20880?revision=222");
List<Object> urlsWithoutRevision = new ArrayList<>();
urlsWithoutRevision.add("30.10.0.1:20880");
List<Object> urlsMultipleProtocols = new ArrayList<>();
urlsMultipleProtocols.add("30.10.0.1:20880?revision=555"); // triple
urlsMultipleProtocols.addAll(urlsSameRevision); // dubbo
app1Instances = buildInstances(urlsSameRevision);
app2Instances = buildInstances(urlsDifferentRevision);
app1FailedInstances = buildInstances(urlsFailedRevision);
app1FailedInstances2 = buildInstances(urlsFailedRevision2);
app1InstancesWithNoRevision = buildInstances(urlsWithoutRevision);
app1InstancesMultipleProtocols = buildInstances(urlsMultipleProtocols);
metadataInfo_111 = JsonUtils.toJavaObject(metadata_111, MetadataInfo.class);
metadataInfo_222 = JsonUtils.toJavaObject(metadata_222, MetadataInfo.class);
metadataInfo_333 = JsonUtils.toJavaObject(metadata_333, MetadataInfo.class);
metadataInfo_444 = JsonUtils.toJavaObject(metadata_444, MetadataInfo.class);
metadataInfo_555_tri = JsonUtils.toJavaObject(metadata_555_triple, MetadataInfo.class);
serviceDiscovery = Mockito.mock(ServiceDiscovery.class);
when(serviceDiscovery.getUrl()).thenReturn(registryURL);
when(serviceDiscovery.getRemoteMetadata(eq("111"), anyList())).thenReturn(metadataInfo_111);
when(serviceDiscovery.getRemoteMetadata(eq("222"), anyList())).thenReturn(metadataInfo_222);
when(serviceDiscovery.getRemoteMetadata(eq("333"), anyList())).thenReturn(metadataInfo_333);
when(serviceDiscovery.getRemoteMetadata(eq("444"), anyList())).thenReturn(MetadataInfo.EMPTY);
when(serviceDiscovery.getRemoteMetadata(eq("555"), anyList())).thenReturn(metadataInfo_555_tri);
}
@BeforeEach
public void init() {
// Because all tests use the same ServiceDiscovery, the previous metadataCache should be cleared before next
// unit test
// to avoid contaminating next unit test.
clearMetadataCache();
}
@AfterEach
public void tearDown() throws Exception {
if (listener != null) {
listener.destroy();
listener = null;
}
}
@AfterAll
public static void destroy() throws Exception {
serviceDiscovery.destroy();
}
// 正常场景。单应用app1 通知地址基本流程,只做instance-metadata关联,没有metadata内容的解析
@Test
@Order(1)
public void testInstanceNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
}
// 正常场景。单应用app1,进一步检查 metadata service 是否正确映射
@Test
@Order(2)
public void testInstanceNotificationAndMetadataParse() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify instance change
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
assertThat(serviceUrls, Matchers.hasItem(Matchers.hasProperty("instance", Matchers.notNullValue())));
assertThat(serviceUrls, Matchers.hasItem(Matchers.hasProperty("metadataInfo", Matchers.notNullValue())));
}
// 正常场景。多应用,app1 app2 分别通知地址
@Test
@Order(3)
public void testMultipleAppNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// check
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(2, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
Assertions.assertEquals(4, allInstances.get("app2").size());
ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey3 = new ProtocolServiceKey(service3, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey1, consumerURL);
Assertions.assertEquals(7, serviceUrls.size());
List<URL> serviceUrls2 = listener.getAddresses(protocolServiceKey2, consumerURL);
Assertions.assertEquals(4, serviceUrls2.size());
assertTrue(serviceUrls2.get(0).getIp().contains("30.10."));
List<URL> serviceUrls3 = listener.getAddresses(protocolServiceKey3, consumerURL);
Assertions.assertEquals(2, serviceUrls3.size());
assertTrue(serviceUrls3.get(0).getIp().contains("30.10."));
}
// 正常场景。多应用,app1 app2,空地址通知(边界条件)能否解析出正确的空地址列表
@Test
@Order(4)
public void testMultipleAppEmptyNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// empty notification
ServiceInstancesChangedEvent app1_event_again =
new ServiceInstancesChangedEvent("app1", Collections.EMPTY_LIST);
listener.onEvent(app1_event_again);
// check app1 cleared
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(2, allInstances.size());
Assertions.assertEquals(0, allInstances.get("app1").size());
Assertions.assertEquals(4, allInstances.get("app2").size());
ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey3 = new ProtocolServiceKey(service3, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey1, consumerURL);
Assertions.assertEquals(4, serviceUrls.size());
assertTrue(serviceUrls.get(0).getIp().contains("30.10."));
List<URL> serviceUrls2 = listener.getAddresses(protocolServiceKey2, consumerURL);
Assertions.assertEquals(4, serviceUrls2.size());
assertTrue(serviceUrls2.get(0).getIp().contains("30.10."));
List<URL> serviceUrls3 = listener.getAddresses(protocolServiceKey3, consumerURL);
Assertions.assertEquals(2, serviceUrls3.size());
assertTrue(serviceUrls3.get(0).getIp().contains("30.10."));
// app2 empty notification
ServiceInstancesChangedEvent app2_event_again =
new ServiceInstancesChangedEvent("app2", Collections.EMPTY_LIST);
listener.onEvent(app2_event_again);
// check app2 cleared
Map<String, List<ServiceInstance>> allInstances_app2 = listener.getAllInstances();
Assertions.assertEquals(2, allInstances_app2.size());
Assertions.assertEquals(0, allInstances_app2.get("app1").size());
Assertions.assertEquals(0, allInstances_app2.get("app2").size());
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey1, consumerURL)));
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey2, consumerURL)));
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey3, consumerURL)));
}
// 正常场景。检查instance listener -> service listener(Directory)地址推送流程
@Test
@Order(5)
public void testServiceListenerNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
NotifyListener demoServiceListener = Mockito.mock(NotifyListener.class);
when(demoServiceListener.getConsumerUrl()).thenReturn(consumerURL);
NotifyListener demoService2Listener = Mockito.mock(NotifyListener.class);
when(demoService2Listener.getConsumerUrl()).thenReturn(consumerURL2);
listener.addListenerAndNotify(consumerURL, demoServiceListener);
listener.addListenerAndNotify(consumerURL2, demoService2Listener);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// check
ArgumentCaptor<List<URL>> captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener, Mockito.times(1)).notify(captor.capture());
List<URL> notifiedUrls = captor.getValue();
Assertions.assertEquals(3, notifiedUrls.size());
ArgumentCaptor<List<URL>> captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener, Mockito.times(1)).notify(captor2.capture());
List<URL> notifiedUrls2 = captor2.getValue();
Assertions.assertEquals(1, notifiedUrls2.size());
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// check
ArgumentCaptor<List<URL>> app2_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener, Mockito.times(2)).notify(app2_captor.capture());
List<URL> app2_notifiedUrls = app2_captor.getValue();
Assertions.assertEquals(7, app2_notifiedUrls.size());
ArgumentCaptor<List<URL>> app2_captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener, Mockito.times(2)).notify(app2_captor2.capture());
List<URL> app2_notifiedUrls2 = app2_captor2.getValue();
Assertions.assertEquals(4, app2_notifiedUrls2.size());
// test service listener still get notified when added after instance notification.
NotifyListener demoService3Listener = Mockito.mock(NotifyListener.class);
when(demoService3Listener.getConsumerUrl()).thenReturn(consumerURL3);
listener.addListenerAndNotify(consumerURL3, demoService3Listener);
Mockito.verify(demoService3Listener, Mockito.times(1)).notify(Mockito.anyList());
}
@Test
@Order(6)
public void testMultiServiceListenerNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
NotifyListener demoServiceListener1 = Mockito.mock(NotifyListener.class);
when(demoServiceListener1.getConsumerUrl()).thenReturn(consumerURL);
NotifyListener demoServiceListener2 = Mockito.mock(NotifyListener.class);
when(demoServiceListener2.getConsumerUrl()).thenReturn(consumerURL);
NotifyListener demoService2Listener1 = Mockito.mock(NotifyListener.class);
when(demoService2Listener1.getConsumerUrl()).thenReturn(consumerURL2);
NotifyListener demoService2Listener2 = Mockito.mock(NotifyListener.class);
when(demoService2Listener2.getConsumerUrl()).thenReturn(consumerURL2);
listener.addListenerAndNotify(consumerURL, demoServiceListener1);
listener.addListenerAndNotify(consumerURL, demoServiceListener2);
listener.addListenerAndNotify(consumerURL2, demoService2Listener1);
listener.addListenerAndNotify(consumerURL2, demoService2Listener2);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// check
ArgumentCaptor<List<URL>> captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener1, Mockito.times(1)).notify(captor.capture());
List<URL> notifiedUrls = captor.getValue();
Assertions.assertEquals(3, notifiedUrls.size());
ArgumentCaptor<List<URL>> captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener1, Mockito.times(1)).notify(captor2.capture());
List<URL> notifiedUrls2 = captor2.getValue();
Assertions.assertEquals(1, notifiedUrls2.size());
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// check
ArgumentCaptor<List<URL>> app2_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener1, Mockito.times(2)).notify(app2_captor.capture());
List<URL> app2_notifiedUrls = app2_captor.getValue();
Assertions.assertEquals(7, app2_notifiedUrls.size());
ArgumentCaptor<List<URL>> app2_captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener1, Mockito.times(2)).notify(app2_captor2.capture());
List<URL> app2_notifiedUrls2 = app2_captor2.getValue();
Assertions.assertEquals(4, app2_notifiedUrls2.size());
// test service listener still get notified when added after instance notification.
NotifyListener demoService3Listener = Mockito.mock(NotifyListener.class);
when(demoService3Listener.getConsumerUrl()).thenReturn(consumerURL3);
listener.addListenerAndNotify(consumerURL3, demoService3Listener);
Mockito.verify(demoService3Listener, Mockito.times(1)).notify(Mockito.anyList());
}
/**
* Test subscribe multiple protocols
*/
@Test
@Order(7)
public void testSubscribeMultipleProtocols() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// no protocol specified, consume all instances
NotifyListener demoServiceListener1 = Mockito.mock(NotifyListener.class);
when(demoServiceListener1.getConsumerUrl()).thenReturn(noProtocolConsumerURL);
listener.addListenerAndNotify(noProtocolConsumerURL, demoServiceListener1);
// multiple protocols specified
NotifyListener demoServiceListener2 = Mockito.mock(NotifyListener.class);
when(demoServiceListener2.getConsumerUrl()).thenReturn(multipleProtocolsConsumerURL);
listener.addListenerAndNotify(multipleProtocolsConsumerURL, demoServiceListener2);
// one protocol specified
NotifyListener demoServiceListener3 = Mockito.mock(NotifyListener.class);
when(demoServiceListener3.getConsumerUrl()).thenReturn(singleProtocolsConsumerURL);
listener.addListenerAndNotify(singleProtocolsConsumerURL, demoServiceListener3);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event =
new ServiceInstancesChangedEvent("app1", app1InstancesMultipleProtocols);
listener.onEvent(app1_event);
// check instances expose framework supported default protocols(currently dubbo, triple and rest) are notified
ArgumentCaptor<List<URL>> default_protocol_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener1, Mockito.times(1)).notify(default_protocol_captor.capture());
List<URL> default_protocol_notifiedUrls = default_protocol_captor.getValue();
Assertions.assertEquals(4, default_protocol_notifiedUrls.size());
// check instances expose protocols in consuming list(dubbo and triple) are notified
ArgumentCaptor<List<URL>> multi_protocols_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener2, Mockito.times(1)).notify(multi_protocols_captor.capture());
List<URL> multi_protocol_notifiedUrls = multi_protocols_captor.getValue();
Assertions.assertEquals(4, multi_protocol_notifiedUrls.size());
// check instances expose protocols in consuming list(only triple) are notified
ArgumentCaptor<List<URL>> single_protocols_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener3, Mockito.times(1)).notify(single_protocols_captor.capture());
List<URL> single_protocol_notifiedUrls = single_protocols_captor.getValue();
Assertions.assertEquals(1, single_protocol_notifiedUrls.size());
}
/**
* Test subscribe multiple groups
*/
@Test
@Order(8)
public void testSubscribeMultipleGroups() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify instance change
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, "", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, ",group1", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, "group1,", "dubbo");
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerTest.java | /*
* 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.event.listener;
import org.apache.dubbo.common.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.LRUCache;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.InstanceAddressURL;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.metadata.store.MetaCacheManager;
import org.apache.dubbo.registry.client.support.MockServiceDiscovery;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.reflect.Field;
import java.util.ArrayList;
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 org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY;
import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty;
import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
/**
* {@link ServiceInstancesChangedListener} Test
*
* @since 2.7.5
*/
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ServiceInstancesChangedListenerTest {
static List<ServiceInstance> app1Instances;
static List<ServiceInstance> app2Instances;
static List<ServiceInstance> app1FailedInstances;
static List<ServiceInstance> app1FailedInstances2;
static List<ServiceInstance> app1InstancesWithNoRevision;
static List<ServiceInstance> app1InstancesMultipleProtocols;
static String metadata_111 = "{\"app\":\"app1\",\"revision\":\"111\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app1\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
static String metadata_222 = "{\"app\":\"app2\",\"revision\":\"222\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}},"
+ "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
static String metadata_333 = "{\"app\":\"app2\",\"revision\":\"333\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}},"
+ "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}},"
+ "\"org.apache.dubbo.demo.DemoService3:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService3\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService3\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService3\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
// failed
static String metadata_444 = "{\"app\":\"app1\",\"revision\":\"444\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
// only triple protocol enabled
static String metadata_555_triple = "{\"app\":\"app1\",\"revision\":\"555\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"tri\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
static String service1 = "org.apache.dubbo.demo.DemoService";
static String service2 = "org.apache.dubbo.demo.DemoService2";
static String service3 = "org.apache.dubbo.demo.DemoService3";
static URL consumerURL = URL.valueOf(
"dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo®istry_cluster=default");
static URL consumerURL2 = URL.valueOf(
"dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService2?interface=org.apache.dubbo.demo.DemoService2&protocol=dubbo®istry_cluster=default");
static URL consumerURL3 = URL.valueOf(
"dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService3?interface=org.apache.dubbo.demo.DemoService3&protocol=dubbo®istry_cluster=default");
static URL multipleProtocolsConsumerURL = URL.valueOf(
"dubbo,tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo,tri®istry_cluster=default");
static URL noProtocolConsumerURL = URL.valueOf(
"consumer://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService®istry_cluster=default");
static URL singleProtocolsConsumerURL = URL.valueOf(
"tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=tri®istry_cluster=default");
static URL registryURL =
URL.valueOf("dubbo://127.0.0.1:2181/org.apache.dubbo.demo.RegistryService?enable-empty-protection=true");
static MetadataInfo metadataInfo_111;
static MetadataInfo metadataInfo_222;
static MetadataInfo metadataInfo_333;
static MetadataInfo metadataInfo_444;
static MetadataInfo metadataInfo_555_tri;
static MetadataService metadataService;
static ServiceDiscovery serviceDiscovery;
static ServiceInstancesChangedListener listener = null;
@BeforeAll
public static void setUp() {
metadataService = Mockito.mock(MetadataService.class);
List<Object> urlsSameRevision = new ArrayList<>();
urlsSameRevision.add("127.0.0.1:20880?revision=111");
urlsSameRevision.add("127.0.0.2:20880?revision=111");
urlsSameRevision.add("127.0.0.3:20880?revision=111");
List<Object> urlsDifferentRevision = new ArrayList<>();
urlsDifferentRevision.add("30.10.0.1:20880?revision=222");
urlsDifferentRevision.add("30.10.0.2:20880?revision=222");
urlsDifferentRevision.add("30.10.0.3:20880?revision=333");
urlsDifferentRevision.add("30.10.0.4:20880?revision=333");
List<Object> urlsFailedRevision = new ArrayList<>();
urlsFailedRevision.add("30.10.0.5:20880?revision=222");
urlsFailedRevision.add("30.10.0.6:20880?revision=222");
urlsFailedRevision.add("30.10.0.7:20880?revision=444"); // revision will fail
urlsFailedRevision.add("30.10.0.8:20880?revision=444"); // revision will fail
List<Object> urlsFailedRevision2 = new ArrayList<>();
urlsFailedRevision2.add("30.10.0.1:20880?revision=222");
urlsFailedRevision2.add("30.10.0.2:20880?revision=222");
List<Object> urlsWithoutRevision = new ArrayList<>();
urlsWithoutRevision.add("30.10.0.1:20880");
List<Object> urlsMultipleProtocols = new ArrayList<>();
urlsMultipleProtocols.add("30.10.0.1:20880?revision=555"); // triple
urlsMultipleProtocols.addAll(urlsSameRevision); // dubbo
app1Instances = buildInstances(urlsSameRevision);
app2Instances = buildInstances(urlsDifferentRevision);
app1FailedInstances = buildInstances(urlsFailedRevision);
app1FailedInstances2 = buildInstances(urlsFailedRevision2);
app1InstancesWithNoRevision = buildInstances(urlsWithoutRevision);
app1InstancesMultipleProtocols = buildInstances(urlsMultipleProtocols);
metadataInfo_111 = JsonUtils.toJavaObject(metadata_111, MetadataInfo.class);
metadataInfo_222 = JsonUtils.toJavaObject(metadata_222, MetadataInfo.class);
metadataInfo_333 = JsonUtils.toJavaObject(metadata_333, MetadataInfo.class);
metadataInfo_444 = JsonUtils.toJavaObject(metadata_444, MetadataInfo.class);
metadataInfo_555_tri = JsonUtils.toJavaObject(metadata_555_triple, MetadataInfo.class);
serviceDiscovery = Mockito.mock(ServiceDiscovery.class);
when(serviceDiscovery.getUrl()).thenReturn(registryURL);
when(serviceDiscovery.getRemoteMetadata(eq("111"), anyList())).thenReturn(metadataInfo_111);
when(serviceDiscovery.getRemoteMetadata(eq("222"), anyList())).thenReturn(metadataInfo_222);
when(serviceDiscovery.getRemoteMetadata(eq("333"), anyList())).thenReturn(metadataInfo_333);
when(serviceDiscovery.getRemoteMetadata(eq("444"), anyList())).thenReturn(MetadataInfo.EMPTY);
when(serviceDiscovery.getRemoteMetadata(eq("555"), anyList())).thenReturn(metadataInfo_555_tri);
}
@BeforeEach
public void init() {
// Because all tests use the same ServiceDiscovery, the previous metadataCache should be cleared before next
// unit test
// to avoid contaminating next unit test.
clearMetadataCache();
}
@AfterEach
public void tearDown() throws Exception {
if (listener != null) {
listener.destroy();
listener = null;
}
}
@AfterAll
public static void destroy() throws Exception {
serviceDiscovery.destroy();
}
// 正常场景。单应用app1 通知地址基本流程,只做instance-metadata关联,没有metadata内容的解析
@Test
@Order(1)
public void testInstanceNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
}
// 正常场景。单应用app1,进一步检查 metadata service 是否正确映射
@Test
@Order(2)
public void testInstanceNotificationAndMetadataParse() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify instance change
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
assertThat(serviceUrls, Matchers.hasItem(Matchers.hasProperty("instance", Matchers.notNullValue())));
assertThat(serviceUrls, Matchers.hasItem(Matchers.hasProperty("metadataInfo", Matchers.notNullValue())));
}
// 正常场景。多应用,app1 app2 分别通知地址
@Test
@Order(3)
public void testMultipleAppNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// check
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(2, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
Assertions.assertEquals(4, allInstances.get("app2").size());
ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey3 = new ProtocolServiceKey(service3, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey1, consumerURL);
Assertions.assertEquals(7, serviceUrls.size());
List<URL> serviceUrls2 = listener.getAddresses(protocolServiceKey2, consumerURL);
Assertions.assertEquals(4, serviceUrls2.size());
assertTrue(serviceUrls2.get(0).getIp().contains("30.10."));
List<URL> serviceUrls3 = listener.getAddresses(protocolServiceKey3, consumerURL);
Assertions.assertEquals(2, serviceUrls3.size());
assertTrue(serviceUrls3.get(0).getIp().contains("30.10."));
}
// 正常场景。多应用,app1 app2,空地址通知(边界条件)能否解析出正确的空地址列表
@Test
@Order(4)
public void testMultipleAppEmptyNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// empty notification
ServiceInstancesChangedEvent app1_event_again =
new ServiceInstancesChangedEvent("app1", Collections.EMPTY_LIST);
listener.onEvent(app1_event_again);
// check app1 cleared
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(2, allInstances.size());
Assertions.assertEquals(0, allInstances.get("app1").size());
Assertions.assertEquals(4, allInstances.get("app2").size());
ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey3 = new ProtocolServiceKey(service3, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey1, consumerURL);
Assertions.assertEquals(4, serviceUrls.size());
assertTrue(serviceUrls.get(0).getIp().contains("30.10."));
List<URL> serviceUrls2 = listener.getAddresses(protocolServiceKey2, consumerURL);
Assertions.assertEquals(4, serviceUrls2.size());
assertTrue(serviceUrls2.get(0).getIp().contains("30.10."));
List<URL> serviceUrls3 = listener.getAddresses(protocolServiceKey3, consumerURL);
Assertions.assertEquals(2, serviceUrls3.size());
assertTrue(serviceUrls3.get(0).getIp().contains("30.10."));
// app2 empty notification
ServiceInstancesChangedEvent app2_event_again =
new ServiceInstancesChangedEvent("app2", Collections.EMPTY_LIST);
listener.onEvent(app2_event_again);
// check app2 cleared
Map<String, List<ServiceInstance>> allInstances_app2 = listener.getAllInstances();
Assertions.assertEquals(2, allInstances_app2.size());
Assertions.assertEquals(0, allInstances_app2.get("app1").size());
Assertions.assertEquals(0, allInstances_app2.get("app2").size());
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey1, consumerURL)));
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey2, consumerURL)));
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey3, consumerURL)));
}
// 正常场景。检查instance listener -> service listener(Directory)地址推送流程
@Test
@Order(5)
public void testServiceListenerNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
NotifyListener demoServiceListener = Mockito.mock(NotifyListener.class);
when(demoServiceListener.getConsumerUrl()).thenReturn(consumerURL);
NotifyListener demoService2Listener = Mockito.mock(NotifyListener.class);
when(demoService2Listener.getConsumerUrl()).thenReturn(consumerURL2);
listener.addListenerAndNotify(consumerURL, demoServiceListener);
listener.addListenerAndNotify(consumerURL2, demoService2Listener);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// check
ArgumentCaptor<List<URL>> captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener, Mockito.times(1)).notify(captor.capture());
List<URL> notifiedUrls = captor.getValue();
Assertions.assertEquals(3, notifiedUrls.size());
ArgumentCaptor<List<URL>> captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener, Mockito.times(1)).notify(captor2.capture());
List<URL> notifiedUrls2 = captor2.getValue();
Assertions.assertEquals(0, notifiedUrls2.size());
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// check
ArgumentCaptor<List<URL>> app2_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener, Mockito.times(2)).notify(app2_captor.capture());
List<URL> app2_notifiedUrls = app2_captor.getValue();
Assertions.assertEquals(7, app2_notifiedUrls.size());
ArgumentCaptor<List<URL>> app2_captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener, Mockito.times(2)).notify(app2_captor2.capture());
List<URL> app2_notifiedUrls2 = app2_captor2.getValue();
Assertions.assertEquals(4, app2_notifiedUrls2.size());
// test service listener still get notified when added after instance notification.
NotifyListener demoService3Listener = Mockito.mock(NotifyListener.class);
when(demoService3Listener.getConsumerUrl()).thenReturn(consumerURL3);
listener.addListenerAndNotify(consumerURL3, demoService3Listener);
Mockito.verify(demoService3Listener, Mockito.times(1)).notify(Mockito.anyList());
}
@Test
@Order(6)
public void testMultiServiceListenerNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
NotifyListener demoServiceListener1 = Mockito.mock(NotifyListener.class);
when(demoServiceListener1.getConsumerUrl()).thenReturn(consumerURL);
NotifyListener demoServiceListener2 = Mockito.mock(NotifyListener.class);
when(demoServiceListener2.getConsumerUrl()).thenReturn(consumerURL);
NotifyListener demoService2Listener1 = Mockito.mock(NotifyListener.class);
when(demoService2Listener1.getConsumerUrl()).thenReturn(consumerURL2);
NotifyListener demoService2Listener2 = Mockito.mock(NotifyListener.class);
when(demoService2Listener2.getConsumerUrl()).thenReturn(consumerURL2);
listener.addListenerAndNotify(consumerURL, demoServiceListener1);
listener.addListenerAndNotify(consumerURL, demoServiceListener2);
listener.addListenerAndNotify(consumerURL2, demoService2Listener1);
listener.addListenerAndNotify(consumerURL2, demoService2Listener2);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// check
ArgumentCaptor<List<URL>> captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener1, Mockito.times(1)).notify(captor.capture());
List<URL> notifiedUrls = captor.getValue();
Assertions.assertEquals(3, notifiedUrls.size());
ArgumentCaptor<List<URL>> captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener1, Mockito.times(1)).notify(captor2.capture());
List<URL> notifiedUrls2 = captor2.getValue();
Assertions.assertEquals(0, notifiedUrls2.size());
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// check
ArgumentCaptor<List<URL>> app2_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener1, Mockito.times(2)).notify(app2_captor.capture());
List<URL> app2_notifiedUrls = app2_captor.getValue();
Assertions.assertEquals(7, app2_notifiedUrls.size());
ArgumentCaptor<List<URL>> app2_captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener1, Mockito.times(2)).notify(app2_captor2.capture());
List<URL> app2_notifiedUrls2 = app2_captor2.getValue();
Assertions.assertEquals(4, app2_notifiedUrls2.size());
// test service listener still get notified when added after instance notification.
NotifyListener demoService3Listener = Mockito.mock(NotifyListener.class);
when(demoService3Listener.getConsumerUrl()).thenReturn(consumerURL3);
listener.addListenerAndNotify(consumerURL3, demoService3Listener);
Mockito.verify(demoService3Listener, Mockito.times(1)).notify(Mockito.anyList());
}
/**
* Test subscribe multiple protocols
*/
@Test
@Order(7)
public void testSubscribeMultipleProtocols() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// no protocol specified, consume all instances
NotifyListener demoServiceListener1 = Mockito.mock(NotifyListener.class);
when(demoServiceListener1.getConsumerUrl()).thenReturn(noProtocolConsumerURL);
listener.addListenerAndNotify(noProtocolConsumerURL, demoServiceListener1);
// multiple protocols specified
NotifyListener demoServiceListener2 = Mockito.mock(NotifyListener.class);
when(demoServiceListener2.getConsumerUrl()).thenReturn(multipleProtocolsConsumerURL);
listener.addListenerAndNotify(multipleProtocolsConsumerURL, demoServiceListener2);
// one protocol specified
NotifyListener demoServiceListener3 = Mockito.mock(NotifyListener.class);
when(demoServiceListener3.getConsumerUrl()).thenReturn(singleProtocolsConsumerURL);
listener.addListenerAndNotify(singleProtocolsConsumerURL, demoServiceListener3);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event =
new ServiceInstancesChangedEvent("app1", app1InstancesMultipleProtocols);
listener.onEvent(app1_event);
// check instances expose framework supported default protocols(currently dubbo, triple and rest) are notified
ArgumentCaptor<List<URL>> default_protocol_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener1, Mockito.times(1)).notify(default_protocol_captor.capture());
List<URL> default_protocol_notifiedUrls = default_protocol_captor.getValue();
Assertions.assertEquals(4, default_protocol_notifiedUrls.size());
// check instances expose protocols in consuming list(dubbo and triple) are notified
ArgumentCaptor<List<URL>> multi_protocols_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener2, Mockito.times(1)).notify(multi_protocols_captor.capture());
List<URL> multi_protocol_notifiedUrls = multi_protocols_captor.getValue();
Assertions.assertEquals(4, multi_protocol_notifiedUrls.size());
// check instances expose protocols in consuming list(only triple) are notified
ArgumentCaptor<List<URL>> single_protocols_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener3, Mockito.times(1)).notify(single_protocols_captor.capture());
List<URL> single_protocol_notifiedUrls = single_protocols_captor.getValue();
Assertions.assertEquals(1, single_protocol_notifiedUrls.size());
}
/**
* Test subscribe multiple groups
*/
@Test
@Order(8)
public void testSubscribeMultipleGroups() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify instance change
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, "", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, ",group1", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/MockServiceInstancesChangedListener.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/MockServiceInstancesChangedListener.java | /*
* 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.event.listener;
import org.apache.dubbo.common.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MockServiceInstancesChangedListener extends ServiceInstancesChangedListener {
public MockServiceInstancesChangedListener(Set<String> serviceNames, ServiceDiscovery serviceDiscovery) {
super(serviceNames, serviceDiscovery);
}
@Override
public synchronized void onEvent(ServiceInstancesChangedEvent event) {
// do nothing
}
@Override
public List<URL> getAddresses(ProtocolServiceKey protocolServiceKey, URL consumerURL) {
return super.getAddresses(protocolServiceKey, consumerURL);
}
public Map<String, Set<NotifyListenerWithKey>> getServiceListeners() {
return listeners;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationInvokerTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationInvokerTest.java | /*
* 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.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.registry.client.migration.model.MigrationStep;
import org.apache.dubbo.registry.integration.DemoService;
import org.apache.dubbo.registry.integration.DynamicDirectory;
import org.apache.dubbo.registry.integration.RegistryProtocol;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
class MigrationInvokerTest {
@BeforeEach
public void before() {
FrameworkModel.destroyAll();
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("Test");
ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig);
ApplicationModel.defaultModel().getBeanFactory().registerBean(FrameworkStatusReportService.class);
}
@AfterEach
public void after() {
FrameworkModel.destroyAll();
}
@SuppressWarnings("all")
@Test
void test() {
RegistryProtocol registryProtocol = Mockito.mock(RegistryProtocol.class);
ClusterInvoker invoker = Mockito.mock(ClusterInvoker.class);
ClusterInvoker serviceDiscoveryInvoker = Mockito.mock(ClusterInvoker.class);
DynamicDirectory directory = Mockito.mock(DynamicDirectory.class);
DynamicDirectory serviceDiscoveryDirectory = Mockito.mock(DynamicDirectory.class);
Mockito.when(invoker.getDirectory()).thenReturn(directory);
Mockito.when(serviceDiscoveryInvoker.getDirectory()).thenReturn(serviceDiscoveryDirectory);
Mockito.when(invoker.isAvailable()).thenReturn(true);
Mockito.when(serviceDiscoveryInvoker.isAvailable()).thenReturn(true);
Mockito.when(invoker.hasProxyInvokers()).thenReturn(true);
Mockito.when(serviceDiscoveryInvoker.hasProxyInvokers()).thenReturn(true);
List<Invoker<?>> invokers = new LinkedList<>();
invokers.add(Mockito.mock(Invoker.class));
invokers.add(Mockito.mock(Invoker.class));
List<Invoker<?>> serviceDiscoveryInvokers = new LinkedList<>();
serviceDiscoveryInvokers.add(Mockito.mock(Invoker.class));
serviceDiscoveryInvokers.add(Mockito.mock(Invoker.class));
Mockito.when(directory.getAllInvokers()).thenReturn(invokers);
Mockito.when(serviceDiscoveryDirectory.getAllInvokers()).thenReturn(serviceDiscoveryInvokers);
Mockito.when(registryProtocol.getInvoker(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
.thenReturn(invoker);
Mockito.when(registryProtocol.getServiceDiscoveryInvoker(
Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
.thenReturn(serviceDiscoveryInvoker);
URL consumerURL = Mockito.mock(URL.class);
Mockito.when(consumerURL.getServiceInterface()).thenReturn("Test");
Mockito.when(consumerURL.getGroup()).thenReturn("Group");
Mockito.when(consumerURL.getVersion()).thenReturn("0.0.0");
Mockito.when(consumerURL.getServiceKey()).thenReturn("Group/Test:0.0.0");
Mockito.when(consumerURL.getDisplayServiceKey()).thenReturn("Test:0.0.0");
Mockito.when(consumerURL.getOrDefaultApplicationModel()).thenReturn(ApplicationModel.defaultModel());
Mockito.when(invoker.getUrl()).thenReturn(consumerURL);
Mockito.when(serviceDiscoveryInvoker.getUrl()).thenReturn(consumerURL);
MigrationInvoker<?> migrationInvoker =
new MigrationInvoker<>(registryProtocol, null, null, DemoService.class, null, consumerURL);
MigrationRule migrationRule = Mockito.mock(MigrationRule.class);
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(true);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(1)).invoke(null);
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_APPLICATION);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(1)).invoke(null);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(1.0f);
migrationInvoker.migrateToApplicationFirstInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.APPLICATION_FIRST);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(2)).invoke(null);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(2.0f);
migrationInvoker.migrateToApplicationFirstInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.APPLICATION_FIRST);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(2)).invoke(null);
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(false);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(1.0f);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(3)).invoke(null);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(4)).invoke(null);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(2.0f);
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_APPLICATION);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(5)).invoke(null);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(1.0f);
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_APPLICATION);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(3)).invoke(null);
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_APPLICATION);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(4)).invoke(null);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(2.0f);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(5)).invoke(null);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(2.0f);
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(true);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(6)).invoke(null);
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_APPLICATION);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(6)).invoke(null);
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(false);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(7)).invoke(null);
Assertions.assertNull(migrationInvoker.getInvoker());
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(true);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(false);
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_APPLICATION);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(7)).invoke(null);
Assertions.assertNull(migrationInvoker.getServiceDiscoveryInvoker());
ArgumentCaptor<InvokersChangedListener> argument = ArgumentCaptor.forClass(InvokersChangedListener.class);
Mockito.verify(serviceDiscoveryDirectory, Mockito.atLeastOnce()).setInvokersChangedListener(argument.capture());
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(1.0f);
migrationInvoker.migrateToApplicationFirstInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.APPLICATION_FIRST);
for (int i = 0; i < 20; i++) {
migrationInvoker.invoke(null);
}
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(27)).invoke(null);
serviceDiscoveryInvokers.remove(1);
Mockito.when(serviceDiscoveryInvoker.hasProxyInvokers()).thenReturn(false);
argument.getAllValues().get(argument.getAllValues().size() - 1).onChange();
for (int i = 0; i < 20; i++) {
migrationInvoker.invoke(null);
}
Mockito.verify(invoker, Mockito.times(27)).invoke(null);
serviceDiscoveryInvokers.add(Mockito.mock(Invoker.class));
Mockito.when(serviceDiscoveryInvoker.hasProxyInvokers()).thenReturn(true);
argument.getAllValues().get(argument.getAllValues().size() - 1).onChange();
Mockito.when(migrationRule.getProportion(Mockito.any())).thenReturn(50);
migrationInvoker.setMigrationRule(migrationRule);
for (int i = 0; i < 1000; i++) {
migrationInvoker.invoke(null);
}
Mockito.verify(serviceDiscoveryInvoker, Mockito.atMost(1026)).invoke(null);
Mockito.verify(invoker, Mockito.atLeast(28)).invoke(null);
Mockito.when(migrationRule.getDelay(Mockito.any())).thenReturn(1);
long currentTimeMillis = System.currentTimeMillis();
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
Assertions.assertTrue(System.currentTimeMillis() - currentTimeMillis >= 2000);
}
@SuppressWarnings("all")
@Test
void testDecide() {
RegistryProtocol registryProtocol = Mockito.mock(RegistryProtocol.class);
ClusterInvoker invoker = Mockito.mock(ClusterInvoker.class);
ClusterInvoker serviceDiscoveryInvoker = Mockito.mock(ClusterInvoker.class);
DynamicDirectory directory = Mockito.mock(DynamicDirectory.class);
DynamicDirectory serviceDiscoveryDirectory = Mockito.mock(DynamicDirectory.class);
Mockito.when(invoker.getDirectory()).thenReturn(directory);
Mockito.when(serviceDiscoveryInvoker.getDirectory()).thenReturn(serviceDiscoveryDirectory);
Mockito.when(invoker.isAvailable()).thenReturn(true);
Mockito.when(serviceDiscoveryInvoker.isAvailable()).thenReturn(true);
Mockito.when(invoker.hasProxyInvokers()).thenReturn(true);
Mockito.when(serviceDiscoveryInvoker.hasProxyInvokers()).thenReturn(true);
List<Invoker<?>> invokers = new LinkedList<>();
invokers.add(Mockito.mock(Invoker.class));
invokers.add(Mockito.mock(Invoker.class));
List<Invoker<?>> serviceDiscoveryInvokers = new LinkedList<>();
serviceDiscoveryInvokers.add(Mockito.mock(Invoker.class));
serviceDiscoveryInvokers.add(Mockito.mock(Invoker.class));
Mockito.when(directory.getAllInvokers()).thenReturn(invokers);
Mockito.when(serviceDiscoveryDirectory.getAllInvokers()).thenReturn(serviceDiscoveryInvokers);
Mockito.when(registryProtocol.getInvoker(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
.thenReturn(invoker);
Mockito.when(registryProtocol.getServiceDiscoveryInvoker(
Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
.thenReturn(serviceDiscoveryInvoker);
URL consumerURL = Mockito.mock(URL.class);
Mockito.when(consumerURL.getServiceInterface()).thenReturn("Test");
Mockito.when(consumerURL.getGroup()).thenReturn("Group");
Mockito.when(consumerURL.getVersion()).thenReturn("0.0.0");
Mockito.when(consumerURL.getServiceKey()).thenReturn("Group/Test:0.0.0");
Mockito.when(consumerURL.getDisplayServiceKey()).thenReturn("Test:0.0.0");
Mockito.when(consumerURL.getOrDefaultApplicationModel()).thenReturn(ApplicationModel.defaultModel());
Mockito.when(invoker.getUrl()).thenReturn(consumerURL);
Mockito.when(serviceDiscoveryInvoker.getUrl()).thenReturn(consumerURL);
MigrationInvoker<?> migrationInvoker =
new MigrationInvoker<>(registryProtocol, null, null, DemoService.class, null, consumerURL);
MigrationRule migrationRule = Mockito.mock(MigrationRule.class);
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(true);
migrationInvoker.migrateToApplicationFirstInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.APPLICATION_FIRST);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(1)).invoke(null);
Mockito.when(serviceDiscoveryInvoker.isAvailable()).thenReturn(false);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(1)).invoke(null);
Mockito.when(serviceDiscoveryInvoker.isAvailable()).thenReturn(true);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(2)).invoke(null);
}
@Test
void testConcurrency() {
// 独立线程
// 独立线程invoker状态切换
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparatorTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparatorTest.java | /*
* 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.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.registry.client.migration.DefaultMigrationAddressComparator.NEW_ADDRESS_SIZE;
import static org.apache.dubbo.registry.client.migration.DefaultMigrationAddressComparator.OLD_ADDRESS_SIZE;
class DefaultMigrationAddressComparatorTest {
@SuppressWarnings("all")
@Test
void test() {
DefaultMigrationAddressComparator comparator = new DefaultMigrationAddressComparator();
ClusterInvoker newInvoker = Mockito.mock(ClusterInvoker.class);
ClusterInvoker oldInvoker = Mockito.mock(ClusterInvoker.class);
Directory newDirectory = Mockito.mock(Directory.class);
Directory oldDirectory = Mockito.mock(Directory.class);
MigrationRule rule = Mockito.mock(MigrationRule.class);
URL url = Mockito.mock(URL.class);
Mockito.when(url.getDisplayServiceKey()).thenReturn("test");
Mockito.when(newInvoker.getDirectory()).thenReturn(newDirectory);
Mockito.when(oldInvoker.getDirectory()).thenReturn(oldDirectory);
Mockito.when(newInvoker.getUrl()).thenReturn(url);
Mockito.when(oldInvoker.getUrl()).thenReturn(url);
Mockito.when(newInvoker.hasProxyInvokers()).thenReturn(false);
Mockito.when(newDirectory.getAllInvokers()).thenReturn(Collections.emptyList());
Assertions.assertFalse(comparator.shouldMigrate(newInvoker, oldInvoker, rule));
Assertions.assertEquals(-1, comparator.getAddressSize("test").get(NEW_ADDRESS_SIZE));
Assertions.assertEquals(0, comparator.getAddressSize("test").get(OLD_ADDRESS_SIZE));
Mockito.when(newInvoker.hasProxyInvokers()).thenReturn(true);
Mockito.when(oldInvoker.hasProxyInvokers()).thenReturn(false);
Mockito.when(oldDirectory.getAllInvokers()).thenReturn(Collections.emptyList());
Assertions.assertTrue(comparator.shouldMigrate(newInvoker, oldInvoker, rule));
Assertions.assertEquals(0, comparator.getAddressSize("test").get(NEW_ADDRESS_SIZE));
Assertions.assertEquals(-1, comparator.getAddressSize("test").get(OLD_ADDRESS_SIZE));
Mockito.when(oldInvoker.hasProxyInvokers()).thenReturn(true);
List<Invoker<?>> newInvokerList = new LinkedList<>();
newInvokerList.add(Mockito.mock(Invoker.class));
newInvokerList.add(Mockito.mock(Invoker.class));
newInvokerList.add(Mockito.mock(Invoker.class));
Mockito.when(newDirectory.getAllInvokers()).thenReturn(newInvokerList);
List<Invoker<?>> oldInvokerList = new LinkedList<>();
oldInvokerList.add(Mockito.mock(Invoker.class));
oldInvokerList.add(Mockito.mock(Invoker.class));
Mockito.when(oldDirectory.getAllInvokers()).thenReturn(oldInvokerList);
Assertions.assertTrue(comparator.shouldMigrate(newInvoker, oldInvoker, null));
Mockito.when(rule.getThreshold(url)).thenReturn(0.5f);
newInvokerList.clear();
newInvokerList.add(Mockito.mock(Invoker.class));
Assertions.assertTrue(comparator.shouldMigrate(newInvoker, oldInvoker, rule));
newInvokerList.clear();
// hasProxyInvokers will check if invokers list is empty
// if hasProxyInvokers return true, comparator will directly because default threshold is 0.0
Assertions.assertTrue(comparator.shouldMigrate(newInvoker, oldInvoker, null));
Assertions.assertFalse(comparator.shouldMigrate(newInvoker, oldInvoker, rule));
Assertions.assertEquals(0, comparator.getAddressSize("test").get(NEW_ADDRESS_SIZE));
Assertions.assertEquals(2, comparator.getAddressSize("test").get(OLD_ADDRESS_SIZE));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleListenerTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleListenerTest.java | /*
* 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.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import static org.awaitility.Awaitility.await;
class MigrationRuleListenerTest {
private String localRule = "key: demo-consumer\n" + "step: APPLICATION_FIRST\n"
+ "threshold: 1.0\n"
+ "proportion: 60\n"
+ "delay: 60\n"
+ "force: false\n"
+ "interfaces:\n"
+ " - serviceKey: DemoService:1.0.0\n"
+ " threshold: 0.5\n"
+ " proportion: 30\n"
+ " delay: 30\n"
+ " force: true\n"
+ " step: APPLICATION_FIRST\n"
+ " - serviceKey: GreetingService:1.0.0\n"
+ " step: FORCE_APPLICATION";
private String remoteRule = "key: demo-consumer\n" + "step: FORCE_APPLICATION\n"
+ "threshold: 1.0\n"
+ "proportion: 60\n"
+ "delay: 60\n"
+ "force: false\n"
+ "interfaces:\n"
+ " - serviceKey: DemoService:1.0.0\n"
+ " threshold: 0.5\n"
+ " proportion: 30\n"
+ " delay: 30\n"
+ " force: true\n"
+ " step: FORCE_APPLICATION\n"
+ " - serviceKey: GreetingService:1.0.0\n"
+ " step: FORCE_INTERFACE";
private String dynamicRemoteRule = "key: demo-consumer\n" + "step: APPLICATION_FIRST\n"
+ "threshold: 1.0\n"
+ "proportion: 60\n"
+ "delay: 60\n"
+ "force: false\n"
+ "interfaces:\n";
@AfterEach
public void tearDown() {
ApplicationModel.reset();
System.clearProperty("dubbo.application.migration.delay");
}
/**
* Listener started with config center and local rule, no initial remote rule.
* Check local rule take effect
*/
@Test
void test() {
DynamicConfiguration dynamicConfiguration = Mockito.mock(DynamicConfiguration.class);
ApplicationModel.reset();
ApplicationModel.defaultModel()
.getDefaultModule()
.modelEnvironment()
.setDynamicConfiguration(dynamicConfiguration);
ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().setLocalMigrationRule(localRule);
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("demo-consumer");
ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig);
URL consumerURL = Mockito.mock(URL.class);
Mockito.when(consumerURL.getServiceKey()).thenReturn("Test");
Mockito.when(consumerURL.getParameter("timestamp")).thenReturn("1");
System.setProperty("dubbo.application.migration.delay", "1");
MigrationRuleHandler<?> handler =
Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging());
CountDownLatch countDownLatch = new CountDownLatch(1);
MigrationRuleListener migrationRuleListener =
new MigrationRuleListener(ApplicationModel.defaultModel().getDefaultModule()) {
@Override
public synchronized void process(ConfigChangedEvent event) {
try {
countDownLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
super.process(event);
}
};
MigrationInvoker<?> migrationInvoker = Mockito.mock(MigrationInvoker.class);
migrationRuleListener.getHandlers().put(migrationInvoker, handler);
countDownLatch.countDown();
await().untilAsserted(() -> {
Mockito.verify(handler).doMigrate(Mockito.any());
});
// Mockito.verify(handler, Mockito.timeout(5000)).doMigrate(Mockito.any());
migrationRuleListener.onRefer(null, migrationInvoker, consumerURL, null);
Mockito.verify(handler, Mockito.times(2)).doMigrate(Mockito.any());
}
/**
* Test listener started without local rule and config center, INIT should be used and no scheduled task should be started.
*/
@Test
void testWithInitAndNoLocalRule() {
ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().setDynamicConfiguration(null);
ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().setLocalMigrationRule("");
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("demo-consumer");
ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig);
URL consumerURL = Mockito.mock(URL.class);
Mockito.when(consumerURL.getServiceKey()).thenReturn("Test");
Mockito.when(consumerURL.getParameter("timestamp")).thenReturn("1");
System.setProperty("dubbo.application.migration.delay", "1000");
MigrationRuleHandler<?> handler =
Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging());
MigrationRuleListener migrationRuleListener =
new MigrationRuleListener(ApplicationModel.defaultModel().getDefaultModule());
MigrationInvoker<?> migrationInvoker = Mockito.mock(MigrationInvoker.class);
migrationRuleListener.getHandlers().put(migrationInvoker, handler);
migrationRuleListener.onRefer(null, migrationInvoker, consumerURL, null);
// check migration happened after invoker referred
Mockito.verify(handler, Mockito.times(1)).doMigrate(MigrationRule.getInitRule());
// check no delay tasks created for there's no local rule and no config center
Assertions.assertNull(migrationRuleListener.localRuleMigrationFuture);
Assertions.assertNull(migrationRuleListener.ruleMigrationFuture);
Assertions.assertEquals(0, migrationRuleListener.ruleQueue.size());
}
/**
* Listener with config center, initial remote rule and local rule, check
* 1. initial remote rule other than local rule take effect
* 2. remote rule change and all invokers gets notified
*/
@Test
void testWithConfigurationListenerAndLocalRule() {
DynamicConfiguration dynamicConfiguration = Mockito.mock(DynamicConfiguration.class);
Mockito.doReturn(remoteRule).when(dynamicConfiguration).getConfig(Mockito.anyString(), Mockito.anyString());
ApplicationModel.defaultModel()
.getDefaultModule()
.modelEnvironment()
.setDynamicConfiguration(dynamicConfiguration);
ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().setLocalMigrationRule(localRule);
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("demo-consumer");
ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig);
URL consumerURL = Mockito.mock(URL.class);
Mockito.when(consumerURL.getServiceKey()).thenReturn("Test");
Mockito.when(consumerURL.getParameter("timestamp")).thenReturn("1");
URL consumerURL2 = Mockito.mock(URL.class);
Mockito.when(consumerURL2.getServiceKey()).thenReturn("Test2");
Mockito.when(consumerURL2.getParameter("timestamp")).thenReturn("2");
System.setProperty("dubbo.application.migration.delay", "10");
MigrationRuleHandler<?> handler =
Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging());
MigrationRuleHandler<?> handler2 =
Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging());
// Both local rule and remote rule are here
// Local rule with one delayed task started to apply
MigrationRuleListener migrationRuleListener =
new MigrationRuleListener(ApplicationModel.defaultModel().getDefaultModule());
Assertions.assertNotNull(migrationRuleListener.localRuleMigrationFuture);
Assertions.assertNull(migrationRuleListener.ruleMigrationFuture);
MigrationInvoker<?> migrationInvoker = Mockito.mock(MigrationInvoker.class);
MigrationInvoker<?> migrationInvoker2 = Mockito.mock(MigrationInvoker.class);
// Remote rule will be applied when onRefer gets executed
migrationRuleListener.getHandlers().put(migrationInvoker, handler);
migrationRuleListener.onRefer(null, migrationInvoker, consumerURL, null);
MigrationRule tmpRemoteRule = migrationRuleListener.getRule();
ArgumentCaptor<MigrationRule> captor = ArgumentCaptor.forClass(MigrationRule.class);
Mockito.verify(handler, Mockito.times(1)).doMigrate(captor.capture());
Assertions.assertEquals(tmpRemoteRule, captor.getValue());
await().until(() -> migrationRuleListener.localRuleMigrationFuture.isDone());
Assertions.assertNull(migrationRuleListener.ruleMigrationFuture);
Assertions.assertEquals(tmpRemoteRule, migrationRuleListener.getRule());
Mockito.verify(handler, Mockito.times(1)).doMigrate(Mockito.any());
ArgumentCaptor<MigrationRule> captor2 = ArgumentCaptor.forClass(MigrationRule.class);
migrationRuleListener.getHandlers().put(migrationInvoker2, handler2);
migrationRuleListener.onRefer(null, migrationInvoker2, consumerURL2, null);
Mockito.verify(handler2, Mockito.times(1)).doMigrate(captor2.capture());
Assertions.assertEquals(tmpRemoteRule, captor2.getValue());
migrationRuleListener.process(new ConfigChangedEvent("key", "group", dynamicRemoteRule));
await().until(migrationRuleListener.ruleQueue::isEmpty);
await().untilAsserted(() -> {
Mockito.verify(handler, Mockito.times(2)).doMigrate(Mockito.any());
Mockito.verify(handler2, Mockito.times(2)).doMigrate(Mockito.any());
});
Assertions.assertNotNull(migrationRuleListener.ruleMigrationFuture);
ArgumentCaptor<MigrationRule> captor_event = ArgumentCaptor.forClass(MigrationRule.class);
Mockito.verify(handler, Mockito.times(2)).doMigrate(captor_event.capture());
Assertions.assertEquals(
"APPLICATION_FIRST", captor_event.getValue().getStep().toString());
Mockito.verify(handler2, Mockito.times(2)).doMigrate(captor_event.capture());
Assertions.assertEquals(
"APPLICATION_FIRST", captor_event.getValue().getStep().toString());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandlerTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandlerTest.java | /*
* 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.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.registry.client.migration.model.MigrationStep;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class MigrationRuleHandlerTest {
@Test
void test() {
MigrationClusterInvoker<?> invoker = Mockito.mock(MigrationClusterInvoker.class);
URL url = Mockito.mock(URL.class);
Mockito.when(url.getDisplayServiceKey()).thenReturn("test");
Mockito.when(url.getParameter(Mockito.any(), (String) Mockito.any())).thenAnswer(i -> i.getArgument(1));
Mockito.when(url.getOrDefaultApplicationModel()).thenReturn(ApplicationModel.defaultModel());
MigrationRuleHandler<?> handler = new MigrationRuleHandler<>(invoker, url);
Mockito.when(invoker.migrateToForceApplicationInvoker(Mockito.any())).thenReturn(true);
Mockito.when(invoker.migrateToForceInterfaceInvoker(Mockito.any())).thenReturn(true);
MigrationRule initRule = MigrationRule.getInitRule();
handler.doMigrate(initRule);
Mockito.verify(invoker, Mockito.times(1)).migrateToApplicationFirstInvoker(initRule);
MigrationRule rule = Mockito.mock(MigrationRule.class);
Mockito.when(rule.getStep(url)).thenReturn(MigrationStep.FORCE_APPLICATION);
handler.doMigrate(rule);
Mockito.verify(invoker, Mockito.times(1)).migrateToForceApplicationInvoker(rule);
Mockito.when(rule.getStep(url)).thenReturn(MigrationStep.APPLICATION_FIRST);
handler.doMigrate(rule);
Mockito.verify(invoker, Mockito.times(1)).migrateToApplicationFirstInvoker(rule);
Mockito.when(rule.getStep(url)).thenReturn(MigrationStep.FORCE_INTERFACE);
handler.doMigrate(rule);
Mockito.verify(invoker, Mockito.times(1)).migrateToForceInterfaceInvoker(rule);
// migration failed, current rule not changed
testMigrationFailed(rule, url, handler, invoker);
// rule not changed, check migration not actually executed
testMigrationWithStepUnchanged(rule, url, handler, invoker);
}
private void testMigrationFailed(
MigrationRule rule, URL url, MigrationRuleHandler<?> handler, MigrationClusterInvoker<?> invoker) {
Assertions.assertEquals(MigrationStep.FORCE_INTERFACE, handler.getMigrationStep());
Mockito.when(invoker.migrateToForceApplicationInvoker(Mockito.any())).thenReturn(false);
Mockito.when(rule.getStep(url)).thenReturn(MigrationStep.FORCE_APPLICATION);
handler.doMigrate(rule);
Mockito.verify(invoker, Mockito.times(2)).migrateToForceApplicationInvoker(rule);
Assertions.assertEquals(MigrationStep.FORCE_INTERFACE, handler.getMigrationStep());
}
private void testMigrationWithStepUnchanged(
MigrationRule rule, URL url, MigrationRuleHandler<?> handler, MigrationClusterInvoker<?> invoker) {
// set the same as
Mockito.when(rule.getStep(url)).thenReturn(handler.getMigrationStep());
handler.doMigrate(rule);
// no interaction
Mockito.verify(invoker, Mockito.times(1)).migrateToForceInterfaceInvoker(rule);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/model/MigrationRuleTest.java | dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/model/MigrationRuleTest.java | /*
* 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.migration.model;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_TYPE_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;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class MigrationRuleTest {
private static final ServiceNameMapping mapping = mock(ServiceNameMapping.class);
@Test
void test_parse() {
when(mapping.getMapping(any(URL.class))).thenReturn(Collections.emptySet());
String rule = "key: demo-consumer\n" + "step: APPLICATION_FIRST\n"
+ "threshold: 1.0\n"
+ "proportion: 60\n"
+ "delay: 60\n"
+ "force: false\n"
+ "interfaces:\n"
+ " - serviceKey: DemoService:1.0.0\n"
+ " threshold: 0.5\n"
+ " proportion: 30\n"
+ " delay: 30\n"
+ " force: true\n"
+ " step: APPLICATION_FIRST\n"
+ " - serviceKey: GreetingService:1.0.0\n"
+ " step: FORCE_APPLICATION\n"
+ "applications:\n"
+ " - serviceKey: TestApplication\n"
+ " threshold: 0.3\n"
+ " proportion: 20\n"
+ " delay: 10\n"
+ " force: false\n"
+ " step: FORCE_INTERFACE\n";
MigrationRule migrationRule = MigrationRule.parse(rule);
assertEquals("demo-consumer", migrationRule.getKey());
assertEquals(MigrationStep.APPLICATION_FIRST, migrationRule.getStep());
assertEquals(1.0f, migrationRule.getThreshold());
assertEquals(60, migrationRule.getProportion());
assertEquals(60, migrationRule.getDelay());
assertEquals(false, migrationRule.getForce());
URL url = Mockito.mock(URL.class);
ApplicationModel defaultModel = Mockito.spy(ApplicationModel.defaultModel());
Mockito.when(defaultModel.getDefaultExtension(ServiceNameMapping.class)).thenReturn(mapping);
Mockito.when(url.getScopeModel()).thenReturn(defaultModel);
Mockito.when(url.getDisplayServiceKey()).thenReturn("DemoService:1.0.0");
Mockito.when(url.getParameter(ArgumentMatchers.eq(REGISTRY_CLUSTER_TYPE_KEY), anyString()))
.thenReturn("default");
Mockito.when(url.getParameter(ArgumentMatchers.eq(REGISTRY_CLUSTER_TYPE_KEY), anyString()))
.thenReturn("default");
assertEquals(2, migrationRule.getInterfaces().size());
assertEquals(0.5f, migrationRule.getThreshold(url));
assertEquals(30, migrationRule.getProportion(url));
assertEquals(30, migrationRule.getDelay(url));
assertTrue(migrationRule.getForce(url));
assertEquals(MigrationStep.APPLICATION_FIRST, migrationRule.getStep(url));
Mockito.when(url.getDisplayServiceKey()).thenReturn("GreetingService:1.0.0");
assertEquals(1.0f, migrationRule.getThreshold(url));
assertEquals(60, migrationRule.getProportion(url));
assertEquals(60, migrationRule.getDelay(url));
assertFalse(migrationRule.getForce(url));
assertEquals(MigrationStep.FORCE_APPLICATION, migrationRule.getStep(url));
Mockito.when(url.getDisplayServiceKey()).thenReturn("GreetingService:1.0.1");
Mockito.when(url.getServiceInterface()).thenReturn("GreetingService");
when(mapping.getRemoteMapping(any(URL.class))).thenReturn(Collections.singleton("TestApplication"));
Set<String> services = new HashSet<>();
services.add("TestApplication");
when(mapping.getMapping(any(URL.class))).thenReturn(services);
assertEquals(0.3f, migrationRule.getThreshold(url));
assertEquals(20, migrationRule.getProportion(url));
assertEquals(10, migrationRule.getDelay(url));
assertFalse(migrationRule.getForce(url));
assertEquals(MigrationStep.FORCE_INTERFACE, migrationRule.getStep(url));
when(mapping.getMapping(any(URL.class))).thenReturn(Collections.emptySet());
ApplicationModel.defaultModel().destroy();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Registry.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Registry.java | /*
* 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;
import org.apache.dubbo.common.Node;
import org.apache.dubbo.common.URL;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_DELAY_NOTIFICATION_TIME;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_DELAY_NOTIFICATION_KEY;
/**
* Registry. (SPI, Prototype, ThreadSafe)
*
* @see org.apache.dubbo.registry.RegistryFactory#getRegistry(URL)
* @see org.apache.dubbo.registry.support.AbstractRegistry
*/
public interface Registry extends Node, RegistryService {
default int getDelay() {
return getUrl().getParameter(REGISTRY_DELAY_NOTIFICATION_KEY, DEFAULT_DELAY_NOTIFICATION_TIME);
}
default boolean isServiceDiscovery() {
return false;
}
default void reExportRegister(URL url) {
register(url);
}
default void reExportUnregister(URL url) {
unregister(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ListenerRegistryWrapper.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ListenerRegistryWrapper.java | /*
* 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;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import java.util.List;
import java.util.function.Consumer;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
public class ListenerRegistryWrapper implements Registry {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ListenerRegistryWrapper.class);
private final Registry registry;
private final List<RegistryServiceListener> listeners;
public ListenerRegistryWrapper(Registry registry, List<RegistryServiceListener> listeners) {
this.registry = registry;
this.listeners = listeners;
}
@Override
public URL getUrl() {
return registry.getUrl();
}
@Override
public boolean isAvailable() {
return registry.isAvailable();
}
@Override
public void destroy() {
registry.destroy();
}
@Override
public void register(URL url) {
try {
if (registry != null) {
registry.register(url);
}
} finally {
if (!UrlUtils.isConsumer(url)) {
listenerEvent(serviceListener -> serviceListener.onRegister(url, registry));
}
}
}
@Override
public void unregister(URL url) {
try {
if (registry != null) {
registry.unregister(url);
}
} finally {
if (!UrlUtils.isConsumer(url)) {
listenerEvent(serviceListener -> serviceListener.onUnregister(url, registry));
}
}
}
@Override
public void subscribe(URL url, NotifyListener listener) {
try {
if (registry != null) {
registry.subscribe(url, listener);
}
} finally {
listenerEvent(serviceListener -> serviceListener.onSubscribe(url, registry));
}
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
try {
registry.unsubscribe(url, listener);
} finally {
listenerEvent(serviceListener -> serviceListener.onUnsubscribe(url, registry));
}
}
@Override
public boolean isServiceDiscovery() {
return registry.isServiceDiscovery();
}
@Override
public List<URL> lookup(URL url) {
return registry.lookup(url);
}
public Registry getRegistry() {
return registry;
}
private void listenerEvent(Consumer<RegistryServiceListener> consumer) {
if (CollectionUtils.isNotEmpty(listeners)) {
RuntimeException exception = null;
for (RegistryServiceListener listener : listeners) {
if (listener != null) {
try {
consumer.accept(listener);
} catch (RuntimeException t) {
logger.error(INTERNAL_ERROR, "unknown error in registry module", "", t.getMessage(), t);
exception = t;
}
}
}
if (exception != null) {
throw exception;
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactoryWrapper.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactoryWrapper.java | /*
* 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;
import org.apache.dubbo.common.URL;
import java.util.Collections;
public class RegistryFactoryWrapper implements RegistryFactory {
private RegistryFactory registryFactory;
public RegistryFactoryWrapper(RegistryFactory registryFactory) {
this.registryFactory = registryFactory;
}
@Override
public Registry getRegistry(URL url) {
return new ListenerRegistryWrapper(
registryFactory.getRegistry(url),
Collections.unmodifiableList(url.getOrDefaultApplicationModel()
.getExtensionLoader(RegistryServiceListener.class)
.getActivateExtension(url, "registry.listeners")));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/NotifyListener.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/NotifyListener.java | /*
* 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;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import java.util.List;
/**
* NotifyListener. (API, Prototype, ThreadSafe)
*
* @see org.apache.dubbo.registry.RegistryService#subscribe(URL, NotifyListener)
*/
public interface NotifyListener {
/**
* Triggered when a service change notification is received.
* <p>
* Notify needs to support the contract: <br>
* 1. Always notifications on the service interface and the dimension of the data type. that is, won't notify part of the same type data belonging to one service. Users do not need to compare the results of the previous notification.<br>
* 2. The first notification at a subscription must be a full notification of all types of data of a service.<br>
* 3. At the time of change, different types of data are allowed to be notified separately, e.g.: providers, consumers, routers, overrides. It allows only one of these types to be notified, but the data of this type must be full, not incremental.<br>
* 4. If a data type is empty, need to notify a empty protocol with category parameter identification of url data.<br>
* 5. The order of notifications to be guaranteed by the notifications(That is, the implementation of the registry). Such as: single thread push, queue serialization, and version comparison.<br>
*
* @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)}.
*/
void notify(List<URL> urls);
default void addServiceListener(ServiceInstancesChangedListener instanceListener) {}
default ServiceInstancesChangedListener getServiceListener() {
return null;
}
default URL getConsumerUrl() {
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryNotifier.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryNotifier.java | /*
* 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;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_DELAY_EXECUTE_TIMES;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_NOTIFY_EVENT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT;
public abstract class RegistryNotifier {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RegistryNotifier.class);
private volatile long lastExecuteTime;
private volatile long lastEventTime;
private final URL url;
private Object rawAddresses;
private long delayTime;
// should delay notify or not
private final AtomicBoolean shouldDelay = new AtomicBoolean(false);
// for the first 10 notification will be notified immediately
private final AtomicInteger executeTime = new AtomicInteger(0);
private ScheduledExecutorService scheduler;
public RegistryNotifier(URL registryUrl, long delayTime) {
this(registryUrl, delayTime, null);
}
public RegistryNotifier(URL registryUrl, long delayTime, ScheduledExecutorService scheduler) {
this.url = registryUrl;
this.delayTime = delayTime;
if (scheduler == null) {
this.scheduler = registryUrl
.getOrDefaultFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getRegistryNotificationExecutor();
} else {
this.scheduler = scheduler;
}
}
public synchronized void notify(Object rawAddresses) {
this.rawAddresses = rawAddresses;
long notifyTime = System.currentTimeMillis();
this.lastEventTime = notifyTime;
long delta = (System.currentTimeMillis() - lastExecuteTime) - delayTime;
// more than 10 calls && next execute time is in the future
boolean delay = shouldDelay.get() && delta < 0;
// when the scheduler is shutdown, no notification is sent
if (scheduler.isShutdown()) {
if (logger.isWarnEnabled()) {
logger.warn(
COMMON_FAILED_NOTIFY_EVENT,
"",
"",
"Notification scheduler is off, no notifications are sent. Registry URL: " + url);
}
return;
} else if (delay) {
scheduler.schedule(new NotificationTask(this, notifyTime), -delta, TimeUnit.MILLISECONDS);
} else {
// check if more than 10 calls
if (!shouldDelay.get() && executeTime.incrementAndGet() > DEFAULT_DELAY_EXECUTE_TIMES) {
shouldDelay.set(true);
}
scheduler.submit(new NotificationTask(this, notifyTime));
}
try {
while (this.lastEventTime == System.currentTimeMillis()) {
// wait to let event time refresh
Thread.sleep(1);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public long getDelayTime() {
return delayTime;
}
/**
* notification of instance addresses (aka providers).
*
* @param rawAddresses data.
*/
protected abstract void doNotify(Object rawAddresses);
public static class NotificationTask implements Runnable {
private final RegistryNotifier listener;
private final long time;
public NotificationTask(RegistryNotifier listener, long time) {
this.listener = listener;
this.time = time;
}
@Override
public void run() {
try {
if (this.time == listener.lastEventTime) {
listener.doNotify(listener.rawAddresses);
listener.lastExecuteTime = System.currentTimeMillis();
synchronized (listener) {
if (this.time == listener.lastEventTime) {
listener.rawAddresses = null;
}
}
}
} catch (Throwable t) {
logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Error occurred when notify directory. ", t);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ProviderFirstParams.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ProviderFirstParams.java | /*
* 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;
import org.apache.dubbo.common.extension.SPI;
import java.util.Set;
@SPI
public interface ProviderFirstParams {
Set<String> params();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryService.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryService.java | /*
* 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;
import org.apache.dubbo.common.URL;
import java.util.List;
/**
* RegistryService. (SPI, Prototype, ThreadSafe)
*
* @see org.apache.dubbo.registry.Registry
* @see org.apache.dubbo.registry.RegistryFactory#getRegistry(URL)
*/
public interface RegistryService {
/**
* Register data, such as : provider service, consumer address, route rule, override rule and other data.
* <p>
* Registering is required to support the contract:<br>
* 1. When the URL sets the check=false parameter. When the registration fails, the exception is not thrown and retried in the background. Otherwise, the exception will be thrown.<br>
* 2. When URL sets the dynamic=false parameter, it needs to be stored persistently, otherwise, it should be deleted automatically when the registrant has an abnormal exit.<br>
* 3. When the URL sets category=routers, it means classified storage, the default category is providers, and the data can be notified by the classified section. <br>
* 4. When the registry is restarted, network jitter, data can not be lost, including automatically deleting data from the broken line.<br>
* 5. Allow URLs which have the same URL but different parameters to coexist,they can't cover each other.<br>
*
* @param url Registration information , is not allowed to be empty, e.g: dubbo://10.20.153.10/org.apache.dubbo.foo.BarService?version=1.0.0&application=kylin
*/
void register(URL url);
/**
* Unregister
* <p>
* Unregistering is required to support the contract:<br>
* 1. If it is the persistent stored data of dynamic=false, the registration data can not be found, then the IllegalStateException is thrown, otherwise it is ignored.<br>
* 2. Unregister according to the full url match.<br>
*
* @param url Registration information , is not allowed to be empty, e.g: dubbo://10.20.153.10/org.apache.dubbo.foo.BarService?version=1.0.0&application=kylin
*/
void unregister(URL url);
/**
* Subscribe to eligible registered data and automatically push when the registered data is changed.
* <p>
* Subscribing need to support contracts:<br>
* 1. When the URL sets the check=false parameter. When the registration fails, the exception is not thrown and retried in the background. <br>
* 2. When URL sets category=routers, it only notifies the specified classification data. Multiple classifications are separated by commas, and allows asterisk to match, which indicates that all categorical data are subscribed.<br>
* 3. Allow interface, group, version, and classifier as a conditional query, e.g.: interface=org.apache.dubbo.foo.BarService&version=1.0.0<br>
* 4. And the query conditions allow the asterisk to be matched, subscribe to all versions of all the packets of all interfaces, e.g. :interface=*&group=*&version=*&classifier=*<br>
* 5. When the registry is restarted and network jitter, it is necessary to automatically restore the subscription request.<br>
* 6. Allow URLs which have the same URL but different parameters to coexist,they can't cover each other.<br>
* 7. The subscription process must be blocked, when the first notice is finished and then returned.<br>
*
* @param url Subscription condition, not allowed to be empty, e.g. consumer://10.20.153.10/org.apache.dubbo.foo.BarService?version=1.0.0&application=kylin
* @param listener A listener of the change event, not allowed to be empty
*/
void subscribe(URL url, NotifyListener listener);
/**
* Unsubscribe
* <p>
* Unsubscribing is required to support the contract:<br>
* 1. If you don't subscribe, ignore it directly.<br>
* 2. Unsubscribe by full URL match.<br>
*
* @param url Subscription condition, not allowed to be empty, e.g. consumer://10.20.153.10/org.apache.dubbo.foo.BarService?version=1.0.0&application=kylin
* @param listener A listener of the change event, not allowed to be empty
*/
void unsubscribe(URL url, NotifyListener listener);
/**
* Query the registered data that matches the conditions. Corresponding to the push mode of the subscription, this is the pull mode and returns only one result.
*
* @param url Query condition, is not allowed to be empty, e.g. consumer://10.20.153.10/org.apache.dubbo.foo.BarService?version=1.0.0&application=kylin
* @return The registered information list, which may be empty, the meaning is the same as the parameters of {@link org.apache.dubbo.registry.NotifyListener#notify(List<URL>)}.
* @see org.apache.dubbo.registry.NotifyListener#notify(List)
*/
List<URL> lookup(URL url);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryServiceListener.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryServiceListener.java | /*
* 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;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
@SPI
public interface RegistryServiceListener {
default void onRegister(URL url, Registry registry) {}
default void onUnregister(URL url, Registry registry) {}
default void onSubscribe(URL url, Registry registry) {}
default void onUnsubscribe(URL url, Registry registry) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java | /*
* 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;
public interface Constants {
String REGISTER_IP_KEY = "register.ip";
String REGISTER_KEY = "register";
String SUBSCRIBE_KEY = "subscribe";
String DEFAULT_REGISTRY = "dubbo";
String REGISTER = "register";
String UNREGISTER = "unregister";
String SUBSCRIBE = "subscribe";
String UNSUBSCRIBE = "unsubscribe";
String CONFIGURATORS_SUFFIX = ".configurators";
String ADMIN_PROTOCOL = "admin";
String PROVIDER_PROTOCOL = "provider";
String CONSUMER_PROTOCOL = "consumer";
String SCRIPT_PROTOCOL = "script";
String CONDITION_PROTOCOL = "condition";
String TRACE_PROTOCOL = "trace";
/**
* simple the registry for provider.
*
* @since 2.7.0
*/
String SIMPLIFIED_KEY = "simplified";
/**
* To decide whether register center saves file synchronously, the default value is asynchronously
*/
String REGISTRY_FILESAVE_SYNC_KEY = "save.file";
/**
* Reconnection period in milliseconds for register center
*/
String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period";
int DEFAULT_SESSION_TIMEOUT = 60 * 1000;
/**
* Default value for the times of retry: -1 (forever)
*/
int DEFAULT_REGISTRY_RETRY_TIMES = -1;
int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000;
/**
* Default value for the period of retry interval in milliseconds: 5000
*/
int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000;
/**
* Most retry times
*/
String REGISTRY_RETRY_TIMES_KEY = "retry.times";
/**
* Period of registry center's retry interval
*/
String REGISTRY_RETRY_PERIOD_KEY = "retry.period";
String SESSION_TIMEOUT_KEY = "session";
/**
* To decide the frequency of checking Distributed Service Discovery Registry callback hook (in ms)
*/
String ECHO_POLLING_CYCLE_KEY = "echoPollingCycle";
/**
* Default value for check frequency: 60000 (ms)
*/
int DEFAULT_ECHO_POLLING_CYCLE = 60000;
String MIGRATION_STEP_KEY = "migration.step";
String MIGRATION_DELAY_KEY = "migration.delay";
String MIGRATION_FORCE_KEY = "migration.force";
String MIGRATION_PROMOTION_KEY = "migration.promotion";
String MIGRATION_THRESHOLD_KEY = "migration.threshold";
String ENABLE_26X_CONFIGURATION_LISTEN = "enable-26x-configuration-listen";
String ENABLE_CONFIGURATION_LISTEN = "enable-configuration-listen";
/**
* MIGRATION_RULE_XXX from remote configuration
*/
String MIGRATION_RULE_KEY = "key";
String MIGRATION_RULE_STEP_KEY = "step";
String MIGRATION_RULE_THRESHOLD_KEY = "threshold";
String MIGRATION_RULE_PROPORTION_KEY = "proportion";
String MIGRATION_RULE_DELAY_KEY = "delay";
String MIGRATION_RULE_FORCE_KEY = "force";
String MIGRATION_RULE_INTERFACES_KEY = "interfaces";
String MIGRATION_RULE_APPLICATIONS_KEY = "applications";
String USER_HOME = "user.home";
String DUBBO_REGISTRY = "/.dubbo/dubbo-registry-";
String CACHE = ".cache";
int DEFAULT_CAS_RETRY_TIMES = 10;
String CAS_RETRY_TIMES_KEY = "dubbo.metadata-report.cas-retry-times";
int DEFAULT_CAS_RETRY_WAIT_TIME = 100;
String CAS_RETRY_WAIT_TIME_KEY = "dubbo.metadata-report.cas-retry-wait-time";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactory.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactory.java | /*
* 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;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.extension.ExtensionScope.APPLICATION;
/**
* RegistryFactory. (SPI, Singleton, ThreadSafe)
*
* @see org.apache.dubbo.registry.support.AbstractRegistryFactory
*/
@SPI(scope = APPLICATION)
public interface RegistryFactory {
/**
* Connect to the registry
* <p>
* Connecting the registry needs to support the contract: <br>
* 1. When the check=false is set, the connection is not checked, otherwise the exception is thrown when disconnection <br>
* 2. Support username:password authority authentication on URL.<br>
* 3. Support the backup=10.20.153.10 candidate registry cluster address.<br>
* 4. Support file=registry.cache local disk file cache.<br>
* 5. Support the timeout=1000 request timeout setting.<br>
* 6. Support session=60000 session timeout or expiration settings.<br>
*
* @param url Registry address, is not allowed to be empty
* @return Registry reference, never return empty value
*/
@Adaptive({PROTOCOL_KEY})
Registry getRegistry(URL url);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryScopeModelInitializer.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryScopeModelInitializer.java | /*
* 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;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegationV2;
import org.apache.dubbo.registry.integration.ExporterFactory;
import org.apache.dubbo.registry.support.RegistryManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class RegistryScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory();
beanFactory.registerBean(ExporterFactory.class);
}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.registerBean(RegistryManager.class);
beanFactory.registerBean(MetadataServiceDelegation.class);
beanFactory.registerBean(MetadataServiceDelegationV2.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/RegistryManager.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/RegistryManager.java | /*
* 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.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceDiscoveryRegistry;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_FETCH_INSTANCE;
/**
* Application Level, used to collect Registries
*/
public class RegistryManager {
private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(RegistryManager.class);
private ApplicationModel applicationModel;
/**
* Registry Collection Map<RegistryAddress, Registry>
*/
private final Map<String, Registry> registries = new ConcurrentHashMap<>();
/**
* The lock for the acquisition process of the registry
*/
protected final ReentrantLock lock = new ReentrantLock();
private final AtomicBoolean destroyed = new AtomicBoolean(false);
public RegistryManager(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
/**
* Get all registries
*
* @return all registries
*/
public Collection<Registry> getRegistries() {
return Collections.unmodifiableCollection(new LinkedList<>(registries.values()));
}
public Registry getRegistry(String key) {
return registries.get(key);
}
public void putRegistry(String key, Registry registry) {
registries.put(key, registry);
}
public List<ServiceDiscovery> getServiceDiscoveries() {
return getRegistries().stream()
.filter(registry -> registry instanceof ServiceDiscoveryRegistry)
.map(registry -> (ServiceDiscoveryRegistry) registry)
.map(ServiceDiscoveryRegistry::getServiceDiscovery)
.collect(Collectors.toList());
}
/**
* Close all created registries
*/
public void destroyAll() {
if (!destroyed.compareAndSet(false, true)) {
return;
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Close all registries " + getRegistries());
}
// Lock up the registry shutdown process
lock.lock();
try {
for (Registry registry : getRegistries()) {
try {
registry.destroy();
} catch (Throwable e) {
LOGGER.warn(INTERNAL_ERROR, "unknown error in registry module", "", e.getMessage(), e);
}
}
registries.clear();
} finally {
// Release the lock
lock.unlock();
}
}
/**
* Reset state of AbstractRegistryFactory
*/
public void reset() {
destroyed.set(false);
registries.clear();
}
protected Registry getDefaultNopRegistryIfDestroyed() {
if (destroyed.get()) {
// 1-12 Failed to fetch (server) instance since the registry instances have been destroyed.
LOGGER.warn(
REGISTRY_FAILED_FETCH_INSTANCE,
"misuse of the methods",
"",
"All registry instances have been destroyed, failed to fetch any instance. "
+ "Usually, this means no need to try to do unnecessary redundant resource clearance, all registries has been taken care of.");
return DEFAULT_NOP_REGISTRY;
}
return null;
}
protected Lock getRegistryLock() {
return lock;
}
public void removeDestroyedRegistry(Registry toRm) {
lock.lock();
try {
registries.entrySet().removeIf(entry -> entry.getValue().equals(toRm));
} finally {
lock.unlock();
}
}
// for unit test
public void clearRegistryNotDestroy() {
registries.clear();
}
public static RegistryManager getInstance(ApplicationModel applicationModel) {
return applicationModel.getBeanFactory().getBean(RegistryManager.class);
}
private static final Registry DEFAULT_NOP_REGISTRY = new Registry() {
@Override
public URL getUrl() {
return null;
}
@Override
public boolean isAvailable() {
return false;
}
@Override
public void destroy() {}
@Override
public void register(URL url) {}
@Override
public void unregister(URL url) {}
@Override
public void subscribe(URL url, NotifyListener listener) {}
@Override
public void unsubscribe(URL url, NotifyListener listener) {}
@Override
public List<URL> lookup(URL url) {
return null;
}
};
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/SkipFailbackWrapperException.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/SkipFailbackWrapperException.java | /*
* 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.support;
/**
* Wrapper Exception, it is used to indicate that {@link FailbackRegistry} skips Failback.
* <p>
* NOTE: Expect to find other more conventional ways of instruction.
*
* @see FailbackRegistry
*/
public class SkipFailbackWrapperException extends RuntimeException {
public SkipFailbackWrapperException(Throwable cause) {
super(cause);
}
@Override
public synchronized Throwable fillInStackTrace() {
// do nothing
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/CacheableFailbackRegistry.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/CacheableFailbackRegistry.java | /*
* 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.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.URLStrParser;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.url.component.DubboServiceAddressURL;
import org.apache.dubbo.common.url.component.ServiceAddressURL;
import org.apache.dubbo.common.url.component.URLAddress;
import org.apache.dubbo.common.url.component.URLParam;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.URLStrParser.ENCODED_AND_MARK;
import static org.apache.dubbo.common.URLStrParser.ENCODED_PID_KEY;
import static org.apache.dubbo.common.URLStrParser.ENCODED_QUESTION_MARK;
import static org.apache.dubbo.common.URLStrParser.ENCODED_TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CACHE_CLEAR_TASK_INTERVAL;
import static org.apache.dubbo.common.constants.CommonConstants.CACHE_CLEAR_WAITING_THRESHOLD;
import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_SEPARATOR_ENCODED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_CLEAR_CACHED_URLS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_URL_EVICTING;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NO_PARAMETERS_URL;
import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_ENABLE_EMPTY_PROTECTION;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.ENABLE_EMPTY_PROTECTION_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY;
/**
* <p>
* Based on FailbackRegistry, it adds a URLAddress and URLParam cache to save RAM space.
*
* <p>
* It's useful for registries whose sdk returns raw string as provider instance. For example, Zookeeper and etcd.
*
* @see org.apache.dubbo.registry.support.FailbackRegistry
* @see org.apache.dubbo.registry.support.AbstractRegistry
*/
public abstract class CacheableFailbackRegistry extends FailbackRegistry {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(CacheableFailbackRegistry.class);
private static String[] VARIABLE_KEYS = new String[] {ENCODED_TIMESTAMP_KEY, ENCODED_PID_KEY};
protected ConcurrentMap<String, URLAddress> stringAddress = new ConcurrentHashMap<>();
protected ConcurrentMap<String, URLParam> stringParam = new ConcurrentHashMap<>();
private ScheduledExecutorService cacheRemovalScheduler;
private int cacheRemovalTaskIntervalInMillis;
private int cacheClearWaitingThresholdInMillis;
private Map<ServiceAddressURL, Long> waitForRemove = new ConcurrentHashMap<>();
private Semaphore semaphore = new Semaphore(1);
private final Map<String, String> extraParameters;
protected final Map<URL, Map<String, ServiceAddressURL>> stringUrls = new ConcurrentHashMap<>();
protected CacheableFailbackRegistry(URL url) {
super(url);
extraParameters = new HashMap<>(8);
extraParameters.put(CHECK_KEY, String.valueOf(false));
cacheRemovalScheduler = url.getOrDefaultFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.nextScheduledExecutor();
cacheRemovalTaskIntervalInMillis = getIntConfig(url.getScopeModel(), CACHE_CLEAR_TASK_INTERVAL, 2 * 60 * 1000);
cacheClearWaitingThresholdInMillis =
getIntConfig(url.getScopeModel(), CACHE_CLEAR_WAITING_THRESHOLD, 5 * 60 * 1000);
}
protected static int getIntConfig(ScopeModel scopeModel, String key, int def) {
String str = ConfigurationUtils.getProperty(scopeModel, key);
int result = def;
if (StringUtils.isNotEmpty(str)) {
try {
result = Integer.parseInt(str);
} catch (NumberFormatException e) {
// 0-2 Property type mismatch.
logger.warn(
COMMON_PROPERTY_TYPE_MISMATCH,
"typo in property value",
"This property requires an integer value.",
"Invalid registry properties configuration key " + key + ", value " + str);
}
}
return result;
}
@Override
public void doUnsubscribe(URL url, NotifyListener listener) {
this.evictURLCache(url);
}
protected void evictURLCache(URL url) {
Map<String, ServiceAddressURL> oldURLs = stringUrls.remove(url);
try {
if (CollectionUtils.isNotEmptyMap(oldURLs)) {
logger.info("Evicting urls for service " + url.getServiceKey() + ", size " + oldURLs.size());
Long currentTimestamp = System.currentTimeMillis();
for (Map.Entry<String, ServiceAddressURL> entry : oldURLs.entrySet()) {
waitForRemove.put(entry.getValue(), currentTimestamp);
}
if (CollectionUtils.isNotEmptyMap(waitForRemove)) {
if (semaphore.tryAcquire()) {
cacheRemovalScheduler.schedule(
new RemovalTask(), cacheRemovalTaskIntervalInMillis, TimeUnit.MILLISECONDS);
}
}
}
} catch (Exception e) {
// It seems that the most possible statement that causes exception is the 'schedule()' method.
// The executor that FrameworkExecutorRepository.nextScheduledExecutor() method returns
// is made by Executors.newSingleThreadScheduledExecutor().
// After observing the code of ScheduledThreadPoolExecutor.delayedExecute,
// it seems that it only throws RejectedExecutionException when the thread pool is shutdown.
// When? FrameworkExecutorRepository gets destroyed.
// 1-3: URL evicting failed.
logger.warn(
REGISTRY_FAILED_URL_EVICTING,
"thread pool getting destroyed",
"",
"Failed to evict url for " + url.getServiceKey(),
e);
}
}
protected List<URL> toUrlsWithoutEmpty(URL consumer, Collection<String> providers) {
// keep old urls
Map<String, ServiceAddressURL> oldURLs = stringUrls.get(consumer);
// create new urls
Map<String, ServiceAddressURL> newURLs = new HashMap<>((int) (providers.size() / 0.75f + 1));
// remove 'release', 'dubbo', 'methods', timestamp, 'dubbo.tag' parameter
// in consumer URL.
URL copyOfConsumer = removeParamsFromConsumer(consumer);
if (oldURLs == null) {
for (String rawProvider : providers) {
// remove VARIABLE_KEYS(timestamp,pid..) in provider url.
rawProvider = stripOffVariableKeys(rawProvider);
// create DubboServiceAddress object using provider url, consumer url, and extra parameters.
ServiceAddressURL cachedURL = createURL(rawProvider, copyOfConsumer, getExtraParameters());
if (cachedURL == null) {
continue;
}
newURLs.put(rawProvider, cachedURL);
}
} else {
// maybe only default, or "env" + default
for (String rawProvider : providers) {
rawProvider = stripOffVariableKeys(rawProvider);
ServiceAddressURL cachedURL = oldURLs.remove(rawProvider);
if (cachedURL == null) {
cachedURL = createURL(rawProvider, copyOfConsumer, getExtraParameters());
if (cachedURL == null) {
continue;
}
}
newURLs.put(rawProvider, cachedURL);
}
}
evictURLCache(consumer);
stringUrls.put(consumer, newURLs);
return new ArrayList<>(newURLs.values());
}
protected List<URL> toUrlsWithEmpty(URL consumer, String path, Collection<String> providers) {
List<URL> urls = new ArrayList<>(1);
boolean isProviderPath = path.endsWith(PROVIDERS_CATEGORY);
if (isProviderPath) {
if (CollectionUtils.isNotEmpty(providers)) {
urls = toUrlsWithoutEmpty(consumer, providers);
} else {
// clear cache on empty notification: unsubscribe or provider offline
evictURLCache(consumer);
}
} else {
if (CollectionUtils.isNotEmpty(providers)) {
urls = toConfiguratorsWithoutEmpty(consumer, providers);
}
}
if (urls.isEmpty()) {
int i = path.lastIndexOf(PATH_SEPARATOR);
String category = i < 0 ? path : path.substring(i + 1);
if (!PROVIDERS_CATEGORY.equals(category)
|| !getUrl().getParameter(ENABLE_EMPTY_PROTECTION_KEY, DEFAULT_ENABLE_EMPTY_PROTECTION)) {
if (PROVIDERS_CATEGORY.equals(category)) {
logger.warn(
REGISTRY_EMPTY_ADDRESS,
"",
"",
"Service " + consumer.getServiceKey()
+ " received empty address list and empty protection is disabled, will clear current available addresses");
}
URL empty = URLBuilder.from(consumer)
.setProtocol(EMPTY_PROTOCOL)
.addParameter(CATEGORY_KEY, category)
.build();
urls.add(empty);
}
}
return urls;
}
/**
* Create DubboServiceAddress object using provider url, consumer url, and extra parameters.
*
* @param rawProvider provider url string
* @param consumerURL URL object of consumer
* @param extraParameters extra parameters
* @return created DubboServiceAddressURL object
*/
protected ServiceAddressURL createURL(String rawProvider, URL consumerURL, Map<String, String> extraParameters) {
boolean encoded = true;
// use encoded value directly to avoid URLDecoder.decode allocation.
int paramStartIdx = rawProvider.indexOf(ENCODED_QUESTION_MARK);
if (paramStartIdx == -1) {
// if ENCODED_QUESTION_MARK does not show, mark as not encoded.
encoded = false;
}
// split by (encoded) question mark.
// part[0] => protocol + ip address + interface.
// part[1] => parameters (metadata).
String[] parts = URLStrParser.parseRawURLToArrays(rawProvider, paramStartIdx);
if (parts.length <= 1) {
// 1-5 Received URL without any parameters.
logger.warn(REGISTRY_NO_PARAMETERS_URL, "", "", "Received url without any parameters " + rawProvider);
return DubboServiceAddressURL.valueOf(rawProvider, consumerURL);
}
String rawAddress = parts[0];
String rawParams = parts[1];
// Workaround for 'effectively final': duplicate the encoded variable.
boolean isEncoded = encoded;
// PathURLAddress if it's using dubbo protocol.
URLAddress address = ConcurrentHashMapUtils.computeIfAbsent(
stringAddress, rawAddress, k -> URLAddress.parse(k, getDefaultURLProtocol(), isEncoded));
address.setTimestamp(System.currentTimeMillis());
URLParam param = ConcurrentHashMapUtils.computeIfAbsent(
stringParam, rawParams, k -> URLParam.parse(k, isEncoded, extraParameters));
param.setTimestamp(System.currentTimeMillis());
// create service URL using cached address, param, and consumer URL.
ServiceAddressURL cachedServiceAddressURL = createServiceURL(address, param, consumerURL);
if (isMatch(consumerURL, cachedServiceAddressURL)) {
return cachedServiceAddressURL;
}
return null;
}
protected ServiceAddressURL createServiceURL(URLAddress address, URLParam param, URL consumerURL) {
return new DubboServiceAddressURL(address, param, consumerURL, null);
}
private String stripOffVariableKeys(String rawProvider) {
String[] keys = getVariableKeys();
if (keys == null || keys.length == 0) {
return rawProvider;
}
for (String key : keys) {
int idxStart = rawProvider.indexOf(key);
if (idxStart == -1) {
continue;
}
int idxEnd = rawProvider.indexOf(ENCODED_AND_MARK, idxStart);
String part1 = rawProvider.substring(0, idxStart);
if (idxEnd == -1) {
rawProvider = part1;
} else {
String part2 = rawProvider.substring(idxEnd + ENCODED_AND_MARK.length());
rawProvider = part1 + part2;
}
}
if (rawProvider.endsWith(ENCODED_AND_MARK)) {
rawProvider = rawProvider.substring(0, rawProvider.length() - ENCODED_AND_MARK.length());
}
if (rawProvider.endsWith(ENCODED_QUESTION_MARK)) {
rawProvider = rawProvider.substring(0, rawProvider.length() - ENCODED_QUESTION_MARK.length());
}
return rawProvider;
}
private List<URL> toConfiguratorsWithoutEmpty(URL consumer, Collection<String> configurators) {
List<URL> urls = new ArrayList<>();
if (CollectionUtils.isNotEmpty(configurators)) {
for (String provider : configurators) {
if (provider.contains(PROTOCOL_SEPARATOR_ENCODED)) {
URL url = URLStrParser.parseEncodedStr(provider);
if (UrlUtils.isMatch(consumer, url)) {
urls.add(url);
}
}
}
}
return urls;
}
protected Map<String, String> getExtraParameters() {
return extraParameters;
}
protected String[] getVariableKeys() {
return VARIABLE_KEYS;
}
protected String getDefaultURLProtocol() {
return DUBBO;
}
/**
* This method is for unit test to see if the RemovalTask has completed or not.<br />
* <strong>Please do not call this method in other places.</strong>
*/
@Deprecated
protected Semaphore getSemaphore() {
return semaphore;
}
protected abstract boolean isMatch(URL subscribeUrl, URL providerUrl);
/**
* The cached URL removal task, which will be run on a scheduled thread pool. (It will be run after a delay.)
*/
private class RemovalTask implements Runnable {
@Override
public void run() {
logger.info("Clearing cached URLs, waiting to clear size " + waitForRemove.size());
int clearCount = 0;
try {
Iterator<Map.Entry<ServiceAddressURL, Long>> it =
waitForRemove.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<ServiceAddressURL, Long> entry = it.next();
ServiceAddressURL removeURL = entry.getKey();
long removeTime = entry.getValue();
long current = System.currentTimeMillis();
if (current - removeTime >= cacheClearWaitingThresholdInMillis) {
URLAddress urlAddress = removeURL.getUrlAddress();
URLParam urlParam = removeURL.getUrlParam();
if (current - urlAddress.getTimestamp() >= cacheClearWaitingThresholdInMillis) {
stringAddress.remove(urlAddress.getRawAddress());
}
if (current - urlParam.getTimestamp() >= cacheClearWaitingThresholdInMillis) {
stringParam.remove(urlParam.getRawParam());
}
it.remove();
clearCount++;
}
}
} catch (Throwable t) {
// 1-6 Error when clearing cached URLs.
logger.error(REGISTRY_FAILED_CLEAR_CACHED_URLS, "", "", "Error occurred when clearing cached URLs", t);
} finally {
semaphore.release();
}
logger.info("Clear cached URLs, size " + clearCount);
if (CollectionUtils.isNotEmptyMap(waitForRemove)) {
// move to next schedule
if (semaphore.tryAcquire()) {
cacheRemovalScheduler.schedule(
new RemovalTask(), cacheRemovalTaskIntervalInMillis, TimeUnit.MILLISECONDS);
}
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java | /*
* 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.support;
import org.apache.dubbo.common.URL;
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.registry.NotifyListener;
import org.apache.dubbo.registry.ProviderFirstParams;
import org.apache.dubbo.registry.retry.FailedRegisteredTask;
import org.apache.dubbo.registry.retry.FailedSubscribedTask;
import org.apache.dubbo.registry.retry.FailedUnregisteredTask;
import org.apache.dubbo.registry.retry.FailedUnsubscribedTask;
import org.apache.dubbo.remoting.Constants;
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 java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.IS_EXTRA;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT;
import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_PERIOD;
import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY;
/**
* A template implementation of registry service that provides auto-retry ability.
* (SPI, Prototype, ThreadSafe)
*/
public abstract class FailbackRegistry extends AbstractRegistry {
/* retry task map */
private final ConcurrentMap<URL, FailedRegisteredTask> failedRegistered = new ConcurrentHashMap<>();
private final ConcurrentMap<URL, FailedUnregisteredTask> failedUnregistered = new ConcurrentHashMap<>();
private final ConcurrentMap<Holder, FailedSubscribedTask> failedSubscribed = new ConcurrentHashMap<>();
private final ConcurrentMap<Holder, FailedUnsubscribedTask> failedUnsubscribed = new ConcurrentHashMap<>();
/**
* The time in milliseconds the retryExecutor will wait
*/
private final int retryPeriod;
// Timer for failure retry, regular check if there is a request for failure, and if there is, an unlimited retry
private final HashedWheelTimer retryTimer;
public FailbackRegistry(URL url) {
super(url);
this.retryPeriod = url.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD);
// since the retry task will not be very much. 128 ticks is enough.
retryTimer = new HashedWheelTimer(
new NamedThreadFactory("DubboRegistryRetryTimer", true), retryPeriod, TimeUnit.MILLISECONDS, 128);
}
public void removeFailedRegisteredTask(URL url) {
failedRegistered.remove(url);
}
public void removeFailedUnregisteredTask(URL url) {
failedUnregistered.remove(url);
}
public void removeFailedSubscribedTask(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
failedSubscribed.remove(h);
}
public void removeFailedUnsubscribedTask(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
failedUnsubscribed.remove(h);
}
private void addFailedRegistered(URL url) {
FailedRegisteredTask oldOne = failedRegistered.get(url);
if (oldOne != null) {
return;
}
FailedRegisteredTask newTask = new FailedRegisteredTask(url, this);
oldOne = failedRegistered.putIfAbsent(url, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
private void removeFailedRegistered(URL url) {
FailedRegisteredTask f = failedRegistered.remove(url);
if (f != null) {
f.cancel();
}
}
private void addFailedUnregistered(URL url) {
FailedUnregisteredTask oldOne = failedUnregistered.get(url);
if (oldOne != null) {
return;
}
FailedUnregisteredTask newTask = new FailedUnregisteredTask(url, this);
oldOne = failedUnregistered.putIfAbsent(url, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
private void removeFailedUnregistered(URL url) {
FailedUnregisteredTask f = failedUnregistered.remove(url);
if (f != null) {
f.cancel();
}
}
protected void addFailedSubscribed(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedSubscribedTask oldOne = failedSubscribed.get(h);
if (oldOne != null) {
return;
}
FailedSubscribedTask newTask = new FailedSubscribedTask(url, this, listener);
oldOne = failedSubscribed.putIfAbsent(h, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
public void removeFailedSubscribed(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedSubscribedTask f = failedSubscribed.remove(h);
if (f != null) {
f.cancel();
}
removeFailedUnsubscribed(url, listener);
}
private void addFailedUnsubscribed(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedUnsubscribedTask oldOne = failedUnsubscribed.get(h);
if (oldOne != null) {
return;
}
FailedUnsubscribedTask newTask = new FailedUnsubscribedTask(url, this, listener);
oldOne = failedUnsubscribed.putIfAbsent(h, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
private void removeFailedUnsubscribed(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedUnsubscribedTask f = failedUnsubscribed.remove(h);
if (f != null) {
f.cancel();
}
}
protected URL removeParamsFromConsumer(URL consumer) {
Set<ProviderFirstParams> providerFirstParams = consumer.getOrDefaultApplicationModel()
.getExtensionLoader(ProviderFirstParams.class)
.getSupportedExtensionInstances();
if (CollectionUtils.isEmpty(providerFirstParams)) {
return consumer;
}
for (ProviderFirstParams paramsFilter : providerFirstParams) {
consumer = consumer.removeParameters(paramsFilter.params());
}
return consumer;
}
ConcurrentMap<URL, FailedRegisteredTask> getFailedRegistered() {
return failedRegistered;
}
ConcurrentMap<URL, FailedUnregisteredTask> getFailedUnregistered() {
return failedUnregistered;
}
ConcurrentMap<Holder, FailedSubscribedTask> getFailedSubscribed() {
return failedSubscribed;
}
ConcurrentMap<Holder, FailedUnsubscribedTask> getFailedUnsubscribed() {
return failedUnsubscribed;
}
@Override
public void register(URL url) {
if (!shouldRegister(url)) {
return;
}
super.register(url);
removeFailedRegistered(url);
removeFailedUnregistered(url);
try {
// Sending a registration request to the server side
doRegister(url);
} catch (Exception e) {
Throwable t = e;
// If the startup detection is opened, the Exception is thrown directly.
boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
&& url.getParameter(Constants.CHECK_KEY, true)
&& (url.getPort() != 0);
boolean skipFailback = t instanceof SkipFailbackWrapperException;
if (check || skipFailback) {
if (skipFailback) {
t = t.getCause();
}
throw new IllegalStateException(
"Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: "
+ t.getMessage(),
t);
} else {
logger.error(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(),
t);
}
// Record a failed registration request to a failed list, retry regularly
addFailedRegistered(url);
}
}
protected boolean shouldRegister(URL providerURL) {
// extra protocol url must not be registered for interface based service discovery
if (providerURL.getParameter(IS_EXTRA, false)) {
return false;
}
if (!acceptable(providerURL)) {
logger.info("URL " + providerURL + " will not be registered to Registry. Registry " + this.getUrl()
+ " does not accept service of this protocol type.");
return false;
}
return true;
}
@Override
public void reExportRegister(URL url) {
if (!acceptable(url)) {
logger.info("URL " + url + " will not be registered to Registry. Registry " + url
+ " does not accept service of this protocol type.");
return;
}
super.register(url);
removeFailedRegistered(url);
removeFailedUnregistered(url);
try {
// Sending a registration request to the server side
doRegister(url);
} catch (Exception e) {
if (!(e instanceof SkipFailbackWrapperException)) {
throw new IllegalStateException(
"Failed to register (re-export) " + url + " to registry " + getUrl().getAddress() + ", cause: "
+ e.getMessage(),
e);
}
}
}
@Override
public void unregister(URL url) {
super.unregister(url);
removeFailedRegistered(url);
removeFailedUnregistered(url);
try {
// Sending a cancellation request to the server side
doUnregister(url);
} catch (Exception e) {
Throwable t = e;
// If the startup detection is opened, the Exception is thrown directly.
boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
&& url.getParameter(Constants.CHECK_KEY, true)
&& (url.getPort() != 0);
boolean skipFailback = t instanceof SkipFailbackWrapperException;
if (check || skipFailback) {
if (skipFailback) {
t = t.getCause();
}
throw new IllegalStateException(
"Failed to unregister " + url + " to registry " + getUrl().getAddress() + ", cause: "
+ t.getMessage(),
t);
} else {
logger.error(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Failed to unregister " + url + ", waiting for retry, cause: " + t.getMessage(),
t);
}
// Record a failed registration request to a failed list, retry regularly
addFailedUnregistered(url);
}
}
@Override
public void reExportUnregister(URL url) {
super.unregister(url);
removeFailedRegistered(url);
removeFailedUnregistered(url);
try {
// Sending a cancellation request to the server side
doUnregister(url);
} catch (Exception e) {
if (!(e instanceof SkipFailbackWrapperException)) {
throw new IllegalStateException(
"Failed to unregister(re-export) " + url + " to registry " + getUrl().getAddress() + ", cause: "
+ e.getMessage(),
e);
}
}
}
@Override
public void subscribe(URL url, NotifyListener listener) {
super.subscribe(url, listener);
removeFailedSubscribed(url, listener);
try {
// Sending a subscription request to the server side
doSubscribe(url, listener);
} catch (Exception e) {
Throwable t = e;
List<URL> urls = getCacheUrls(url);
if (CollectionUtils.isNotEmpty(urls)) {
notify(url, listener, urls);
logger.error(
REGISTRY_FAILED_NOTIFY_EVENT,
"",
"",
"Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: "
+ getCacheFile().getName() + ", cause: " + t.getMessage(),
t);
} else {
// If the startup detection is opened, the Exception is thrown directly.
boolean check =
getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true);
boolean skipFailback = t instanceof SkipFailbackWrapperException;
if (check || skipFailback) {
if (skipFailback) {
t = t.getCause();
}
throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t);
} else {
logger.error(
REGISTRY_FAILED_NOTIFY_EVENT,
"",
"",
"Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(),
t);
}
}
// Record a failed registration request to a failed list, retry regularly
addFailedSubscribed(url, listener);
}
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
super.unsubscribe(url, listener);
removeFailedSubscribed(url, listener);
try {
// Sending a canceling subscription request to the server side
doUnsubscribe(url, listener);
} catch (Exception e) {
Throwable t = e;
// If the startup detection is opened, the Exception is thrown directly.
boolean check =
getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true);
boolean skipFailback = t instanceof SkipFailbackWrapperException;
if (check || skipFailback) {
if (skipFailback) {
t = t.getCause();
}
throw new IllegalStateException(
"Failed to unsubscribe " + url + " to registry " + getUrl().getAddress() + ", cause: "
+ t.getMessage(),
t);
} else {
logger.error(
REGISTRY_FAILED_NOTIFY_EVENT,
"",
"",
"Failed to unsubscribe " + url + ", waiting for retry, cause: " + t.getMessage(),
t);
}
// Record a failed registration request to a failed list, retry regularly
addFailedUnsubscribed(url, listener);
}
}
@Override
protected void notify(URL url, NotifyListener listener, List<URL> urls) {
if (url == null) {
throw new IllegalArgumentException("notify url == null");
}
if (listener == null) {
throw new IllegalArgumentException("notify listener == null");
}
try {
doNotify(url, listener, urls);
} catch (Exception t) {
// Record a failed registration request to a failed list
logger.error(
REGISTRY_FAILED_NOTIFY_EVENT,
"",
"",
"Failed to notify addresses for subscribe " + url + ", cause: " + t.getMessage(),
t);
}
}
protected void doNotify(URL url, NotifyListener listener, List<URL> urls) {
super.notify(url, listener, urls);
}
@Override
protected void recover() throws Exception {
// register
Set<URL> recoverRegistered = new HashSet<>(getRegistered());
if (!recoverRegistered.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover register url " + recoverRegistered);
}
for (URL url : recoverRegistered) {
// remove fail registry or unRegistry task first.
removeFailedRegistered(url);
removeFailedUnregistered(url);
addFailedRegistered(url);
}
}
// subscribe
Map<URL, Set<NotifyListener>> recoverSubscribed = new HashMap<>(getSubscribed());
if (!recoverSubscribed.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover subscribe url " + recoverSubscribed.keySet());
}
for (Map.Entry<URL, Set<NotifyListener>> entry : recoverSubscribed.entrySet()) {
URL url = entry.getKey();
for (NotifyListener listener : entry.getValue()) {
// First remove other tasks to ensure that addFailedSubscribed can succeed.
removeFailedSubscribed(url, listener);
addFailedSubscribed(url, listener);
}
}
}
}
@Override
public void destroy() {
super.destroy();
retryTimer.stop();
}
// ==== Template method ====
public abstract void doRegister(URL url);
public abstract void doUnregister(URL url);
public abstract void doSubscribe(URL url, NotifyListener listener);
public abstract void doUnsubscribe(URL url, NotifyListener listener);
static class Holder {
private final URL url;
private final NotifyListener notifyListener;
Holder(URL url, NotifyListener notifyListener) {
if (url == null || notifyListener == null) {
throw new IllegalArgumentException();
}
this.url = url;
this.notifyListener = notifyListener;
}
@Override
public int hashCode() {
return url.hashCode() + notifyListener.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Holder) {
Holder h = (Holder) obj;
return this.url.equals(h.url) && this.notifyListener.equals(h.notifyListener);
} else {
return false;
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java | /*
* 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.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_CREATE_INSTANCE;
import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
/**
* AbstractRegistryFactory. (SPI, Singleton, ThreadSafe)
*
* @see org.apache.dubbo.registry.RegistryFactory
*/
public abstract class AbstractRegistryFactory implements RegistryFactory, ScopeModelAware {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(AbstractRegistryFactory.class);
private RegistryManager registryManager;
protected ApplicationModel applicationModel;
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
this.registryManager = applicationModel.getBeanFactory().getBean(RegistryManager.class);
}
@Override
public Registry getRegistry(URL url) {
if (registryManager == null) {
throw new IllegalStateException("Unable to fetch RegistryManager from ApplicationModel BeanFactory. "
+ "Please check if `setApplicationModel` has been override.");
}
Registry defaultNopRegistry = registryManager.getDefaultNopRegistryIfDestroyed();
if (null != defaultNopRegistry) {
return defaultNopRegistry;
}
url = URLBuilder.from(url)
.setPath(RegistryService.class.getName())
.addParameter(INTERFACE_KEY, RegistryService.class.getName())
.removeParameter(TIMESTAMP_KEY)
.removeAttribute(EXPORT_KEY)
.removeAttribute(REFER_KEY)
.build();
String key = createRegistryCacheKey(url);
Registry registry = null;
boolean check = UrlUtils.isCheck(url);
// Lock the registry access process to ensure a single instance of the registry
registryManager.getRegistryLock().lock();
try {
// double check
// fix https://github.com/apache/dubbo/issues/7265.
defaultNopRegistry = registryManager.getDefaultNopRegistryIfDestroyed();
if (null != defaultNopRegistry) {
return defaultNopRegistry;
}
registry = registryManager.getRegistry(key);
if (registry != null) {
return registry;
}
// create registry by spi/ioc
registry = createRegistry(url);
if (check && registry == null) {
throw new IllegalStateException("Can not create registry " + url);
}
if (registry != null) {
registryManager.putRegistry(key, registry);
}
} catch (Exception e) {
if (check) {
throw new RuntimeException("Can not create registry " + url, e);
} else {
// 1-11 Failed to obtain or create registry (service) object.
LOGGER.warn(REGISTRY_FAILED_CREATE_INSTANCE, "", "", "Failed to obtain or create registry ", e);
}
} finally {
// Release the lock
registryManager.getRegistryLock().unlock();
}
return registry;
}
/**
* Create the key for the registries cache.
* This method may be overridden by the sub-class.
*
* @param url the registration {@link URL url}
* @return non-null
*/
protected String createRegistryCacheKey(URL url) {
return url.toServiceStringWithoutResolving();
}
protected abstract Registry createRegistry(URL url);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/DefaultProviderFirstParams.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/DefaultProviderFirstParams.java | /*
* 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.support;
import org.apache.dubbo.registry.ProviderFirstParams;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
public class DefaultProviderFirstParams implements ProviderFirstParams {
private static final Set<String> PARAMS = Collections.unmodifiableSet(new HashSet<String>() {
{
addAll(Arrays.asList(RELEASE_KEY, DUBBO_VERSION_KEY, METHODS_KEY, TIMESTAMP_KEY, TAG_KEY));
}
});
@Override
public Set<String> params() {
return PARAMS;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java | /*
* 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.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED;
import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.USER_HOME;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DELETE_LOCKFILE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DESTROY_UNREGISTER_URL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_READ_WRITE_CACHE_FILE;
import static org.apache.dubbo.common.constants.RegistryConstants.ACCEPTS_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.registry.Constants.CACHE;
import static org.apache.dubbo.registry.Constants.DUBBO_REGISTRY;
import static org.apache.dubbo.registry.Constants.REGISTRY_FILESAVE_SYNC_KEY;
/**
* <p>
* Provides a fail-safe registry service backed by cache file. The consumer/provider can still find each other when registry center crashed.
* <p>
* (SPI, Prototype, ThreadSafe)
*/
public abstract class AbstractRegistry implements Registry {
// URL address separator, used in file cache, service provider URL separation
private static final char URL_SEPARATOR = ' ';
// URL address separated regular expression for parsing the service provider URL list in the file cache
private static final String URL_SPLIT = "\\s+";
// Max times to retry to save properties to local cache file
private static final int MAX_RETRY_TIMES_SAVE_PROPERTIES = 3;
// Default interval in millisecond for saving properties to local cache file
private static final long DEFAULT_INTERVAL_SAVE_PROPERTIES = 500L;
// Log output
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
// Local disk cache, where the special key value.registries records the list of registry centers, and the others are
// the list of notified service providers
private final Properties properties = new Properties();
// File cache timing writing
private final ScheduledExecutorService registryCacheExecutor;
private final AtomicLong lastCacheChanged = new AtomicLong();
private final AtomicInteger savePropertiesRetryTimes = new AtomicInteger();
private final Set<URL> registered = new ConcurrentHashSet<>();
private final ConcurrentMap<URL, Set<NotifyListener>> subscribed = new ConcurrentHashMap<>();
private final ConcurrentMap<URL, Map<String, List<URL>>> notified = new ConcurrentHashMap<>();
// Is it synchronized to save the file
private boolean syncSaveFile;
private URL registryUrl;
// Local disk cache file
private File file;
private final boolean localCacheEnabled;
protected RegistryManager registryManager;
protected ApplicationModel applicationModel;
private static final String CAUSE_MULTI_DUBBO_USING_SAME_FILE = "multiple Dubbo instance are using the same file";
protected AbstractRegistry(URL url) {
setUrl(url);
registryManager = url.getOrDefaultApplicationModel().getBeanFactory().getBean(RegistryManager.class);
localCacheEnabled = url.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true);
registryCacheExecutor = url.getOrDefaultFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getSharedScheduledExecutor();
if (localCacheEnabled) {
// Start file save timer
syncSaveFile = url.getParameter(REGISTRY_FILESAVE_SYNC_KEY, false);
String defaultFilename = SystemPropertyConfigUtils.getSystemProperty(USER_HOME) + DUBBO_REGISTRY
+ url.getApplication() + "-" + url.getAddress().replaceAll(":", "-") + CACHE;
String filename = url.getParameter(FILE_KEY, defaultFilename);
File file = null;
if (ConfigUtils.isNotEmpty(filename)) {
file = new File(filename);
if (!file.exists()
&& file.getParentFile() != null
&& !file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
IllegalArgumentException illegalArgumentException =
new IllegalArgumentException("Invalid registry cache file " + file
+ ", cause: Failed to create directory " + file.getParentFile() + "!");
if (logger != null) {
// 1-9 failed to read / save registry cache file.
logger.error(
REGISTRY_FAILED_READ_WRITE_CACHE_FILE,
"cache directory inaccessible",
"Try adjusting permission of the directory.",
"failed to create directory",
illegalArgumentException);
}
throw illegalArgumentException;
}
}
}
this.file = file;
// When starting the subscription center,
// we need to read the local cache file for future Registry fault tolerance processing.
loadProperties();
notify(url.getBackupUrls());
}
}
protected static List<URL> filterEmpty(URL url, List<URL> urls) {
if (CollectionUtils.isEmpty(urls)) {
List<URL> result = new ArrayList<>(1);
result.add(url.setProtocol(EMPTY_PROTOCOL));
return result;
}
return urls;
}
@Override
public URL getUrl() {
return registryUrl;
}
protected void setUrl(URL url) {
if (url == null) {
throw new IllegalArgumentException("registry url == null");
}
this.registryUrl = url;
}
public Set<URL> getRegistered() {
return Collections.unmodifiableSet(registered);
}
public Map<URL, Set<NotifyListener>> getSubscribed() {
return Collections.unmodifiableMap(subscribed);
}
public Map<URL, Map<String, List<URL>>> getNotified() {
return Collections.unmodifiableMap(notified);
}
public File getCacheFile() {
return file;
}
public Properties getCacheProperties() {
return properties;
}
public AtomicLong getLastCacheChanged() {
return lastCacheChanged;
}
public void doSaveProperties(long version) {
if (version < lastCacheChanged.get()) {
return;
}
if (file == null) {
return;
}
// Save
File lockfile = null;
try {
lockfile = new File(file.getAbsolutePath() + ".lock");
if (!lockfile.exists()) {
lockfile.createNewFile();
}
try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
FileChannel channel = raf.getChannel()) {
FileLock lock = channel.tryLock();
if (lock == null) {
IOException ioException = new IOException(
"Can not lock the registry cache file " + file.getAbsolutePath() + ", "
+ "ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties");
// 1-9 failed to read / save registry cache file.
logger.warn(
REGISTRY_FAILED_READ_WRITE_CACHE_FILE,
CAUSE_MULTI_DUBBO_USING_SAME_FILE,
"",
"Adjust dubbo.registry.file.",
ioException);
throw ioException;
}
// Save
try {
if (!file.exists()) {
file.createNewFile();
}
Properties tmpProperties;
if (syncSaveFile) {
// When syncReport = true, properties.setProperty and properties.store are called from the same
// thread(reportCacheExecutor), so deep copy is not required
tmpProperties = properties;
} else {
// Using properties.setProperty and properties.store method will cause lock contention
// under multi-threading, so deep copy a new container
tmpProperties = new Properties();
Set<Map.Entry<Object, Object>> entries = properties.entrySet();
for (Map.Entry<Object, Object> entry : entries) {
tmpProperties.setProperty((String) entry.getKey(), (String) entry.getValue());
}
}
try (FileOutputStream outputFile = new FileOutputStream(file)) {
tmpProperties.store(outputFile, "Dubbo Registry Cache");
}
} finally {
lock.release();
}
}
} catch (Throwable e) {
savePropertiesRetryTimes.incrementAndGet();
if (savePropertiesRetryTimes.get() >= MAX_RETRY_TIMES_SAVE_PROPERTIES) {
if (e instanceof OverlappingFileLockException) {
// fix #9341, ignore OverlappingFileLockException
logger.info("Failed to save registry cache file for file overlapping lock exception, file name "
+ file.getName());
} else {
// 1-9 failed to read / save registry cache file.
logger.warn(
REGISTRY_FAILED_READ_WRITE_CACHE_FILE,
CAUSE_MULTI_DUBBO_USING_SAME_FILE,
"",
"Failed to save registry cache file after retrying " + MAX_RETRY_TIMES_SAVE_PROPERTIES
+ " times, cause: " + e.getMessage(),
e);
}
savePropertiesRetryTimes.set(0);
return;
}
if (version < lastCacheChanged.get()) {
savePropertiesRetryTimes.set(0);
return;
} else {
registryCacheExecutor.schedule(
() -> doSaveProperties(lastCacheChanged.incrementAndGet()),
DEFAULT_INTERVAL_SAVE_PROPERTIES,
TimeUnit.MILLISECONDS);
}
if (!(e instanceof OverlappingFileLockException)) {
logger.warn(
REGISTRY_FAILED_READ_WRITE_CACHE_FILE,
CAUSE_MULTI_DUBBO_USING_SAME_FILE,
"However, the retrying count limit is not exceeded. Dubbo will still try.",
"Failed to save registry cache file, will retry, cause: " + e.getMessage(),
e);
}
} finally {
if (lockfile != null) {
if (!lockfile.delete()) {
// 1-10 Failed to delete lock file.
logger.warn(
REGISTRY_FAILED_DELETE_LOCKFILE,
"",
"",
String.format("Failed to delete lock file [%s]", lockfile.getName()));
}
}
}
}
private void loadProperties() {
if (file == null || !file.exists()) {
return;
}
try (InputStream in = Files.newInputStream(file.toPath())) {
properties.load(in);
if (logger.isInfoEnabled()) {
logger.info("Loaded registry cache file " + file);
}
} catch (IOException e) {
// 1-9 failed to read / save registry cache file.
logger.warn(
REGISTRY_FAILED_READ_WRITE_CACHE_FILE, CAUSE_MULTI_DUBBO_USING_SAME_FILE, "", e.getMessage(), e);
} catch (Throwable e) {
// 1-9 failed to read / save registry cache file.
logger.warn(
REGISTRY_FAILED_READ_WRITE_CACHE_FILE,
CAUSE_MULTI_DUBBO_USING_SAME_FILE,
"",
"Failed to load registry cache file " + file,
e);
}
}
public List<URL> getCacheUrls(URL url) {
Map<String, List<URL>> categoryNotified = notified.get(url);
if (CollectionUtils.isNotEmptyMap(categoryNotified)) {
List<URL> urls = categoryNotified.values().stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
return urls;
}
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (StringUtils.isNotEmpty(key)
&& key.equals(url.getServiceKey())
&& (Character.isLetter(key.charAt(0)) || key.charAt(0) == '_')
&& StringUtils.isNotEmpty(value)) {
String[] arr = value.trim().split(URL_SPLIT);
List<URL> urls = new ArrayList<>();
for (String u : arr) {
urls.add(URL.valueOf(u));
}
return urls;
}
}
return null;
}
@Override
public List<URL> lookup(URL url) {
List<URL> result = new ArrayList<>();
Map<String, List<URL>> notifiedUrls = getNotified().get(url);
if (CollectionUtils.isNotEmptyMap(notifiedUrls)) {
for (List<URL> urls : notifiedUrls.values()) {
for (URL u : urls) {
if (!EMPTY_PROTOCOL.equals(u.getProtocol())) {
result.add(u);
}
}
}
} else {
final AtomicReference<List<URL>> reference = new AtomicReference<>();
NotifyListener listener = reference::set;
subscribe(url, listener); // Subscribe logic guarantees the first notify to return
List<URL> urls = reference.get();
if (CollectionUtils.isNotEmpty(urls)) {
for (URL u : urls) {
if (!EMPTY_PROTOCOL.equals(u.getProtocol())) {
result.add(u);
}
}
}
}
return result;
}
@Override
public void register(URL url) {
if (url == null) {
throw new IllegalArgumentException("register url == null");
}
if (url.getPort() != 0) {
if (logger.isInfoEnabled()) {
logger.info("Register: " + url);
}
}
registered.add(url);
}
@Override
public void unregister(URL url) {
if (url == null) {
throw new IllegalArgumentException("unregister url == null");
}
if (url.getPort() != 0) {
if (logger.isInfoEnabled()) {
logger.info("Unregister: " + url);
}
}
registered.remove(url);
}
@Override
public void subscribe(URL url, NotifyListener listener) {
if (url == null) {
throw new IllegalArgumentException("subscribe url == null");
}
if (listener == null) {
throw new IllegalArgumentException("subscribe listener == null");
}
if (logger.isInfoEnabled()) {
logger.info("Subscribe: " + url);
}
Set<NotifyListener> listeners =
ConcurrentHashMapUtils.computeIfAbsent(subscribed, url, n -> new ConcurrentHashSet<>());
listeners.add(listener);
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
if (url == null) {
throw new IllegalArgumentException("unsubscribe url == null");
}
if (listener == null) {
throw new IllegalArgumentException("unsubscribe listener == null");
}
if (logger.isInfoEnabled()) {
logger.info("Unsubscribe: " + url);
}
Set<NotifyListener> listeners = subscribed.get(url);
if (listeners != null) {
listeners.remove(listener);
}
// do not forget remove notified
notified.remove(url);
}
protected void recover() throws Exception {
// register
Set<URL> recoverRegistered = new HashSet<>(getRegistered());
if (!recoverRegistered.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover register url " + recoverRegistered);
}
for (URL url : recoverRegistered) {
register(url);
}
}
// subscribe
Map<URL, Set<NotifyListener>> recoverSubscribed = new HashMap<>(getSubscribed());
if (!recoverSubscribed.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover subscribe url " + recoverSubscribed.keySet());
}
for (Map.Entry<URL, Set<NotifyListener>> entry : recoverSubscribed.entrySet()) {
URL url = entry.getKey();
for (NotifyListener listener : entry.getValue()) {
subscribe(url, listener);
}
}
}
}
protected void notify(List<URL> urls) {
if (CollectionUtils.isEmpty(urls)) {
return;
}
for (Map.Entry<URL, Set<NotifyListener>> entry : getSubscribed().entrySet()) {
URL url = entry.getKey();
if (!UrlUtils.isMatch(url, urls.get(0))) {
continue;
}
Set<NotifyListener> listeners = entry.getValue();
if (listeners != null) {
for (NotifyListener listener : listeners) {
try {
notify(url, listener, filterEmpty(url, urls));
} catch (Throwable t) {
// 1-7: Failed to notify registry event.
logger.error(
REGISTRY_FAILED_NOTIFY_EVENT,
"consumer is offline",
"",
"Failed to notify registry event, urls: " + urls + ", cause: " + t.getMessage(),
t);
}
}
}
}
}
/**
* Notify changes from the provider side.
*
* @param url consumer side url
* @param listener listener
* @param urls provider latest urls
*/
protected void notify(URL url, NotifyListener listener, List<URL> urls) {
if (url == null) {
throw new IllegalArgumentException("notify url == null");
}
if (listener == null) {
throw new IllegalArgumentException("notify listener == null");
}
if ((CollectionUtils.isEmpty(urls)) && !ANY_VALUE.equals(url.getServiceInterface())) {
// 1-4 Empty address.
logger.warn(REGISTRY_EMPTY_ADDRESS, "", "", "Ignore empty notify urls for subscribe url " + url);
return;
}
if (logger.isInfoEnabled()) {
logger.info("[INSTANCE_REGISTER] Notify urls for subscribe url " + url + ", url size: " + urls.size());
}
// keep every provider's category.
Map<String, List<URL>> result = new HashMap<>();
for (URL u : urls) {
if (UrlUtils.isMatch(url, u)) {
String category = u.getCategory(DEFAULT_CATEGORY);
List<URL> categoryList = result.computeIfAbsent(category, k -> new ArrayList<>());
categoryList.add(u);
}
}
if (result.size() == 0) {
return;
}
Map<String, List<URL>> categoryNotified =
ConcurrentHashMapUtils.computeIfAbsent(notified, url, u -> new ConcurrentHashMap<>());
for (Map.Entry<String, List<URL>> entry : result.entrySet()) {
String category = entry.getKey();
List<URL> categoryList = entry.getValue();
categoryNotified.put(category, categoryList);
listener.notify(categoryList);
// We will update our cache file after each notification.
// When our Registry has a subscribed failure due to network jitter, we can return at least the existing
// cache URL.
if (localCacheEnabled) {
saveProperties(url);
}
}
}
private void saveProperties(URL url) {
if (file == null) {
return;
}
try {
StringBuilder buf = new StringBuilder();
Map<String, List<URL>> categoryNotified = notified.get(url);
if (categoryNotified != null) {
for (List<URL> us : categoryNotified.values()) {
for (URL u : us) {
if (buf.length() > 0) {
buf.append(URL_SEPARATOR);
}
buf.append(u.toFullString());
}
}
}
properties.setProperty(url.getServiceKey(), buf.toString());
long version = lastCacheChanged.incrementAndGet();
if (syncSaveFile) {
doSaveProperties(version);
} else {
registryCacheExecutor.schedule(
() -> doSaveProperties(version), DEFAULT_INTERVAL_SAVE_PROPERTIES, TimeUnit.MILLISECONDS);
}
} catch (Throwable t) {
logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", t.getMessage(), t);
}
}
@Override
public void destroy() {
if (logger.isInfoEnabled()) {
logger.info("Destroy registry:" + getUrl());
}
Set<URL> destroyRegistered = new HashSet<>(getRegistered());
if (!destroyRegistered.isEmpty()) {
for (URL url : new HashSet<>(destroyRegistered)) {
if (url.getParameter(DYNAMIC_KEY, true)) {
try {
unregister(url);
if (logger.isInfoEnabled()) {
logger.info("Destroy unregister url " + url);
}
} catch (Throwable t) {
// 1-8: Failed to unregister / unsubscribe url on destroy.
logger.warn(
REGISTRY_FAILED_DESTROY_UNREGISTER_URL,
"",
"",
"Failed to unregister url " + url + " to registry " + getUrl() + " on destroy, cause: "
+ t.getMessage(),
t);
}
}
}
}
Map<URL, Set<NotifyListener>> destroySubscribed = new HashMap<>(getSubscribed());
if (!destroySubscribed.isEmpty()) {
for (Map.Entry<URL, Set<NotifyListener>> entry : destroySubscribed.entrySet()) {
URL url = entry.getKey();
for (NotifyListener listener : entry.getValue()) {
try {
unsubscribe(url, listener);
if (logger.isInfoEnabled()) {
logger.info("Destroy unsubscribe url " + url);
}
} catch (Throwable t) {
// 1-8: Failed to unregister / unsubscribe url on destroy.
logger.warn(
REGISTRY_FAILED_DESTROY_UNREGISTER_URL,
"",
"",
"Failed to unsubscribe url " + url + " to registry " + getUrl() + " on destroy, cause: "
+ t.getMessage(),
t);
}
}
}
}
registryManager.removeDestroyedRegistry(this);
}
protected boolean acceptable(URL urlToRegistry) {
String pattern = registryUrl.getParameter(ACCEPTS_KEY);
if (StringUtils.isEmpty(pattern)) {
return true;
}
String[] accepts = COMMA_SPLIT_PATTERN.split(pattern);
Set<String> allow =
Arrays.stream(accepts).filter(p -> !p.startsWith("-")).collect(Collectors.toSet());
Set<String> disAllow = Arrays.stream(accepts)
.filter(p -> p.startsWith("-"))
.map(p -> p.substring(1))
.collect(Collectors.toSet());
if (CollectionUtils.isNotEmpty(allow)) {
// allow first
return allow.contains(urlToRegistry.getProtocol());
} else if (CollectionUtils.isNotEmpty(disAllow)) {
// contains disAllow, deny
return !disAllow.contains(urlToRegistry.getProtocol());
} else {
// default allow
return true;
}
}
@Override
public String toString() {
return getUrl().toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/InterfaceCompatibleRegistryProtocol.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/InterfaceCompatibleRegistryProtocol.java | /*
* 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.registry.Registry;
import org.apache.dubbo.registry.client.ServiceDiscoveryRegistryDirectory;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
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.registry.Constants.DEFAULT_REGISTRY;
/**
* RegistryProtocol
*/
public class InterfaceCompatibleRegistryProtocol extends RegistryProtocol {
@Override
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;
}
@Override
protected URL getRegistryUrl(URL url) {
return URLBuilder.from(url)
.setProtocol(url.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY))
.removeParameter(REGISTRY_KEY)
.build();
}
@Override
public <T> ClusterInvoker<T> getInvoker(Cluster cluster, Registry registry, Class<T> type, URL url) {
DynamicDirectory<T> directory = new RegistryDirectory<>(type, url);
return doCreateInvoker(directory, cluster, registry, type);
}
@Override
public <T> ClusterInvoker<T> getServiceDiscoveryInvoker(
Cluster cluster, Registry registry, Class<T> type, URL url) {
registry = getRegistry(super.getRegistryUrl(url));
DynamicDirectory<T> directory = new ServiceDiscoveryRegistryDirectory<>(type, url);
return doCreateInvoker(directory, cluster, registry, type);
}
@Override
protected <T> ClusterInvoker<T> getMigrationInvoker(
RegistryProtocol registryProtocol,
Cluster cluster,
Registry registry,
Class<T> type,
URL url,
URL consumerUrl) {
// ClusterInvoker<T> invoker = getInvoker(cluster, registry, type, url);
return new MigrationInvoker<>(registryProtocol, cluster, registry, type, url, consumerUrl);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java | /*
* 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.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.timer.HashedWheelTimer;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
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.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.registry.event.RegistryEvent;
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.client.ServiceDiscoveryRegistryDirectory;
import org.apache.dubbo.registry.client.migration.MigrationClusterInvoker;
import org.apache.dubbo.registry.client.migration.ServiceDiscoveryMigrationInvoker;
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.Constants;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.protocol.InvokerWrapper;
import org.apache.dubbo.rpc.support.ProtocolUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
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.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_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.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.IPV6_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MERGEABLE_CLUSTER_NAME;
import static org.apache.dubbo.common.constants.CommonConstants.PACKABLE_METHOD_FACTORY_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PASSWORD_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.common.constants.CommonConstants.REGISTRY_PROTOCOL_LISTENER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_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.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNSUPPORTED_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.ALL_CATEGORIES;
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.DYNAMIC_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_PROTOCOL;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
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.DEFAULT_REGISTRY_RETRY_PERIOD;
import static org.apache.dubbo.registry.Constants.ENABLE_26X_CONFIGURATION_LISTEN;
import static org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN;
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.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.PREFER_SERIALIZATION_KEY;
import static org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY;
import static org.apache.dubbo.rpc.Constants.AUTHENTICATOR_KEY;
import static org.apache.dubbo.rpc.Constants.AUTH_KEY;
import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY;
import static org.apache.dubbo.rpc.Constants.GENERIC_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.CONSUMER_URL_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;
import static org.apache.dubbo.rpc.model.ScopeModelUtil.getApplicationModel;
/**
* TODO, replace RegistryProtocol completely in the future.
*/
public class RegistryProtocol implements Protocol, ScopeModelAware {
public static final String[] DEFAULT_REGISTER_PROVIDER_KEYS = {
APPLICATION_KEY,
CODEC_KEY,
EXCHANGER_KEY,
SERIALIZATION_KEY,
PREFER_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,
SIDE_KEY,
IPV6_KEY,
PACKABLE_METHOD_FACTORY_KEY,
AUTH_KEY,
AUTHENTICATOR_KEY,
USERNAME_KEY,
PASSWORD_KEY
};
public static final String[] DEFAULT_REGISTER_CONSUMER_KEYS = {
APPLICATION_KEY, VERSION_KEY, GROUP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY
};
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RegistryProtocol.class);
private final Map<String, ServiceConfigurationListener> serviceConfigurationListeners = new ConcurrentHashMap<>();
// To solve the problem of RMI repeated exposure port conflicts, the services that have been exposed are no longer
// exposed.
// provider url <--> registry url <--> exporter
private final ConcurrentHashMap<String, ConcurrentHashMap<String, ExporterChangeableWrapper<?>>> bounds =
new ConcurrentHashMap<>();
protected Protocol protocol;
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);
private FrameworkModel frameworkModel;
private ExporterFactory exporterFactory;
public RegistryProtocol() {}
@Override
public void setFrameworkModel(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
this.exporterFactory = frameworkModel.getBeanFactory().getBean(ExporterFactory.class);
}
public void setProtocol(Protocol protocol) {
this.protocol = protocol;
}
public void setProxyFactory(ProxyFactory proxyFactory) {
this.proxyFactory = proxyFactory;
}
@Override
public int getDefaultPort() {
return 9090;
}
public Map<URL, Set<NotifyListener>> getOverrideListeners() {
Map<URL, Set<NotifyListener>> map = new HashMap<>();
List<ApplicationModel> applicationModels = frameworkModel.getApplicationModels();
if (applicationModels.size() == 1) {
return applicationModels
.get(0)
.getBeanFactory()
.getBean(ProviderConfigurationListener.class)
.getOverrideListeners();
} else {
for (ApplicationModel applicationModel : applicationModels) {
map.putAll(applicationModel
.getBeanFactory()
.getBean(ProviderConfigurationListener.class)
.getOverrideListeners());
}
}
return map;
}
private static void register(Registry registry, URL registeredProviderUrl) {
ApplicationDeployer deployer =
registeredProviderUrl.getOrDefaultApplicationModel().getDeployer();
try {
deployer.increaseServiceRefreshCount();
String registryName = Optional.ofNullable(registry.getUrl())
.map(u -> u.getParameter(
RegistryConstants.REGISTRY_CLUSTER_KEY,
UrlUtils.isServiceDiscoveryURL(u) ? u.getParameter(REGISTRY_KEY) : u.getProtocol()))
.filter(StringUtils::isNotEmpty)
.orElse("unknown");
MetricsEventBus.post(
RegistryEvent.toRsEvent(
registeredProviderUrl.getApplicationModel(),
registeredProviderUrl.getServiceKey(),
1,
Collections.singletonList(registryName)),
() -> {
registry.register(registeredProviderUrl);
return null;
});
} finally {
deployer.decreaseServiceRefreshCount();
}
}
private void registerStatedUrl(URL registryUrl, URL registeredProviderUrl, boolean registered) {
ProviderModel model = (ProviderModel) registeredProviderUrl.getServiceModel();
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);
ConcurrentHashMap<URL, Set<NotifyListener>> overrideListeners =
getProviderConfigurationListener(overrideSubscribeUrl).getOverrideListeners();
ConcurrentHashMapUtils.computeIfAbsent(overrideListeners, overrideSubscribeUrl, k -> new ConcurrentHashSet<>())
.add(overrideSubscribeListener);
providerUrl = overrideUrlWithConfig(providerUrl, overrideSubscribeListener);
// export invoker
final ExporterChangeableWrapper<T> exporter = doLocalExport(originInvoker, providerUrl);
// url to registry
final Registry registry = getRegistry(registryUrl);
final URL registeredProviderUrl = customizeURL(providerUrl, registryUrl);
// decide if we need to delay publish (provider itself and registry should both need to register)
boolean register = providerUrl.getParameter(REGISTER_KEY, true) && registryUrl.getParameter(REGISTER_KEY, true);
if (register) {
register(registry, registeredProviderUrl);
}
// register stated url on provider model
registerStatedUrl(registryUrl, registeredProviderUrl, register);
exporter.setRegisterUrl(registeredProviderUrl);
exporter.setSubscribeUrl(overrideSubscribeUrl);
exporter.setNotifyListener(overrideSubscribeListener);
exporter.setRegistered(register);
ApplicationModel applicationModel = getApplicationModel(providerUrl.getScopeModel());
if (applicationModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, ENABLE_26X_CONFIGURATION_LISTEN, true)) {
if (!registry.isServiceDiscovery()) {
// 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) {
ScopeModel scopeModel = exporter.getRegisterUrl().getScopeModel();
List<RegistryProtocolListener> listeners = ScopeModelUtil.getExtensionLoader(
RegistryProtocolListener.class, scopeModel)
.getActivateExtension(exporter.getOriginInvoker().getUrl(), REGISTRY_PROTOCOL_LISTENER_KEY);
if (CollectionUtils.isNotEmpty(listeners)) {
for (RegistryProtocolListener listener : listeners) {
listener.onExport(this, exporter);
}
}
}
private URL overrideUrlWithConfig(URL providerUrl, OverrideListener listener) {
ProviderConfigurationListener providerConfigurationListener = getProviderConfigurationListener(providerUrl);
providerUrl = providerConfigurationListener.overrideUrl(providerUrl);
ServiceConfigurationListener serviceConfigurationListener =
new ServiceConfigurationListener(providerUrl.getOrDefaultModuleModel(), 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 providerUrlKey = getProviderUrlKey(originInvoker);
String registryUrlKey = getRegistryUrlKey(originInvoker);
Invoker<?> invokerDelegate = new InvokerDelegate<>(originInvoker, providerUrl);
ReferenceCountExporter<?> exporter =
exporterFactory.createExporter(providerUrlKey, () -> protocol.export(invokerDelegate));
return (ExporterChangeableWrapper<T>) ConcurrentHashMapUtils.computeIfAbsent(
ConcurrentHashMapUtils.computeIfAbsent(bounds, providerUrlKey, k -> new ConcurrentHashMap<>()),
registryUrlKey,
s -> new ExporterChangeableWrapper<>((ReferenceCountExporter<T>) exporter, 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 providerUrlKey = getProviderUrlKey(originInvoker);
String registryUrlKey = getRegistryUrlKey(originInvoker);
Map<String, ExporterChangeableWrapper<?>> registryMap = bounds.get(providerUrlKey);
if (registryMap == null) {
logger.warn(
INTERNAL_ERROR,
"error state, exporterMap can not be null",
"",
"error state, exporterMap can not be null",
new IllegalStateException("error state, exporterMap can not be null"));
return;
}
ExporterChangeableWrapper<T> exporter = (ExporterChangeableWrapper<T>) registryMap.get(registryUrlKey);
if (exporter == null) {
logger.warn(
INTERNAL_ERROR,
"error state, exporterMap can not be null",
"",
"error state, exporterMap can not be null",
new IllegalStateException("error state, exporterMap can not be null"));
return;
}
URL registeredUrl = exporter.getRegisterUrl();
URL registryUrl = getRegistryUrl(originInvoker);
URL newProviderUrl = customizeURL(newInvokerUrl, registryUrl);
// update local exporter
Invoker<T> invokerDelegate = new InvokerDelegate<>(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 (exporter.isRegistered()) {
Registry registry;
try {
registry = getRegistry(getRegistryUrl(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 =
frameworkModel.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 registryUrl
* @return
*/
protected Registry getRegistry(final URL registryUrl) {
RegistryFactory registryFactory = ScopeModelUtil.getExtensionLoader(
RegistryFactory.class, registryUrl.getScopeModel())
.getAdaptiveExtension();
return registryFactory.getRegistry(registryUrl);
}
protected URL getRegistryUrl(Invoker<?> originInvoker) {
return originInvoker.getUrl();
}
protected URL getRegistryUrl(URL url) {
if (SERVICE_REGISTRY_PROTOCOL.equals(url.getProtocol())) {
return url;
}
return url.addParameter(REGISTRY_KEY, url.getProtocol()).setProtocol(SERVICE_REGISTRY_PROTOCOL);
}
/**
* Return the url that is registered to the registry and filter the url parameter once
*
* @param providerUrl provider service url
* @param registryUrl registry center url
* @return url to registry.
*/
private URL customizeURL(final URL providerUrl, final URL registryUrl) {
URL newProviderURL = providerUrl.putAttribute(SIMPLIFIED_KEY, registryUrl.getParameter(SIMPLIFIED_KEY, false));
newProviderURL = newProviderURL.putAttribute(EXTRA_KEYS_KEY, registryUrl.getParameter(EXTRA_KEYS_KEY, ""));
ApplicationModel applicationModel = providerUrl.getOrDefaultApplicationModel();
ExtensionLoader<ServiceURLCustomizer> loader = applicationModel.getExtensionLoader(ServiceURLCustomizer.class);
for (ServiceURLCustomizer customizer : loader.getSupportedExtensionInstances()) {
newProviderURL = customizer.customize(newProviderURL, applicationModel);
}
return newProviderURL;
}
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) {
Object providerURL = originInvoker.getUrl().getAttribute(EXPORT_KEY);
if (!(providerURL instanceof URL)) {
throw new IllegalArgumentException("The registry export url is null! registry: "
+ originInvoker.getUrl().getAddress());
}
return (URL) providerURL;
}
/**
* Get the key cached in bounds by invoker
*
* @param originInvoker
* @return
*/
private String getProviderUrlKey(final Invoker<?> originInvoker) {
URL providerUrl = getProviderUrl(originInvoker);
return providerUrl.removeParameters(DYNAMIC_KEY, ENABLED_KEY).toFullString();
}
private String getRegistryUrlKey(final Invoker<?> originInvoker) {
URL registryUrl = getRegistryUrl(originInvoker);
return registryUrl.removeParameters(DYNAMIC_KEY, ENABLED_KEY).toFullString();
}
@Override
@SuppressWarnings("unchecked")
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
url = getRegistryUrl(url);
Registry registry = getRegistry(url);
if (RegistryService.class.equals(type)) {
return proxyFactory.getInvoker((T) registry, type, url);
}
// group="a,b" or group="*"
Map<String, String> qs = (Map<String, String>) url.getAttribute(REFER_KEY);
String group = qs.get(GROUP_KEY);
if (StringUtils.isNotEmpty(group)) {
if ((COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) {
return doRefer(
Cluster.getCluster(url.getScopeModel(), MERGEABLE_CLUSTER_NAME), registry, type, url, qs);
}
}
Cluster cluster = Cluster.getCluster(url.getScopeModel(), qs.get(CLUSTER_KEY));
return doRefer(cluster, registry, type, url, qs);
}
protected <T> Invoker<T> doRefer(
Cluster cluster, Registry registry, Class<T> type, URL url, Map<String, String> parameters) {
Map<String, Object> consumerAttribute = new HashMap<>(url.getAttributes());
consumerAttribute.remove(REFER_KEY);
String p = isEmpty(parameters.get(PROTOCOL_KEY)) ? CONSUMER : parameters.get(PROTOCOL_KEY);
URL consumerUrl = new ServiceConfigURL(
p,
null,
null,
parameters.get(REGISTER_IP_KEY),
0,
getPath(parameters, type),
parameters,
consumerAttribute);
url = url.putAttribute(CONSUMER_URL_KEY, consumerUrl);
ClusterInvoker<T> migrationInvoker = getMigrationInvoker(this, cluster, registry, type, url, consumerUrl);
return interceptInvoker(migrationInvoker, url, consumerUrl);
}
private String getPath(Map<String, String> parameters, Class<?> type) {
return !ProtocolUtils.isGeneric(parameters.get(GENERIC_KEY)) ? type.getName() : parameters.get(INTERFACE_KEY);
}
protected <T> ClusterInvoker<T> getMigrationInvoker(
RegistryProtocol registryProtocol,
Cluster cluster,
Registry registry,
Class<T> type,
URL url,
URL consumerUrl) {
return new ServiceDiscoveryMigrationInvoker<>(registryProtocol, cluster, registry, type, url, consumerUrl);
}
/**
* This method tries to load all RegistryProtocolListener definitions, which are used to control the behaviour of invoker by interacting with defined, then uses those listeners to
* change the status and behaviour of the MigrationInvoker.
* <p>
* Currently available Listener is MigrationRuleListener, one used to control the Migration behaviour with dynamically changing rules.
*
* @param invoker MigrationInvoker that determines which type of invoker list to use
* @param url The original url generated during refer, more like a registry:// style url
* @param consumerUrl Consumer url representing current interface and its config
* @param <T> The service definition
* @return The @param MigrationInvoker passed in
*/
protected <T> Invoker<T> interceptInvoker(ClusterInvoker<T> invoker, URL url, URL consumerUrl) {
List<RegistryProtocolListener> listeners = findRegistryProtocolListeners(url);
if (CollectionUtils.isEmpty(listeners)) {
return invoker;
}
for (RegistryProtocolListener listener : listeners) {
listener.onRefer(this, invoker, consumerUrl, url);
}
return invoker;
}
public <T> ClusterInvoker<T> getServiceDiscoveryInvoker(
Cluster cluster, Registry registry, Class<T> type, URL url) {
DynamicDirectory<T> directory = new ServiceDiscoveryRegistryDirectory<>(type, url);
return doCreateInvoker(directory, cluster, registry, type);
}
public <T> ClusterInvoker<T> getInvoker(Cluster cluster, Registry registry, Class<T> type, URL url) {
// FIXME, this method is currently not used, create the right registry before enable.
DynamicDirectory<T> directory = new RegistryDirectory<>(type, url);
return doCreateInvoker(directory, cluster, registry, type);
}
protected <T> ClusterInvoker<T> doCreateInvoker(
DynamicDirectory<T> directory, Cluster cluster, Registry registry, Class<T> type) {
directory.setRegistry(registry);
directory.setProtocol(protocol);
// all attributes of REFER_KEY
Map<String, String> parameters =
new HashMap<>(directory.getConsumerUrl().getParameters());
URL urlToRegistry = new ServiceConfigURL(
parameters.get(PROTOCOL_KEY) == null ? CONSUMER : parameters.get(PROTOCOL_KEY),
parameters.remove(REGISTER_IP_KEY),
0,
getPath(parameters, type),
parameters);
urlToRegistry = urlToRegistry.setScopeModel(directory.getConsumerUrl().getScopeModel());
urlToRegistry = urlToRegistry.setServiceModel(directory.getConsumerUrl().getServiceModel());
if (directory.isShouldRegister()) {
directory.setRegisteredConsumerUrl(urlToRegistry);
registry.register(directory.getRegisteredConsumerUrl());
}
directory.buildRouterChain(urlToRegistry);
directory.subscribe(toSubscribeUrl(urlToRegistry));
return (ClusterInvoker<T>) cluster.join(directory, true);
}
public <T> void reRefer(ClusterInvoker<?> invoker, URL newSubscribeUrl) {
if (!(invoker instanceof MigrationClusterInvoker)) {
logger.error(
REGISTRY_UNSUPPORTED_CATEGORY,
"",
"",
"Only invoker type of MigrationClusterInvoker supports reRefer, current invoker is "
+ invoker.getClass());
return;
}
MigrationClusterInvoker<?> migrationClusterInvoker = (MigrationClusterInvoker<?>) invoker;
migrationClusterInvoker.reRefer(newSubscribeUrl);
}
public static URL toSubscribeUrl(URL url) {
return url.addParameter(CATEGORY_KEY, ALL_CATEGORIES);
}
protected List<RegistryProtocolListener> findRegistryProtocolListeners(URL url) {
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ReferenceCountExporter.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ReferenceCountExporter.java | /*
* 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.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import java.util.concurrent.atomic.AtomicInteger;
public class ReferenceCountExporter<T> implements Exporter<T> {
private final Exporter<T> exporter;
private final String providerKey;
private final ExporterFactory exporterFactory;
private final AtomicInteger count = new AtomicInteger(0);
public ReferenceCountExporter(Exporter<T> exporter, String providerKey, ExporterFactory exporterFactory) {
this.exporter = exporter;
this.providerKey = providerKey;
this.exporterFactory = exporterFactory;
}
@Override
public Invoker<T> getInvoker() {
return exporter.getInvoker();
}
public void increaseCount() {
count.incrementAndGet();
}
@Override
public void unexport() {
if (count.decrementAndGet() == 0) {
exporter.unexport();
}
exporterFactory.remove(providerKey, this);
}
@Override
public void register() {}
@Override
public void unregister() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DynamicDirectory.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DynamicDirectory.java | /*
* 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.Version;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.AddressListener;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.registry.client.migration.InvokersChangedListener;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
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.Constants;
import org.apache.dubbo.rpc.cluster.RouterChain;
import org.apache.dubbo.rpc.cluster.RouterFactory;
import org.apache.dubbo.rpc.cluster.SingleRouterChain;
import org.apache.dubbo.rpc.cluster.directory.AbstractDirectory;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_SITE_SELECTION;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DESTROY_SERVICE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DESTROY_UNREGISTER_URL;
import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY;
import static org.apache.dubbo.registry.Constants.REGISTER_KEY;
import static org.apache.dubbo.registry.Constants.SIMPLIFIED_KEY;
import static org.apache.dubbo.registry.integration.InterfaceCompatibleRegistryProtocol.DEFAULT_REGISTER_CONSUMER_KEYS;
import static org.apache.dubbo.remoting.Constants.CHECK_KEY;
/**
* DynamicDirectory
*/
public abstract class DynamicDirectory<T> extends AbstractDirectory<T> implements NotifyListener {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DynamicDirectory.class);
protected final Cluster cluster;
protected final RouterFactory routerFactory;
/**
* Initialization at construction time, assertion not null
*/
protected final String serviceKey;
/**
* Initialization at construction time, assertion not null
*/
protected final Class<T> serviceType;
/**
* Initialization at construction time, assertion not null, and always assign non-null value
*/
protected volatile URL directoryUrl;
protected final boolean multiGroup;
/**
* Initialization at the time of injection, the assertion is not null
*/
protected Protocol protocol;
/**
* Initialization at the time of injection, the assertion is not null
*/
protected Registry registry;
protected volatile boolean forbidden = false;
protected boolean shouldRegister;
protected boolean shouldSimplified;
/**
* Initialization at construction time, assertion not null, and always assign not null value
*/
protected volatile URL subscribeUrl;
protected volatile URL registeredConsumerUrl;
/**
* The initial value is null and the midway may be assigned to null, please use the local variable reference
* override rules
* Priority: override>-D>consumer>provider
* Rule one: for a certain provider <ip:port,timeout=100>
* Rule two: for all providers <* ,timeout=5000>
*/
protected volatile List<Configurator> configurators;
protected ServiceInstancesChangedListener serviceListener;
/**
* Should continue route if directory is empty
*/
private final boolean shouldFailFast;
private volatile InvokersChangedListener invokersChangedListener;
private volatile boolean invokersChanged;
public DynamicDirectory(Class<T> serviceType, URL url) {
super(url, true);
ModuleModel moduleModel = url.getOrDefaultModuleModel();
this.cluster = moduleModel.getExtensionLoader(Cluster.class).getAdaptiveExtension();
this.routerFactory = moduleModel.getExtensionLoader(RouterFactory.class).getAdaptiveExtension();
if (serviceType == null) {
throw new IllegalArgumentException("service type is null.");
}
if (StringUtils.isEmpty(url.getServiceKey())) {
throw new IllegalArgumentException("registry serviceKey is null.");
}
this.shouldRegister = !ANY_VALUE.equals(url.getServiceInterface()) && url.getParameter(REGISTER_KEY, true);
this.shouldSimplified = url.getParameter(SIMPLIFIED_KEY, false);
this.serviceType = serviceType;
this.serviceKey = super.getConsumerUrl().getServiceKey();
this.directoryUrl = consumerUrl;
String group = directoryUrl.getGroup("");
this.multiGroup = group != null && (ANY_VALUE.equals(group) || group.contains(","));
this.shouldFailFast = Boolean.parseBoolean(
ConfigurationUtils.getProperty(moduleModel, Constants.SHOULD_FAIL_FAST_KEY, "true"));
}
@Override
public void addServiceListener(ServiceInstancesChangedListener instanceListener) {
this.serviceListener = instanceListener;
}
@Override
public ServiceInstancesChangedListener getServiceListener() {
return this.serviceListener;
}
public void setProtocol(Protocol protocol) {
this.protocol = protocol;
}
public void setRegistry(Registry registry) {
this.registry = registry;
}
public Registry getRegistry() {
return registry;
}
public boolean isShouldRegister() {
return shouldRegister;
}
public void subscribe(URL url) {
setSubscribeUrl(url);
registry.subscribe(url, this);
}
public void unSubscribe(URL url) {
setSubscribeUrl(null);
registry.unsubscribe(url, this);
}
@Override
public List<Invoker<T>> doList(
SingleRouterChain<T> singleRouterChain, BitList<Invoker<T>> invokers, Invocation invocation) {
if (forbidden && shouldFailFast) {
// 1. No service provider 2. Service providers are disabled
throw new RpcException(
RpcException.FORBIDDEN_EXCEPTION,
"No provider available from registry " + this
+ " for service " + getConsumerUrl().getServiceKey() + " on consumer "
+ NetUtils.getLocalHost()
+ " use dubbo version " + Version.getVersion()
+ ", please check status of providers(disabled, not registered or in blocklist).");
}
if (multiGroup) {
return this.getInvokers();
}
try {
// Get invokers from cache, only runtime routers will be executed.
List<Invoker<T>> result = singleRouterChain.route(getConsumerUrl(), invokers, invocation);
return result == null ? BitList.emptyList() : result;
} catch (Throwable t) {
// 2-1 - Failed to execute routing.
logger.error(
CLUSTER_FAILED_SITE_SELECTION,
"",
"",
"Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(),
t);
return BitList.emptyList();
}
}
@Override
public Class<T> getInterface() {
return serviceType;
}
@Override
public List<Invoker<T>> getAllInvokers() {
return this.getInvokers();
}
/**
* The currently effective consumer url
*
* @return URL
*/
@Override
public URL getConsumerUrl() {
return this.directoryUrl;
}
/**
* The original consumer url
*
* @return URL
*/
public URL getOriginalConsumerUrl() {
return this.consumerUrl;
}
/**
* The url registered to registry or metadata center
*
* @return URL
*/
public URL getRegisteredConsumerUrl() {
return registeredConsumerUrl;
}
/**
* The url used to subscribe from registry
*
* @return URL
*/
public URL getSubscribeUrl() {
return subscribeUrl;
}
public void setSubscribeUrl(URL subscribeUrl) {
this.subscribeUrl = subscribeUrl;
}
public void setRegisteredConsumerUrl(URL url) {
if (!shouldSimplified) {
this.registeredConsumerUrl =
url.addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false));
} else {
this.registeredConsumerUrl = URL.valueOf(url, DEFAULT_REGISTER_CONSUMER_KEYS, null)
.addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false));
}
}
public void buildRouterChain(URL url) {
this.setRouterChain(RouterChain.buildChain(getInterface(), url));
}
@Override
public boolean isAvailable() {
if (isDestroyed() || this.forbidden) {
return false;
}
for (Invoker<T> validInvoker : getValidInvokers()) {
if (validInvoker.isAvailable()) {
return true;
} else {
addInvalidateInvoker(validInvoker);
}
}
return false;
}
@Override
public void destroy() {
if (isDestroyed()) {
return;
}
// unregister.
try {
if (getRegisteredConsumerUrl() != null && registry != null && registry.isAvailable()) {
registry.unregister(getRegisteredConsumerUrl());
}
} catch (Throwable t) {
// 1-8: Failed to unregister / unsubscribe url on destroy.
logger.warn(
REGISTRY_FAILED_DESTROY_UNREGISTER_URL,
"",
"",
"unexpected error when unregister service " + serviceKey + " from registry: " + registry.getUrl(),
t);
}
// unsubscribe.
try {
if (getSubscribeUrl() != null && registry != null && registry.isAvailable()) {
registry.unsubscribe(getSubscribeUrl(), this);
}
} catch (Throwable t) {
// 1-8: Failed to unregister / unsubscribe url on destroy.
logger.warn(
REGISTRY_FAILED_DESTROY_UNREGISTER_URL,
"",
"",
"unexpected error when unsubscribe service " + serviceKey + " from registry: " + registry.getUrl(),
t);
}
ExtensionLoader<AddressListener> addressListenerExtensionLoader =
getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class);
List<AddressListener> supportedListeners =
addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null);
if (CollectionUtils.isNotEmpty(supportedListeners)) {
for (AddressListener addressListener : supportedListeners) {
addressListener.destroy(getConsumerUrl(), this);
}
}
synchronized (this) {
try {
destroyAllInvokers();
} catch (Throwable t) {
// 1-15 - Failed to destroy service.
logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", "Failed to destroy service " + serviceKey, t);
}
routerChain.destroy();
invokersChangedListener = null;
serviceListener = null;
super.destroy(); // must be executed after unsubscribing
}
}
@Override
public void discordAddresses() {
try {
destroyAllInvokers();
} catch (Throwable t) {
// 1-15 - Failed to destroy service.
logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", "Failed to destroy service " + serviceKey, t);
}
}
public synchronized void setInvokersChangedListener(InvokersChangedListener listener) {
this.invokersChangedListener = listener;
if (invokersChangedListener != null && invokersChanged) {
invokersChangedListener.onChange();
}
}
protected synchronized void invokersChanged() {
refreshInvoker();
invokersChanged = true;
if (invokersChangedListener != null) {
invokersChangedListener.onChange();
invokersChanged = false;
}
}
@Override
public boolean isNotificationReceived() {
return invokersChanged;
}
protected abstract void destroyAllInvokers();
protected abstract void refreshOverrideAndInvoker(List<URL> urls);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ExporterFactory.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ExporterFactory.java | /*
* 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.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.rpc.Exporter;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
public class ExporterFactory {
private final ConcurrentHashMap<String, ReferenceCountExporter<?>> exporters = new ConcurrentHashMap<>();
protected ReferenceCountExporter<?> createExporter(String providerKey, Callable<Exporter<?>> exporterProducer) {
return ConcurrentHashMapUtils.computeIfAbsent(exporters, providerKey, key -> {
try {
return new ReferenceCountExporter<>(exporterProducer.call(), key, this);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
protected void remove(String key, ReferenceCountExporter<?> exporter) {
exporters.remove(key, exporter);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java | /*
* 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.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.DubboServiceAddressURL;
import org.apache.dubbo.common.url.component.ServiceAddressURL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.registry.event.RegistryEvent;
import org.apache.dubbo.registry.AddressListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.support.ClusterUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.EXT_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_REGISTER_MODE;
import static org.apache.dubbo.common.constants.CommonConstants.PREFERRED_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REFER_INVOKER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_CONVERT_URL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DESTROY_SERVICE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNSUPPORTED_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_HASHMAP_LOAD_FACTOR;
import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL;
import static org.apache.dubbo.registry.Constants.CONFIGURATORS_SUFFIX;
import static org.apache.dubbo.registry.Constants.ENABLE_26X_CONFIGURATION_LISTEN;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY;
import static org.apache.dubbo.rpc.model.ScopeModelUtil.getModuleModel;
/**
* RegistryDirectory
*/
public class RegistryDirectory<T> extends DynamicDirectory<T> {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RegistryDirectory.class);
private final ConsumerConfigurationListener consumerConfigurationListener;
private ReferenceConfigurationListener referenceConfigurationListener;
/**
* Map<url, Invoker> cache service url to invoker mapping.
* The initial value is null and the midway may be assigned to null, please use the local variable reference
*/
protected volatile Map<URL, Invoker<T>> urlInvokerMap;
/**
* The initial value is null and the midway may be assigned to null, please use the local variable reference
*/
protected volatile Set<URL> cachedInvokerUrls;
private final ModuleModel moduleModel;
public RegistryDirectory(Class<T> serviceType, URL url) {
super(serviceType, url);
moduleModel = getModuleModel(url.getScopeModel());
consumerConfigurationListener = getConsumerConfigurationListener(moduleModel);
}
@Override
public void subscribe(URL url) {
// Fail-fast detection protocol spi
String queryProtocols = this.queryMap.get(PROTOCOL_KEY);
if (StringUtils.isNotBlank(queryProtocols)) {
String[] acceptProtocols = queryProtocols.split(",");
for (String acceptProtocol : acceptProtocols) {
if (!moduleModel
.getApplicationModel()
.getExtensionLoader(Protocol.class)
.hasExtension(acceptProtocol)) {
throw new IllegalStateException("No such extension org.apache.dubbo.rpc.Protocol by name "
+ acceptProtocol + ", please check whether related SPI module is missing");
}
}
}
ApplicationModel applicationModel = url.getApplicationModel();
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
consumerConfigurationListener.addNotifyListener(this);
referenceConfigurationListener = new ReferenceConfigurationListener(moduleModel, this, url);
}
String registryClusterName = registry.getUrl()
.getParameter(
RegistryConstants.REGISTRY_CLUSTER_KEY,
registry.getUrl().getParameter(PROTOCOL_KEY));
MetricsEventBus.post(RegistryEvent.toSubscribeEvent(applicationModel, registryClusterName), () -> {
super.subscribe(url);
return null;
});
}
private ConsumerConfigurationListener getConsumerConfigurationListener(ModuleModel moduleModel) {
return moduleModel
.getBeanFactory()
.getOrRegisterBean(
ConsumerConfigurationListener.class, type -> new ConsumerConfigurationListener(moduleModel));
}
@Override
public void unSubscribe(URL url) {
super.unSubscribe(url);
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
consumerConfigurationListener.removeNotifyListener(this);
if (referenceConfigurationListener != null) {
referenceConfigurationListener.stop();
}
}
}
@Override
public void destroy() {
super.destroy();
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
consumerConfigurationListener.removeNotifyListener(this);
if (referenceConfigurationListener != null) {
referenceConfigurationListener.stop();
}
}
}
@Override
public synchronized void notify(List<URL> urls) {
if (isDestroyed()) {
return;
}
Map<String, List<URL>> categoryUrls = urls.stream()
.filter(Objects::nonNull)
.filter(this::isValidCategory)
.filter(this::isNotCompatibleFor26x)
.collect(Collectors.groupingBy(this::judgeCategory));
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, ENABLE_26X_CONFIGURATION_LISTEN, true)) {
List<URL> configuratorURLs = categoryUrls.getOrDefault(CONFIGURATORS_CATEGORY, Collections.emptyList());
this.configurators = Configurator.toConfigurators(configuratorURLs).orElse(this.configurators);
List<URL> routerURLs = categoryUrls.getOrDefault(ROUTERS_CATEGORY, Collections.emptyList());
toRouters(routerURLs).ifPresent(this::addRouters);
}
// providers
List<URL> providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList());
// 3.x added for extend URL address
ExtensionLoader<AddressListener> addressListenerExtensionLoader =
getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class);
List<AddressListener> supportedListeners =
addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null);
if (supportedListeners != null && !supportedListeners.isEmpty()) {
for (AddressListener addressListener : supportedListeners) {
providerURLs = addressListener.notify(providerURLs, getConsumerUrl(), this);
}
}
refreshOverrideAndInvoker(providerURLs);
}
@Override
public boolean isServiceDiscovery() {
return false;
}
private String judgeCategory(URL url) {
if (UrlUtils.isConfigurator(url)) {
return CONFIGURATORS_CATEGORY;
} else if (UrlUtils.isRoute(url)) {
return ROUTERS_CATEGORY;
} else if (UrlUtils.isProvider(url)) {
return PROVIDERS_CATEGORY;
}
return "";
}
// RefreshOverrideAndInvoker will be executed by registryCenter and configCenter, so it should be synchronized.
@Override
protected synchronized void refreshOverrideAndInvoker(List<URL> urls) {
// mock zookeeper://xxx?mock=return null
this.directoryUrl = overrideWithConfigurator(getOriginalConsumerUrl());
refreshInvoker(urls);
}
/**
* Convert the invokerURL list to the Invoker Map. The rules of the conversion are as follows:
* <ol>
* <li> If URL has been converted to invoker, it is no longer re-referenced and obtained directly from the cache,
* and notice that any parameter changes in the URL will be re-referenced.</li>
* <li>If the incoming invoker list is not empty, it means that it is the latest invoker list.</li>
* <li>If the list of incoming invokerUrl is empty, It means that the rule is only a override rule or a route
* rule, which needs to be re-contrasted to decide whether to re-reference.</li>
* </ol>
*
* @param invokerUrls this parameter can't be null
*/
private void refreshInvoker(List<URL> invokerUrls) {
Assert.notNull(invokerUrls, "invokerUrls should not be null");
if (invokerUrls.size() == 1
&& invokerUrls.get(0) != null
&& EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) {
refreshRouter(
BitList.emptyList(), () -> this.forbidden = true // Forbid to access
);
destroyAllInvokers(); // Close all invokers
} else {
this.forbidden = false; // Allow to access
if (invokerUrls == Collections.<URL>emptyList()) {
invokerUrls = new ArrayList<>();
}
// use local reference to avoid NPE as this.cachedInvokerUrls will be set null by destroyAllInvokers().
Set<URL> localCachedInvokerUrls = this.cachedInvokerUrls;
if (invokerUrls.isEmpty()) {
if (CollectionUtils.isNotEmpty(localCachedInvokerUrls)) {
// 1-4 Empty address.
logger.warn(
REGISTRY_EMPTY_ADDRESS,
"configuration ",
"",
"Service" + serviceKey
+ " received empty address list with no EMPTY protocol set, trigger empty protection.");
invokerUrls.addAll(localCachedInvokerUrls);
}
} else {
localCachedInvokerUrls = new HashSet<>();
localCachedInvokerUrls.addAll(invokerUrls); // Cached invoker urls, convenient for comparison
this.cachedInvokerUrls = localCachedInvokerUrls;
}
if (invokerUrls.isEmpty()) {
return;
}
int originSize = invokerUrls.size();
invokerUrls = invokerUrls.stream().distinct().collect(Collectors.toList());
if (invokerUrls.size() != originSize) {
logger.info("Received duplicated invoker urls changed event from registry. "
+ "Registry type: interface. "
+ "Service Key: "
+ getConsumerUrl().getServiceKey() + ". "
+ "Notify Urls Size : " + originSize + ". "
+ "Distinct Urls Size: " + invokerUrls.size() + ".");
}
// use local reference to avoid NPE as this.urlInvokerMap will be set null concurrently at
// destroyAllInvokers().
Map<URL, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap;
// can't use local reference as oldUrlInvokerMap's mappings might be removed directly at toInvokers().
Map<URL, Invoker<T>> oldUrlInvokerMap = null;
if (localUrlInvokerMap != null) {
// the initial capacity should be set greater than the maximum number of entries divided by the load
// factor to avoid resizing.
oldUrlInvokerMap =
new LinkedHashMap<>(Math.round(1 + localUrlInvokerMap.size() / DEFAULT_HASHMAP_LOAD_FACTOR));
localUrlInvokerMap.forEach(oldUrlInvokerMap::put);
}
Map<URL, Invoker<T>> newUrlInvokerMap =
toInvokers(oldUrlInvokerMap, invokerUrls); // Translate url list to Invoker map
/*
* If the calculation is wrong, it is not processed.
*
* 1. The protocol configured by the client is inconsistent with the protocol of the server.
* eg: consumer protocol = dubbo, provider only has other protocol services(rest).
* 2. The registration center is not robust and pushes illegal specification data.
*
*/
if (CollectionUtils.isEmptyMap(newUrlInvokerMap)) {
// 3-1 - Failed to convert the URL address into Invokers.
logger.error(
PROXY_FAILED_CONVERT_URL,
"inconsistency between the client protocol and the protocol of the server",
"",
"urls to invokers error",
new IllegalStateException("urls to invokers error. invokerUrls.size :" + invokerUrls.size()
+ ", invoker.size :0. urls :" + invokerUrls.toString()));
return;
}
List<Invoker<T>> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values()));
BitList<Invoker<T>> finalInvokers =
multiGroup ? new BitList<>(toMergeInvokerList(newInvokers)) : new BitList<>(newInvokers);
// pre-route and build cache
refreshRouter(finalInvokers.clone(), () -> this.setInvokers(finalInvokers));
this.urlInvokerMap = newUrlInvokerMap;
try {
destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // Close the unused Invoker
} catch (Exception e) {
logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", "destroyUnusedInvokers error. ", e);
}
// notify invokers refreshed
this.invokersChanged();
}
logger.info("Received invokers changed event from registry. " + "Registry type: interface. "
+ "Service Key: "
+ getConsumerUrl().getServiceKey() + ". " + "Urls Size : "
+ invokerUrls.size() + ". " + "Invokers Size : "
+ getInvokers().size() + ". " + "Available Size: "
+ getValidInvokers().size() + ". " + "Available Invokers : "
+ joinValidInvokerAddresses());
}
private List<Invoker<T>> toMergeInvokerList(List<Invoker<T>> invokers) {
List<Invoker<T>> mergedInvokers = new ArrayList<>();
Map<String, List<Invoker<T>>> groupMap = new HashMap<>();
for (Invoker<T> invoker : invokers) {
String group = invoker.getUrl().getGroup("");
groupMap.computeIfAbsent(group, k -> new ArrayList<>());
groupMap.get(group).add(invoker);
}
if (groupMap.size() == 1) {
mergedInvokers.addAll(groupMap.values().iterator().next());
} else if (groupMap.size() > 1) {
for (List<Invoker<T>> groupList : groupMap.values()) {
StaticDirectory<T> staticDirectory = new StaticDirectory<>(groupList);
staticDirectory.buildRouterChain();
mergedInvokers.add(cluster.join(staticDirectory, false));
}
} else {
mergedInvokers = invokers;
}
return mergedInvokers;
}
/**
* @param urls
* @return null : no routers ,do nothing
* else :routers list
*/
private Optional<List<Router>> toRouters(List<URL> urls) {
if (urls == null || urls.isEmpty()) {
return Optional.empty();
}
List<Router> routers = new ArrayList<>();
for (URL url : urls) {
if (EMPTY_PROTOCOL.equals(url.getProtocol())) {
continue;
}
String routerType = url.getParameter(ROUTER_KEY);
if (routerType != null && routerType.length() > 0) {
url = url.setProtocol(routerType);
}
try {
Router router = routerFactory.getRouter(url);
if (!routers.contains(router)) {
routers.add(router);
}
} catch (Throwable t) {
logger.error(PROXY_FAILED_CONVERT_URL, "", "", "convert router url to router error, url:" + url, t);
}
}
return Optional.of(routers);
}
/**
* Turn urls into invokers, and if url has been referred, will not re-reference.
* the items that will be put into newUrlInvokeMap will be removed from oldUrlInvokerMap.
*
* @param oldUrlInvokerMap it might be modified during the process.
* @param urls
* @return invokers
*/
private Map<URL, Invoker<T>> toInvokers(Map<URL, Invoker<T>> oldUrlInvokerMap, List<URL> urls) {
Map<URL, Invoker<T>> newUrlInvokerMap =
new ConcurrentHashMap<>(urls == null ? 1 : (int) (urls.size() / 0.75f + 1));
if (urls == null || urls.isEmpty()) {
return newUrlInvokerMap;
}
String queryProtocols = this.queryMap.get(PROTOCOL_KEY);
for (URL providerUrl : urls) {
if (!checkProtocolValid(queryProtocols, providerUrl)) {
continue;
}
URL url = mergeUrl(providerUrl);
// get the effective protocol that this consumer should consume based on consumer side protocol
// configuration and available protocols in address pool.
String effectiveProtocol = getEffectiveProtocol(queryProtocols, url);
if (!effectiveProtocol.equals(url.getProtocol())) {
url = url.setProtocol(effectiveProtocol);
}
// Cache key is url that does not merge with consumer side parameters,
// regardless of how the consumer combines parameters,
// if the server url changes, then refer again
Invoker<T> invoker = oldUrlInvokerMap == null ? null : oldUrlInvokerMap.remove(url);
if (invoker == null) { // Not in the cache, refer again
try {
boolean enabled = true;
if (url.hasParameter(DISABLED_KEY)) {
enabled = !url.getParameter(DISABLED_KEY, false);
} else {
enabled = url.getParameter(ENABLED_KEY, true);
}
if (enabled) {
invoker = protocol.refer(serviceType, url);
}
} catch (Throwable t) {
// Thrown by AbstractProtocol.optimizeSerialization()
if (t instanceof RpcException && t.getMessage().contains("serialization optimizer")) {
// 4-2 - serialization optimizer class initialization failed.
logger.error(
PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER,
"typo in optimizer class",
"",
"Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")"
+ t.getMessage(),
t);
} else {
// 4-3 - Failed to refer invoker by other reason.
logger.error(
PROTOCOL_FAILED_REFER_INVOKER,
"",
"",
"Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")"
+ t.getMessage(),
t);
}
}
if (invoker != null) { // Put new invoker in cache
newUrlInvokerMap.put(url, invoker);
}
} else {
newUrlInvokerMap.put(url, invoker);
}
}
return newUrlInvokerMap;
}
/**
* Get the protocol to consume by matching the consumer acceptable protocols and the available provider protocols.
* <p>
* Only the first protocol that can match with the provider protocols will be used if consumer set to accept multiple protocols.
* For example, if dubbo.consumer.protocol='tri,rest' is set and provider provides tri protocol, then consumer will use tri protocol to communicate with provider.
*
* @param queryProtocols consumer side protocols.
* @param url provider url that have extra protocols specified.
* @return the protocol to consume.
*/
private String getEffectiveProtocol(String queryProtocols, URL url) {
String protocol = url.getProtocol();
String prioritizedProtocol = url.getParameter(PREFERRED_PROTOCOL, protocol);
String effectiveProtocol = prioritizedProtocol;
if (StringUtils.isNotEmpty(queryProtocols)) {
String[] acceptProtocols = queryProtocols.split(COMMA_SEPARATOR);
String acceptedProtocol = acceptProtocols[0];
if (!acceptedProtocol.equals(prioritizedProtocol)) {
if (!acceptedProtocol.equals(protocol)) {
String extProtocols = url.getParameter(EXT_PROTOCOL);
if (StringUtils.isNotEmpty(extProtocols)) {
String[] extProtocolsArr = extProtocols.split(COMMA_SEPARATOR);
for (String p : extProtocolsArr) {
if (p.equalsIgnoreCase(acceptedProtocol)) {
effectiveProtocol = acceptedProtocol;
break;
}
}
}
} else {
effectiveProtocol = protocol;
}
}
}
return effectiveProtocol;
}
private boolean checkProtocolValid(String queryProtocols, URL providerUrl) {
// If protocol is configured at the reference side, only the matching protocol is selected
if (queryProtocols != null && queryProtocols.length() > 0) {
boolean accept = false;
String[] acceptProtocols = queryProtocols.split(",");
for (String acceptProtocol : acceptProtocols) {
if (providerUrl.getProtocol().equals(acceptProtocol)) {
accept = true;
break;
}
}
if (!accept) {
return false;
}
}
if (EMPTY_PROTOCOL.equals(providerUrl.getProtocol())) {
return false;
}
if (!getUrl().getOrDefaultFrameworkModel()
.getExtensionLoader(Protocol.class)
.hasExtension(providerUrl.getProtocol())) {
// 4-1 - Unsupported protocol
logger.error(
PROTOCOL_UNSUPPORTED,
"protocol extension does not installed",
"",
"Unsupported protocol.",
new IllegalStateException("Unsupported protocol " + providerUrl.getProtocol() + " in notified url: "
+ providerUrl + " from registry " + getUrl().getAddress() + " to consumer "
+ NetUtils.getLocalHost() + ", supported protocol: "
+ getUrl().getOrDefaultFrameworkModel()
.getExtensionLoader(Protocol.class)
.getSupportedExtensions()));
return false;
}
return true;
}
/**
* Merge url parameters. the order is: override > -D >Consumer > Provider
*
* @param providerUrl
* @return
*/
private URL mergeUrl(URL providerUrl) {
if (providerUrl instanceof ServiceAddressURL) {
providerUrl = overrideWithConfigurator(providerUrl);
} else {
providerUrl = moduleModel
.getApplicationModel()
.getBeanFactory()
.getBean(ClusterUtils.class)
.mergeUrl(providerUrl, queryMap); // Merge the consumer side parameters
providerUrl = overrideWithConfigurator(providerUrl);
providerUrl = providerUrl.addParameter(
Constants.CHECK_KEY,
String.valueOf(
false)); // Do not check whether the connection is successful or not, always create Invoker!
}
// FIXME, kept for mock
if (providerUrl.hasParameter(MOCK_KEY) || providerUrl.getAnyMethodParameter(MOCK_KEY) != null) {
providerUrl = providerUrl.removeParameter(MOCK_KEY);
}
if ((providerUrl.getPath() == null || providerUrl.getPath().length() == 0)
&& DUBBO_PROTOCOL.equals(providerUrl.getProtocol())) { // Compatible version 1.0
// fix by tony.chenl DUBBO-44
String path = directoryUrl.getServiceInterface();
if (path != null) {
int i = path.indexOf('/');
if (i >= 0) {
path = path.substring(i + 1);
}
i = path.lastIndexOf(':');
if (i >= 0) {
path = path.substring(0, i);
}
providerUrl = providerUrl.setPath(path);
}
}
return providerUrl;
}
protected URL overrideWithConfigurator(URL providerUrl) {
// override url with configurator from "override://" URL for dubbo 2.6 and before
providerUrl = overrideWithConfigurators(this.configurators, providerUrl);
// override url with configurator from "app-name.configurators"
providerUrl = overrideWithConfigurators(consumerConfigurationListener.getConfigurators(), providerUrl);
// override url with configurator from configurators from "service-name.configurators"
if (referenceConfigurationListener != null) {
providerUrl = overrideWithConfigurators(referenceConfigurationListener.getConfigurators(), providerUrl);
}
return providerUrl;
}
private URL overrideWithConfigurators(List<Configurator> configurators, URL url) {
if (CollectionUtils.isNotEmpty(configurators)) {
if (url instanceof DubboServiceAddressURL) {
DubboServiceAddressURL interfaceAddressURL = (DubboServiceAddressURL) url;
URL overriddenURL = interfaceAddressURL.getOverrideURL();
if (overriddenURL == null) {
String appName = interfaceAddressURL.getApplication();
String side = interfaceAddressURL.getSide();
String group = interfaceAddressURL.getGroup();
String version = interfaceAddressURL.getVersion();
overriddenURL = URLBuilder.from(interfaceAddressURL)
.clearParameters()
.addParameter(APPLICATION_KEY, appName)
.addParameter(SIDE_KEY, side)
.addParameter(GROUP_KEY, group)
.addParameter(VERSION_KEY, version)
.build();
}
for (Configurator configurator : configurators) {
overriddenURL = configurator.configure(overriddenURL);
}
url = new DubboServiceAddressURL(
interfaceAddressURL.getUrlAddress(),
interfaceAddressURL.getUrlParam(),
interfaceAddressURL.getConsumerURL(),
(ServiceConfigURL) overriddenURL);
} else {
for (Configurator configurator : configurators) {
url = configurator.configure(url);
}
}
}
return url;
}
/**
* Close all invokers
*/
@Override
protected void destroyAllInvokers() {
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java | /*
* 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.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.configurator.parser.ConfigParser;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_PARSE_DYNAMIC_CONFIG;
import static org.apache.dubbo.rpc.Constants.ACCESS_LOG_FIXED_PATH_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY;
public abstract class AbstractConfiguratorListener implements ConfigurationListener {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractConfiguratorListener.class);
protected List<Configurator> configurators = Collections.emptyList();
protected GovernanceRuleRepository ruleRepository;
protected Set<String> securityKey = new HashSet<>();
protected ModuleModel moduleModel;
public AbstractConfiguratorListener(ModuleModel moduleModel) {
this.moduleModel = moduleModel;
ruleRepository =
moduleModel.getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension();
initSecurityKey();
}
private void initSecurityKey() {
// FileRouterFactory key
securityKey.add(ACCESS_LOG_FIXED_PATH_KEY);
securityKey.add(ROUTER_KEY);
securityKey.add(RULE_KEY);
securityKey.add(RUNTIME_KEY);
securityKey.add(TYPE_KEY);
}
protected final void initWith(String key) {
ruleRepository.addListener(key, this);
String rawConfig = ruleRepository.getRule(key, DynamicConfiguration.DEFAULT_GROUP);
if (!StringUtils.isEmpty(rawConfig)) {
genConfiguratorsFromRawRule(rawConfig);
}
}
protected final void stopListen(String key) {
ruleRepository.removeListener(key, this);
}
@Override
public void process(ConfigChangedEvent event) {
if (logger.isInfoEnabled()) {
logger.info("Notification of overriding rule, change type is: " + event.getChangeType()
+ ", raw config content is:\n " + event.getContent());
}
if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
configurators.clear();
} else {
// ADDED or MODIFIED
if (!genConfiguratorsFromRawRule(event.getContent())) {
return;
}
}
notifyOverrides();
}
private boolean genConfiguratorsFromRawRule(String rawConfig) {
List<URL> urls;
try {
// parseConfigurators will recognize app/service config automatically.
urls = ConfigParser.parseConfigurators(rawConfig);
} catch (Exception e) {
// 1-14 - Failed to parse raw dynamic config.
logger.warn(
REGISTRY_FAILED_PARSE_DYNAMIC_CONFIG,
"",
"",
"Failed to parse raw dynamic config and it will not take effect, the raw config is: " + rawConfig
+ ", cause: " + e.getMessage());
return false;
}
List<URL> safeUrls = urls.stream()
.map(url -> url.removeParameters(securityKey))
.map(url -> url.setScopeModel(moduleModel))
.collect(Collectors.toList());
configurators = Configurator.toConfigurators(safeUrls).orElse(configurators);
return true;
}
protected abstract void notifyOverrides();
public List<Configurator> getConfigurators() {
return configurators;
}
public void setConfigurators(List<Configurator> configurators) {
this.configurators = configurators;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ServiceURLCustomizer.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ServiceURLCustomizer.java | /*
* 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.extension.SPI;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.rpc.model.ApplicationModel;
import static org.apache.dubbo.common.extension.ExtensionScope.APPLICATION;
/**
* Customize parameters for interface-level registration
*/
@SPI(scope = APPLICATION)
public interface ServiceURLCustomizer extends Prioritized {
/**
* Customizes {@link URL the service url}
*
* @param serviceURL {@link URL the service url}
* @return new service url
*/
URL customize(URL serviceURL, ApplicationModel applicationModel);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DefaultServiceURLCustomizer.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DefaultServiceURLCustomizer.java | /*
* 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.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Stream;
import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.BACKGROUND_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE;
import static org.apache.dubbo.common.constants.CommonConstants.EXTRA_KEYS_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.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED;
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TRIPLE_PREFIX;
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.REGISTER_MODE_KEY;
import static org.apache.dubbo.registry.Constants.SIMPLIFIED_KEY;
import static org.apache.dubbo.registry.integration.RegistryProtocol.DEFAULT_REGISTER_PROVIDER_KEYS;
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.rpc.Constants.INTERFACES;
public class DefaultServiceURLCustomizer implements ServiceURLCustomizer {
private static final String[] excludedParameters = new String[] {
MONITOR_KEY,
BIND_IP_KEY,
BIND_PORT_KEY,
QOS_ENABLE,
QOS_HOST,
QOS_PORT,
ACCEPT_FOREIGN_IP,
VALIDATION_KEY,
INTERFACES,
REGISTER_MODE_KEY,
PID_KEY,
REGISTRY_LOCAL_FILE_CACHE_ENABLED,
EXECUTOR_MANAGEMENT_MODE,
BACKGROUND_KEY,
ANYHOST_KEY,
THREAD_NAME_KEY,
THREADPOOL_KEY,
ALIVE_KEY,
QUEUES_KEY,
CORE_THREADS_KEY,
THREADS_KEY
};
private static final String[] excludedPrefixes = new String[] {HIDE_KEY_PREFIX, TRIPLE_PREFIX};
@Override
public URL customize(URL serviceURL, ApplicationModel applicationModel) {
boolean simplified = (boolean) serviceURL.getAttribute(SIMPLIFIED_KEY, false);
if (simplified) {
String extraKeys = (String) serviceURL.getAttribute(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 (!serviceURL.getPath().equals(serviceURL.getParameter(INTERFACE_KEY))) {
if (StringUtils.isNotEmpty(extraKeys)) {
extraKeys += ",";
}
extraKeys += INTERFACE_KEY;
}
String[] paramsToRegistry = Stream.concat(
Arrays.stream(DEFAULT_REGISTER_PROVIDER_KEYS),
Arrays.stream(COMMA_SPLIT_PATTERN.split(extraKeys)))
.toArray(String[]::new);
return URL.valueOf(serviceURL, paramsToRegistry, serviceURL.getParameter(METHODS_KEY, (String[]) null));
}
return serviceURL.removeParameters(getFilteredKeys(serviceURL)).removeParameters(excludedParameters);
}
@Override
public int getPriority() {
return MAX_PRIORITY;
}
private String[] getFilteredKeys(URL url) {
Map<String, String> params = url.getParameters();
if (CollectionUtils.isNotEmptyMap(params)) {
return params.keySet().stream()
.filter(k -> {
for (String excludedPrefix : excludedPrefixes) {
if (k.startsWith(excludedPrefix)) {
return true;
}
}
return false;
})
.toArray(String[]::new);
}
return new String[0];
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocolListener.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocolListener.java | /*
* 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.extension.SPI;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import static org.apache.dubbo.common.extension.ExtensionScope.MODULE;
/**
* RegistryProtocol listener is introduced to provide a chance to user to customize or change export and refer behavior
* of RegistryProtocol. For example: re-export or re-refer on the fly when certain condition meets.
*/
@SPI(scope = MODULE)
public interface RegistryProtocolListener {
/**
* Notify RegistryProtocol's listeners when a service is registered
*
* @param registryProtocol RegistryProtocol instance
* @param exporter exporter
* @see RegistryProtocol#export(org.apache.dubbo.rpc.Invoker)
*/
void onExport(RegistryProtocol registryProtocol, Exporter<?> exporter);
/**
* Notify RegistryProtocol's listeners when a service is subscribed
*
* @param registryProtocol RegistryProtocol instance
* @param invoker invoker
* @param url
* @see RegistryProtocol#refer(Class, URL)
*/
void onRefer(RegistryProtocol registryProtocol, ClusterInvoker<?> invoker, URL url, URL registryURL);
/**
* Notify RegistryProtocol's listeners when the protocol is destroyed
*/
void onDestroy();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnsubscribedTask.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnsubscribedTask.java | /*
* 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.retry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.support.FailbackRegistry;
public final class FailedUnsubscribedTask extends AbstractRetryTask {
private static final String NAME = "retry unsubscribe";
private final NotifyListener listener;
public FailedUnsubscribedTask(URL url, FailbackRegistry registry, NotifyListener listener) {
super(url, registry, NAME);
if (listener == null) {
throw new IllegalArgumentException();
}
this.listener = listener;
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.doUnsubscribe(url, listener);
registry.removeFailedUnsubscribedTask(url, listener);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java | /*
* 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.retry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.common.timer.Timer;
import org.apache.dubbo.common.timer.TimerTask;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.support.FailbackRegistry;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_EXECUTE_RETRYING_TASK;
import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_PERIOD;
import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_TIMES;
import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY;
import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_TIMES_KEY;
public abstract class AbstractRetryTask implements TimerTask {
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
/**
* url for retry task
*/
protected final URL url;
/**
* registry for this task
*/
protected final FailbackRegistry registry;
/**
* retry period
*/
private final long retryPeriod;
/**
* define the most retry times
*/
private final int retryTimes;
/**
* task name for this task
*/
private final String taskName;
/**
* times of retry.
* retry task is execute in single thread so that the times is not need volatile.
*/
private int times = 1;
private volatile boolean cancel;
AbstractRetryTask(URL url, FailbackRegistry registry, String taskName) {
if (url == null || StringUtils.isBlank(taskName)) {
throw new IllegalArgumentException();
}
this.url = url;
this.registry = registry;
this.taskName = taskName;
this.cancel = false;
this.retryPeriod = url.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD);
this.retryTimes = url.getParameter(REGISTRY_RETRY_TIMES_KEY, DEFAULT_REGISTRY_RETRY_TIMES);
}
public void cancel() {
cancel = true;
}
public boolean isCancel() {
return cancel;
}
protected void reput(Timeout timeout, long tick) {
if (timeout == null) {
throw new IllegalArgumentException();
}
Timer timer = timeout.timer();
if (timer.isStop() || timeout.isCancelled() || isCancel()) {
return;
}
times++;
timer.newTimeout(timeout.task(), tick, TimeUnit.MILLISECONDS);
}
@Override
public void run(Timeout timeout) throws Exception {
if (timeout.isCancelled() || timeout.timer().isStop() || isCancel()) {
// other thread cancel this timeout or stop the timer.
return;
}
if (retryTimes > 0 && times > retryTimes) {
// 1-13 - failed to execute the retrying task.
logger.warn(
REGISTRY_EXECUTE_RETRYING_TASK,
"registry center offline",
"Check the registry server.",
"Final failed to execute task " + taskName + ", url: " + url + ", retry " + retryTimes + " times.");
return;
}
if (logger.isInfoEnabled()) {
logger.info(taskName + " : " + url);
}
try {
if (!registry.isAvailable()) {
throw new IllegalStateException("Registry is not available.");
}
doRetry(url, registry, timeout);
} catch (Throwable t) { // Ignore all the exceptions and wait for the next retry
// 1-13 - failed to execute the retrying task.
logger.warn(
REGISTRY_EXECUTE_RETRYING_TASK,
"registry center offline",
"Check the registry server.",
"Failed to execute task " + taskName + ", url: " + url + ", waiting for again, cause:"
+ t.getMessage(),
t);
// reput this task when catch exception.
reput(timeout, retryPeriod);
}
}
protected abstract void doRetry(URL url, FailbackRegistry registry, Timeout timeout);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnregisteredTask.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnregisteredTask.java | /*
* 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.retry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.registry.support.FailbackRegistry;
public final class FailedUnregisteredTask extends AbstractRetryTask {
private static final String NAME = "retry unregister";
public FailedUnregisteredTask(URL url, FailbackRegistry registry) {
super(url, registry, NAME);
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.doUnregister(url);
registry.removeFailedUnregisteredTask(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedSubscribedTask.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedSubscribedTask.java | /*
* 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.retry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.support.FailbackRegistry;
public final class FailedSubscribedTask extends AbstractRetryTask {
private static final String NAME = "retry subscribe";
private final NotifyListener listener;
public FailedSubscribedTask(URL url, FailbackRegistry registry, NotifyListener listener) {
super(url, registry, NAME);
if (listener == null) {
throw new IllegalArgumentException();
}
this.listener = listener;
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.doSubscribe(url, listener);
registry.removeFailedSubscribedTask(url, listener);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedRegisteredTask.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedRegisteredTask.java | /*
* 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.retry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.registry.support.FailbackRegistry;
public final class FailedRegisteredTask extends AbstractRetryTask {
private static final String NAME = "retry register";
public FailedRegisteredTask(URL url, FailbackRegistry registry) {
super(url, registry, NAME);
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.doRegister(url);
registry.removeFailedRegisteredTask(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/ReExportTask.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/ReExportTask.java | /*
* 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.retry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.registry.support.FailbackRegistry;
public class ReExportTask extends AbstractRetryTask {
private static final String NAME = "retry re-export";
private Runnable runnable;
public ReExportTask(Runnable runnable, URL oldUrl, FailbackRegistry registry) {
super(oldUrl, registry, NAME);
this.runnable = runnable;
}
@Override
protected void doRetry(URL oldUrl, FailbackRegistry registry, Timeout timeout) {
runnable.run();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/aot/RegistryReflectionTypeDescriberRegistrar.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/aot/RegistryReflectionTypeDescriberRegistrar.java | /*
* 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.aot;
import org.apache.dubbo.aot.api.MemberCategory;
import org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar;
import org.apache.dubbo.aot.api.TypeDescriber;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RegistryReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar {
@Override
public List<TypeDescriber> getTypeDescribers() {
List<TypeDescriber> typeDescribers = new ArrayList<>();
typeDescribers.add(buildTypeDescriberWithDeclaredMethod(MetadataServiceDelegation.class));
return typeDescribers;
}
private TypeDescriber buildTypeDescriberWithDeclaredMethod(Class<?> cl) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS);
memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
return new TypeDescriber(
cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java | /*
* 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.extension.SPI;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.rpc.model.ApplicationModel;
import static org.apache.dubbo.common.extension.ExtensionScope.APPLICATION;
/**
* The interface to customize {@link ServiceInstance the service instance}
*
* @see ServiceInstance#getMetadata()
* @since 2.7.5
*/
@SPI(scope = APPLICATION)
public interface ServiceInstanceCustomizer extends Prioritized {
/**
* Customizes {@link ServiceInstance the service instance}
*
* @param serviceInstance {@link ServiceInstance the service instance}
*/
void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java | /*
* 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.constants.RegistryConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.metadata.AbstractServiceNameMapping;
import org.apache.dubbo.metadata.MappingChangedEvent;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.registry.event.RegistryEvent;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.registry.support.FailbackRegistry;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
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.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE;
import static org.apache.dubbo.common.function.ThrowableAction.execute;
import static org.apache.dubbo.common.utils.CollectionUtils.toTreeSet;
import static org.apache.dubbo.metadata.ServiceNameMapping.toStringKeys;
import static org.apache.dubbo.registry.client.ServiceDiscoveryFactory.getExtension;
/**
* TODO, this bridge implementation is not necessary now, protocol can interact with service discovery directly.
* <p>
* ServiceDiscoveryRegistry is a very special Registry implementation, which is used to bridge the old interface-level service discovery model
* with the new service discovery model introduced in 3.0 in a compatible manner.
* <p>
* It fully complies with the extension specification of the Registry SPI, but is different from the specific implementation of zookeeper and Nacos,
* because it does not interact with any real third-party registry, but only with the relevant components of ServiceDiscovery in the process.
* In short, it bridges the old interface model and the new service discovery model:
* <p>
* - register() aggregates interface level data into MetadataInfo by mainly interacting with MetadataService.
* - subscribe() triggers the whole subscribe process of the application level service discovery model.
* - Maps interface to applications depending on ServiceNameMapping.
* - Starts the new service discovery listener (InstanceListener) and makes NotifierListeners part of the InstanceListener.
*/
public class ServiceDiscoveryRegistry extends FailbackRegistry {
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private final ServiceDiscovery serviceDiscovery;
private final AbstractServiceNameMapping serviceNameMapping;
/* apps - listener */
private final Map<String, ServiceInstancesChangedListener> serviceListeners = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Set<MappingListener>> mappingListeners = new ConcurrentHashMap<>();
/* This lock has the same scope and lifecycle as its corresponding instance listener.
It's used to make sure that only one interface mapping to the same app list can do subscribe or unsubscribe at the same moment.
And the lock should be destroyed when listener destroying its corresponding instance listener.
* */
private final ConcurrentMap<String, Lock> appSubscriptionLocks = new ConcurrentHashMap<>();
public ServiceDiscoveryRegistry(URL registryURL, ApplicationModel applicationModel) {
super(registryURL);
this.serviceDiscovery = createServiceDiscovery(registryURL);
this.serviceNameMapping =
(AbstractServiceNameMapping) ServiceNameMapping.getDefaultExtension(registryURL.getScopeModel());
super.applicationModel = applicationModel;
}
// Currently, for test purpose
protected ServiceDiscoveryRegistry(
URL registryURL, ServiceDiscovery serviceDiscovery, ServiceNameMapping serviceNameMapping) {
super(registryURL);
this.serviceDiscovery = serviceDiscovery;
this.serviceNameMapping = (AbstractServiceNameMapping) serviceNameMapping;
}
public ServiceDiscovery getServiceDiscovery() {
return serviceDiscovery;
}
/**
* Create the {@link ServiceDiscovery} from the registry {@link URL}
*
* @param registryURL the {@link URL} to connect the registry
* @return non-null
*/
protected ServiceDiscovery createServiceDiscovery(URL registryURL) {
return getServiceDiscovery(registryURL
.addParameter(INTERFACE_KEY, ServiceDiscovery.class.getName())
.removeParameter(REGISTRY_TYPE_KEY));
}
/**
* Get the instance {@link ServiceDiscovery} from the registry {@link URL} using
* {@link ServiceDiscoveryFactory} SPI
*
* @param registryURL the {@link URL} to connect the registry
* @return
*/
private ServiceDiscovery getServiceDiscovery(URL registryURL) {
ServiceDiscoveryFactory factory = getExtension(registryURL);
return factory.getServiceDiscovery(registryURL);
}
@Override
protected boolean shouldRegister(URL providerURL) {
String side = providerURL.getSide();
boolean should = PROVIDER_SIDE.equals(side); // Only register the Provider.
if (!should && logger.isDebugEnabled()) {
logger.debug(String.format("The URL[%s] should not be registered.", providerURL));
}
if (!acceptable(providerURL)) {
logger.info("URL " + providerURL + " will not be registered to Registry. Registry " + this.getUrl()
+ " does not accept service of this protocol type.");
return false;
}
return should;
}
protected boolean shouldSubscribe(URL subscribedURL) {
return !shouldRegister(subscribedURL);
}
@Override
public final void register(URL url) {
if (!shouldRegister(url)) { // Should Not Register
return;
}
doRegister(url);
}
@Override
public void doRegister(URL url) {
// fixme, add registry-cluster is not necessary anymore
url = addRegistryClusterKey(url);
serviceDiscovery.register(url);
}
@Override
public final void unregister(URL url) {
if (!shouldRegister(url)) {
return;
}
doUnregister(url);
}
@Override
public void doUnregister(URL url) {
// fixme, add registry-cluster is not necessary anymore
url = addRegistryClusterKey(url);
serviceDiscovery.unregister(url);
}
@Override
public final void subscribe(URL url, NotifyListener listener) {
if (!shouldSubscribe(url)) { // Should Not Subscribe
return;
}
doSubscribe(url, listener);
}
@Override
public void doSubscribe(URL url, NotifyListener listener) {
url = addRegistryClusterKey(url);
serviceDiscovery.subscribe(url, listener);
Set<String> mappingByUrl = ServiceNameMapping.getMappingByUrl(url);
String key = ServiceNameMapping.buildMappingKey(url);
if (mappingByUrl == null) {
Lock mappingLock = serviceNameMapping.getMappingLock(key);
try {
mappingLock.lock();
mappingByUrl = serviceNameMapping.getMapping(url);
try {
DefaultMappingListener mappingListener = new DefaultMappingListener(url, mappingByUrl, listener);
mappingByUrl = serviceNameMapping.getAndListen(this.getUrl(), url, mappingListener);
// update the initial mapping apps we started to listen, to make sure it reflects the real value
// used do subscription before any event.
// it's protected by the mapping lock, so it won't override the event value.
mappingListener.updateInitialApps(mappingByUrl);
synchronized (mappingListeners) {
ConcurrentHashMapUtils.computeIfAbsent(
mappingListeners, url.getProtocolServiceKey(), (k) -> new ConcurrentHashSet<>())
.add(mappingListener);
}
} catch (Exception e) {
logger.warn(
INTERNAL_ERROR,
"",
"",
"Cannot find app mapping for service " + url.getServiceInterface() + ", will not migrate.",
e);
}
if (CollectionUtils.isEmpty(mappingByUrl)) {
logger.info(
"[METADATA_REGISTER] No interface-apps mapping found in local cache, stop subscribing, will automatically wait for mapping listener callback: "
+ url);
// if (check) {
// throw new IllegalStateException("Should has at least one way to know which
// services this interface belongs to, subscription url: " + url);
// }
return;
}
} finally {
mappingLock.unlock();
}
}
subscribeURLs(url, listener, mappingByUrl);
}
@Override
public final void unsubscribe(URL url, NotifyListener listener) {
if (!shouldSubscribe(url)) { // Should Not Subscribe
return;
}
url = addRegistryClusterKey(url);
doUnsubscribe(url, listener);
}
private URL addRegistryClusterKey(URL url) {
String registryCluster = serviceDiscovery.getUrl().getParameter(REGISTRY_CLUSTER_KEY);
if (registryCluster != null && url.getParameter(REGISTRY_CLUSTER_KEY) == null) {
url = url.addParameter(REGISTRY_CLUSTER_KEY, registryCluster);
}
return url;
}
@Override
public void doUnsubscribe(URL url, NotifyListener listener) {
// TODO: remove service name mapping listener
serviceDiscovery.unsubscribe(url, listener);
String protocolServiceKey = url.getProtocolServiceKey();
Set<String> serviceNames = serviceNameMapping.getMapping(url);
synchronized (mappingListeners) {
Set<MappingListener> keyedListeners = mappingListeners.get(protocolServiceKey);
if (keyedListeners != null) {
List<MappingListener> matched = keyedListeners.stream()
.filter(mappingListener -> mappingListener instanceof DefaultMappingListener
&& (Objects.equals(((DefaultMappingListener) mappingListener).getListener(), listener)))
.collect(Collectors.toList());
for (MappingListener mappingListener : matched) {
serviceNameMapping.stopListen(url, mappingListener);
keyedListeners.remove(mappingListener);
}
if (keyedListeners.isEmpty()) {
mappingListeners.remove(protocolServiceKey, Collections.emptySet());
}
}
}
if (CollectionUtils.isNotEmpty(serviceNames)) {
String serviceNamesKey = toStringKeys(serviceNames);
Lock appSubscriptionLock = getAppSubscription(serviceNamesKey);
try {
appSubscriptionLock.lock();
ServiceInstancesChangedListener instancesChangedListener = serviceListeners.get(serviceNamesKey);
if (instancesChangedListener != null) {
instancesChangedListener.removeListener(url.getServiceKey(), listener);
if (!instancesChangedListener.hasListeners()) {
instancesChangedListener.destroy();
serviceListeners.remove(serviceNamesKey);
removeAppSubscriptionLock(serviceNamesKey);
}
}
} finally {
appSubscriptionLock.unlock();
}
}
}
@Override
public List<URL> lookup(URL url) {
throw new UnsupportedOperationException("");
}
@Override
public boolean isAvailable() {
// serviceDiscovery isAvailable has a default method, which can be used as a reference when implementing
return serviceDiscovery.isAvailable();
}
@Override
public void destroy() {
registryManager.removeDestroyedRegistry(this);
// stop ServiceDiscovery
execute(serviceDiscovery::destroy);
// destroy all event listener
for (ServiceInstancesChangedListener listener : serviceListeners.values()) {
listener.destroy();
}
appSubscriptionLocks.clear();
serviceListeners.clear();
mappingListeners.clear();
}
@Override
public boolean isServiceDiscovery() {
return true;
}
protected void subscribeURLs(URL url, NotifyListener listener, Set<String> serviceNames) {
serviceNames = toTreeSet(serviceNames);
String serviceNamesKey = toStringKeys(serviceNames);
String serviceKey = url.getServiceKey();
logger.info(
String.format("Trying to subscribe from apps %s for service key %s, ", serviceNamesKey, serviceKey));
// register ServiceInstancesChangedListener
Lock appSubscriptionLock = getAppSubscription(serviceNamesKey);
try {
appSubscriptionLock.lock();
ServiceInstancesChangedListener serviceInstancesChangedListener = serviceListeners.get(serviceNamesKey);
if (serviceInstancesChangedListener == null) {
serviceInstancesChangedListener = serviceDiscovery.createListener(serviceNames);
for (String serviceName : serviceNames) {
List<ServiceInstance> serviceInstances = serviceDiscovery.getInstances(serviceName);
if (CollectionUtils.isNotEmpty(serviceInstances)) {
serviceInstancesChangedListener.onEvent(
new ServiceInstancesChangedEvent(serviceName, serviceInstances));
}
}
serviceListeners.put(serviceNamesKey, serviceInstancesChangedListener);
}
if (!serviceInstancesChangedListener.isDestroyed()) {
listener.addServiceListener(serviceInstancesChangedListener);
serviceInstancesChangedListener.addListenerAndNotify(url, listener);
ServiceInstancesChangedListener finalServiceInstancesChangedListener = serviceInstancesChangedListener;
String serviceDiscoveryName =
url.getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, url.getProtocol());
MetricsEventBus.post(
RegistryEvent.toSsEvent(
url.getApplicationModel(), serviceKey, Collections.singletonList(serviceDiscoveryName)),
() -> {
serviceDiscovery.addServiceInstancesChangedListener(finalServiceInstancesChangedListener);
return null;
});
} else {
logger.info(String.format("Listener of %s has been destroyed by another thread.", serviceNamesKey));
serviceListeners.remove(serviceNamesKey);
}
} finally {
appSubscriptionLock.unlock();
}
}
/**
* Supports or not ?
*
* @param registryURL the {@link URL url} of registry
* @return if supported, return <code>true</code>, or <code>false</code>
*/
public static boolean supports(URL registryURL) {
return SERVICE_REGISTRY_TYPE.equalsIgnoreCase(registryURL.getParameter(REGISTRY_TYPE_KEY));
}
public Map<String, ServiceInstancesChangedListener> getServiceListeners() {
return serviceListeners;
}
private class DefaultMappingListener implements MappingListener {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultMappingListener.class);
private final URL url;
private final NotifyListener listener;
private volatile Set<String> oldApps;
private volatile boolean stopped;
public DefaultMappingListener(URL subscribedURL, Set<String> serviceNames, NotifyListener listener) {
this.url = subscribedURL;
this.oldApps = serviceNames;
this.listener = listener;
}
@Override
public synchronized void onEvent(MappingChangedEvent event) {
logger.info("Received mapping notification from meta server, " + event);
if (stopped) {
logger.warn(
INTERNAL_ERROR,
"",
"",
"Listener has been stopped, ignore mapping notification, check why listener is not removed.");
return;
}
Set<String> newApps = event.getApps();
Set<String> tempOldApps = oldApps;
Lock mappingLock = serviceNameMapping.getMappingLock(event.getServiceKey());
try {
mappingLock.lock();
if (CollectionUtils.isEmpty(newApps) || CollectionUtils.equals(newApps, tempOldApps)) {
return;
}
logger.info("Mapping of service " + event.getServiceKey() + "changed from " + tempOldApps + " to "
+ newApps);
if (CollectionUtils.isEmpty(tempOldApps) && !newApps.isEmpty()) {
serviceNameMapping.putCachedMapping(ServiceNameMapping.buildMappingKey(url), newApps);
subscribeURLs(url, listener, newApps);
oldApps = newApps;
return;
}
for (String newAppName : newApps) {
if (!tempOldApps.contains(newAppName)) {
serviceNameMapping.removeCachedMapping(ServiceNameMapping.buildMappingKey(url));
serviceNameMapping.putCachedMapping(ServiceNameMapping.buildMappingKey(url), newApps);
// old instance listener related to old app list that needs to be destroyed after subscribe
// refresh.
ServiceInstancesChangedListener oldListener = listener.getServiceListener();
if (oldListener != null) {
String appKey = toStringKeys(toTreeSet(tempOldApps));
Lock appSubscriptionLock = getAppSubscription(appKey);
try {
appSubscriptionLock.lock();
oldListener.removeListener(url.getServiceKey(), listener);
if (!oldListener.hasListeners()) {
oldListener.destroy();
serviceListeners.remove(appKey);
removeAppSubscriptionLock(appKey);
}
} finally {
appSubscriptionLock.unlock();
}
}
subscribeURLs(url, listener, newApps);
oldApps = newApps;
return;
}
}
} finally {
mappingLock.unlock();
}
}
protected NotifyListener getListener() {
return listener;
}
// writing of oldApps is protected by mapping lock to guarantee sequence consistency.
public void updateInitialApps(Set<String> oldApps) {
if (oldApps != null && !CollectionUtils.equals(oldApps, this.oldApps)) {
this.oldApps = oldApps;
logger.info("Update initial mapping apps from " + this.oldApps + " to " + oldApps);
}
}
@Override
public void stop() {
stopped = true;
}
}
public Lock getAppSubscription(String key) {
return ConcurrentHashMapUtils.computeIfAbsent(appSubscriptionLocks, key, _k -> new ReentrantLock());
}
public void removeAppSubscriptionLock(String key) {
Lock lock = appSubscriptionLocks.get(key);
if (lock != null) {
try {
lock.lock();
appSubscriptionLocks.remove(key);
} finally {
lock.unlock();
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java | /*
* 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.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.SPI;
import static org.apache.dubbo.common.extension.ExtensionScope.APPLICATION;
/**
* The factory to create {@link ServiceDiscovery}
*
* @see ServiceDiscovery
* @since 2.7.5
*/
@SPI(value = "default", scope = APPLICATION)
public interface ServiceDiscoveryFactory {
/**
* Get the instance of {@link ServiceDiscovery}
*
* @param registryURL the {@link URL} to connect the registry
* @return non-null
*/
ServiceDiscovery getServiceDiscovery(URL registryURL);
/**
* Get the extension instance of {@link ServiceDiscoveryFactory} by {@link URL#getProtocol() the protocol}
*
* @param registryURL the {@link URL} to connect the registry
* @return non-null
*/
static ServiceDiscoveryFactory getExtension(URL registryURL) {
String protocol = registryURL.getProtocol();
ExtensionLoader<ServiceDiscoveryFactory> loader =
registryURL.getOrDefaultApplicationModel().getExtensionLoader(ServiceDiscoveryFactory.class);
return loader.getOrDefaultExtension(protocol);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java | /*
* 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.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.MetadataReportInstance;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.metadata.event.MetadataEvent;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.registry.client.metadata.MetadataUtils;
import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils;
import org.apache.dubbo.registry.client.metadata.store.MetaCacheManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_INFO_CACHE_EXPIRE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_INFO_CACHE_SIZE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_INFO_CACHE_EXPIRE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_INFO_CACHE_SIZE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_LOAD_METADATA;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY;
import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getExportedServicesRevision;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.isValidInstance;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.setMetadataStorageType;
/**
* Each service discovery is bond to one application.
*/
public abstract class AbstractServiceDiscovery implements ServiceDiscovery {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractServiceDiscovery.class);
private volatile boolean isDestroy;
protected final String serviceName;
protected volatile ServiceInstance serviceInstance;
protected volatile MetadataInfo metadataInfo;
protected final ConcurrentHashMap<String, MetadataInfoStat> metadataInfos = new ConcurrentHashMap<>();
protected volatile ScheduledFuture<?> refreshCacheFuture;
protected MetadataReport metadataReport;
protected String metadataType;
protected final MetaCacheManager metaCacheManager;
protected URL registryURL;
protected Set<ServiceInstancesChangedListener> instanceListeners = new ConcurrentHashSet<>();
protected ApplicationModel applicationModel;
public AbstractServiceDiscovery(ApplicationModel applicationModel, URL registryURL) {
this(applicationModel, applicationModel.getApplicationName(), registryURL);
MetadataReportInstance metadataReportInstance =
applicationModel.getBeanFactory().getBean(MetadataReportInstance.class);
this.metadataType = metadataReportInstance.getMetadataType();
this.metadataReport = metadataReportInstance.getMetadataReport(registryURL.getParameter(REGISTRY_CLUSTER_KEY));
}
public AbstractServiceDiscovery(String serviceName, URL registryURL) {
this(ApplicationModel.defaultModel(), serviceName, registryURL);
}
private AbstractServiceDiscovery(ApplicationModel applicationModel, String serviceName, URL registryURL) {
this.applicationModel = applicationModel;
this.serviceName = serviceName;
this.registryURL = registryURL;
this.metadataInfo = new MetadataInfo(serviceName);
boolean localCacheEnabled = registryURL.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true);
this.metaCacheManager = new MetaCacheManager(
localCacheEnabled,
getCacheNameSuffix(),
applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getCacheRefreshingScheduledExecutor());
int metadataInfoCacheExpireTime =
registryURL.getParameter(METADATA_INFO_CACHE_EXPIRE_KEY, DEFAULT_METADATA_INFO_CACHE_EXPIRE);
int metadataInfoCacheSize =
registryURL.getParameter(METADATA_INFO_CACHE_SIZE_KEY, DEFAULT_METADATA_INFO_CACHE_SIZE);
startRefreshCache(metadataInfoCacheExpireTime / 2, metadataInfoCacheSize, metadataInfoCacheExpireTime);
}
private void removeExpiredMetadataInfo(int metadataInfoCacheSize, int metadataInfoCacheExpireTime) {
Long nextTime = null;
// Cache cleanup is only required when the cache size exceeds the cache limit.
if (metadataInfos.size() > metadataInfoCacheSize) {
List<MetadataInfoStat> values = new ArrayList<>(metadataInfos.values());
// Place the earliest data at the front
values.sort(Comparator.comparingLong(MetadataInfoStat::getUpdateTime));
for (MetadataInfoStat v : values) {
long time = System.currentTimeMillis() - v.getUpdateTime();
if (time > metadataInfoCacheExpireTime) {
metadataInfos.remove(v.metadataInfo.getRevision(), v);
} else {
// Calculate how long it will take for the next task to start
nextTime = metadataInfoCacheExpireTime - time;
break;
}
}
}
// If there is no metadata to clean up this time, the next task will start within half of the cache expiration
// time.
startRefreshCache(
nextTime == null ? metadataInfoCacheExpireTime / 2 : nextTime,
metadataInfoCacheSize,
metadataInfoCacheExpireTime);
}
private void startRefreshCache(long nextTime, int metadataInfoCacheSize, int metadataInfoCacheExpireTime) {
this.refreshCacheFuture = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getSharedScheduledExecutor()
.schedule(
() -> removeExpiredMetadataInfo(metadataInfoCacheSize, metadataInfoCacheExpireTime),
nextTime,
TimeUnit.MILLISECONDS);
}
@Override
public synchronized void register() throws RuntimeException {
if (isDestroy) {
return;
}
if (this.serviceInstance == null) {
ServiceInstance serviceInstance = createServiceInstance(this.metadataInfo);
if (!isValidInstance(serviceInstance)) {
return;
}
this.serviceInstance = serviceInstance;
}
boolean revisionUpdated = calOrUpdateInstanceRevision(this.serviceInstance);
if (revisionUpdated) {
try {
reportMetadata(this.metadataInfo);
doRegister(this.serviceInstance);
} catch (Exception e) {
this.serviceInstance = null;
throw e;
}
}
}
/**
* Update assumes that DefaultServiceInstance and its attributes will never get updated once created.
* Checking hasExportedServices() before registration guarantees that at least one service is ready for creating the
* instance.
*/
@Override
public synchronized void update() throws RuntimeException {
if (isDestroy) {
return;
}
if (this.serviceInstance == null) {
register();
}
if (!isValidInstance(this.serviceInstance)) {
return;
}
ServiceInstance oldServiceInstance = this.serviceInstance;
DefaultServiceInstance newServiceInstance =
new DefaultServiceInstance((DefaultServiceInstance) oldServiceInstance);
boolean revisionUpdated = calOrUpdateInstanceRevision(newServiceInstance);
if (revisionUpdated) {
logger.info(String.format(
"Metadata of instance changed, updating instance with revision %s.",
newServiceInstance.getServiceMetadata().getRevision()));
doUpdate(oldServiceInstance, newServiceInstance);
this.serviceInstance = newServiceInstance;
}
}
@Override
public synchronized void unregister() throws RuntimeException {
if (isDestroy) {
return;
}
// fixme, this metadata info might still being shared by other instances
// unReportMetadata(this.metadataInfo);
if (!isValidInstance(this.serviceInstance)) {
return;
}
doUnregister(this.serviceInstance);
}
@Override
public final ServiceInstance getLocalInstance() {
return this.serviceInstance;
}
@Override
public MetadataInfo getLocalMetadata() {
return this.metadataInfo;
}
@Override
public MetadataInfo getLocalMetadata(String revision) {
MetadataInfoStat metadataInfoStat = metadataInfos.get(revision);
if (metadataInfoStat != null) {
return metadataInfoStat.getMetadataInfo();
} else {
return null;
}
}
@Override
public MetadataInfo getRemoteMetadata(String revision, List<ServiceInstance> instances) {
MetadataInfo metadata = metaCacheManager.get(revision);
if (metadata != null && metadata != MetadataInfo.EMPTY) {
metadata.init();
// metadata loaded from cache
if (logger.isDebugEnabled()) {
logger.debug("MetadataInfo for revision=" + revision + ", " + metadata);
}
return metadata;
}
synchronized (metaCacheManager) {
// try to load metadata from remote.
int triedTimes = 0;
while (triedTimes < 3) {
metadata = MetricsEventBus.post(
MetadataEvent.toSubscribeEvent(applicationModel),
() -> MetadataUtils.getRemoteMetadata(revision, instances, metadataReport),
result -> result != MetadataInfo.EMPTY);
if (metadata != MetadataInfo.EMPTY) { // succeeded
metadata.init();
break;
} else { // failed
if (triedTimes > 0) {
if (logger.isDebugEnabled()) {
logger.debug("Retry the " + triedTimes + " times to get metadata for revision=" + revision);
}
}
triedTimes++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
if (metadata == MetadataInfo.EMPTY) {
logger.error(
REGISTRY_FAILED_LOAD_METADATA,
"",
"",
"Failed to get metadata for revision after 3 retries, revision=" + revision);
} else {
metaCacheManager.put(revision, metadata);
}
}
return metadata;
}
@Override
public MetadataInfo getRemoteMetadata(String revision) {
return metaCacheManager.get(revision);
}
@Override
public final void destroy() throws Exception {
isDestroy = true;
metaCacheManager.destroy();
refreshCacheFuture.cancel(true);
doDestroy();
}
@Override
public final boolean isDestroy() {
return isDestroy;
}
@Override
public void register(URL url) {
metadataInfo.addService(url);
}
@Override
public void unregister(URL url) {
metadataInfo.removeService(url);
}
@Override
public void subscribe(URL url, NotifyListener listener) {
metadataInfo.addSubscribedURL(url);
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
metadataInfo.removeSubscribedURL(url);
}
@Override
public List<URL> lookup(URL url) {
throw new UnsupportedOperationException(
"Service discovery implementation does not support lookup of url list.");
}
/**
* Update Service Instance. Unregister and then register by default.
* Can be override if registry support update instance directly.
* <br/>
* NOTICE: Remind to update {@link AbstractServiceDiscovery#serviceInstance}'s reference if updated
* and report metadata by {@link AbstractServiceDiscovery#reportMetadata(MetadataInfo)}
*
* @param oldServiceInstance origin service instance
* @param newServiceInstance new service instance
*/
protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) {
this.doUnregister(oldServiceInstance);
this.serviceInstance = newServiceInstance;
if (!EMPTY_REVISION.equals(getExportedServicesRevision(newServiceInstance))) {
reportMetadata(newServiceInstance.getServiceMetadata());
this.doRegister(newServiceInstance);
}
}
@Override
public URL getUrl() {
return registryURL;
}
protected abstract void doRegister(ServiceInstance serviceInstance) throws RuntimeException;
protected abstract void doUnregister(ServiceInstance serviceInstance);
protected abstract void doDestroy() throws Exception;
protected ServiceInstance createServiceInstance(MetadataInfo metadataInfo) {
DefaultServiceInstance instance = new DefaultServiceInstance(serviceName, applicationModel);
instance.setServiceMetadata(metadataInfo);
setMetadataStorageType(instance, metadataType);
ServiceInstanceMetadataUtils.customizeInstance(instance, applicationModel);
return instance;
}
protected boolean calOrUpdateInstanceRevision(ServiceInstance instance) {
String existingInstanceRevision = getExportedServicesRevision(instance);
MetadataInfo metadataInfo = instance.getServiceMetadata();
String newRevision = metadataInfo.calAndGetRevision();
if (!newRevision.equals(existingInstanceRevision)) {
instance.getMetadata().put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, metadataInfo.getRevision());
return true;
}
return false;
}
protected void reportMetadata(MetadataInfo metadataInfo) {
if (metadataInfo == null) {
return;
}
if (metadataReport != null) {
SubscriberMetadataIdentifier identifier =
new SubscriberMetadataIdentifier(serviceName, metadataInfo.getRevision());
if ((DEFAULT_METADATA_STORAGE_TYPE.equals(metadataType) && metadataReport.shouldReportMetadata())
|| REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) {
MetricsEventBus.post(MetadataEvent.toPushEvent(applicationModel), () -> {
metadataReport.publishAppMetadata(identifier, metadataInfo);
return null;
});
}
}
MetadataInfo clonedMetadataInfo = metadataInfo.clone();
metadataInfos.put(metadataInfo.getRevision(), new MetadataInfoStat(clonedMetadataInfo));
}
protected void unReportMetadata(MetadataInfo metadataInfo) {
if (metadataReport != null) {
SubscriberMetadataIdentifier identifier =
new SubscriberMetadataIdentifier(serviceName, metadataInfo.getRevision());
if ((DEFAULT_METADATA_STORAGE_TYPE.equals(metadataType) && metadataReport.shouldReportMetadata())
|| REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) {
metadataReport.unPublishAppMetadata(identifier, metadataInfo);
}
}
}
private String getCacheNameSuffix() {
String name = this.getClass().getSimpleName();
int i = name.indexOf(ServiceDiscovery.class.getSimpleName());
if (i != -1) {
name = name.substring(0, i);
}
StringBuilder stringBuilder = new StringBuilder(128);
Optional<ApplicationConfig> application =
applicationModel.getApplicationConfigManager().getApplication();
if (application.isPresent()) {
stringBuilder.append(application.get().getName());
stringBuilder.append(".");
}
stringBuilder.append(name.toLowerCase());
URL url = this.getUrl();
if (url != null) {
stringBuilder.append(".");
stringBuilder.append(url.getBackupAddress());
}
return stringBuilder.toString();
}
private static class MetadataInfoStat {
private final MetadataInfo metadataInfo;
private final long updateTime = System.currentTimeMillis();
public MetadataInfoStat(MetadataInfo metadataInfo) {
this.metadataInfo = metadataInfo;
}
public MetadataInfo getMetadataInfo() {
return metadataInfo;
}
public long getUpdateTime() {
return updateTime;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceDiscoveryFactory.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceDiscoveryFactory.java | /*
* 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;
/**
* This class is designed for compatibility purpose. When a specific registry type does not have counterpart service discovery provided,
* the nop instance will be returned.
*/
public class DefaultServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory {
@Override
protected ServiceDiscovery createDiscovery(URL registryURL) {
return new NopServiceDiscovery(registryURL.getApplicationModel(), registryURL);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultRegistryClusterIdentifier.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultRegistryClusterIdentifier.java | /*
* 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 static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY;
public class DefaultRegistryClusterIdentifier implements RegistryClusterIdentifier {
@Override
public String providerKey(URL url) {
return url.getParameter(REGISTRY_CLUSTER_KEY);
}
@Override
public String consumerKey(URL url) {
return url.getParameter(REGISTRY_CLUSTER_KEY);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/package-info.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/package-info.java | /*
* 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.
*/
/**
* * The inspiration of service registration and discovery comes from
* <a href="https://spring.io/projects/spring-cloud-commons">Spring Cloud Commons</a>.
*
* @since 2.7.5
*/
package org.apache.dubbo.registry.client;
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/OverrideInstanceAddressURL.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/OverrideInstanceAddressURL.java | /*
* 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.url.component.URLAddress;
import org.apache.dubbo.common.url.component.URLParam;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ServiceModel;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class OverrideInstanceAddressURL extends InstanceAddressURL {
private static final long serialVersionUID = 1373220432794558426L;
private final URLParam overrideParams;
private final InstanceAddressURL originUrl;
public OverrideInstanceAddressURL(InstanceAddressURL originUrl) {
this.originUrl = originUrl;
this.overrideParams = URLParam.parse("");
}
public OverrideInstanceAddressURL(InstanceAddressURL originUrl, URLParam overrideParams) {
this.originUrl = originUrl;
this.overrideParams = overrideParams;
}
@Override
public ServiceInstance getInstance() {
return originUrl.getInstance();
}
@Override
public MetadataInfo getMetadataInfo() {
return originUrl.getMetadataInfo();
}
@Override
public String getServiceInterface() {
return originUrl.getServiceInterface();
}
@Override
public String getGroup() {
return originUrl.getGroup();
}
@Override
public String getVersion() {
return originUrl.getVersion();
}
@Override
public String getProtocol() {
return originUrl.getProtocol();
}
@Override
public String getProtocolServiceKey() {
return originUrl.getProtocolServiceKey();
}
@Override
public String getServiceKey() {
return originUrl.getServiceKey();
}
@Override
public String getAddress() {
return originUrl.getAddress();
}
@Override
public String getHost() {
return originUrl.getHost();
}
@Override
public int getPort() {
return originUrl.getPort();
}
@Override
public String getIp() {
return originUrl.getIp();
}
@Override
public String getPath() {
return originUrl.getPath();
}
@Override
public String getParameter(String key) {
String overrideParam = overrideParams.getParameter(key);
return StringUtils.isNotEmpty(overrideParam) ? overrideParam : originUrl.getParameter(key);
}
@Override
public String getServiceParameter(String service, String key) {
String overrideParam = overrideParams.getParameter(key);
return StringUtils.isNotEmpty(overrideParam) ? overrideParam : originUrl.getServiceParameter(service, key);
}
@Override
public String getServiceMethodParameter(String protocolServiceKey, String method, String key) {
String overrideParam = overrideParams.getMethodParameter(method, key);
return StringUtils.isNotEmpty(overrideParam)
? overrideParam
: originUrl.getServiceMethodParameter(protocolServiceKey, method, key);
}
@Override
public String getMethodParameter(String method, String key) {
String overrideParam = overrideParams.getMethodParameter(method, key);
return StringUtils.isNotEmpty(overrideParam) ? overrideParam : originUrl.getMethodParameter(method, key);
}
@Override
public boolean hasServiceMethodParameter(String protocolServiceKey, String method, String key) {
return StringUtils.isNotEmpty(overrideParams.getMethodParameter(method, key))
|| originUrl.hasServiceMethodParameter(protocolServiceKey, method, key);
}
@Override
public boolean hasMethodParameter(String method, String key) {
return StringUtils.isNotEmpty(overrideParams.getMethodParameter(method, key))
|| originUrl.hasMethodParameter(method, key);
}
@Override
public boolean hasServiceMethodParameter(String protocolServiceKey, String method) {
return overrideParams.hasMethodParameter(method)
|| originUrl.hasServiceMethodParameter(protocolServiceKey, method);
}
@Override
public boolean hasMethodParameter(String method) {
return overrideParams.hasMethodParameter(method) || originUrl.hasMethodParameter(method);
}
@Override
public Map<String, String> getServiceParameters(String protocolServiceKey) {
Map<String, String> parameters = originUrl.getServiceParameters(protocolServiceKey);
Map<String, String> overrideParameters = overrideParams.getParameters();
Map<String, String> result = new HashMap<>((int) (parameters.size() + overrideParameters.size() / 0.75f) + 1);
result.putAll(parameters);
result.putAll(overrideParameters);
return result;
}
@Override
public Map<String, String> getParameters() {
Map<String, String> parameters = originUrl.getParameters();
Map<String, String> overrideParameters = overrideParams.getParameters();
Map<String, String> result = new HashMap<>((int) (parameters.size() + overrideParameters.size() / 0.75f) + 1);
result.putAll(parameters);
result.putAll(overrideParameters);
return result;
}
@Override
public URL addParameter(String key, String value) {
return new OverrideInstanceAddressURL(originUrl, overrideParams.addParameter(key, value));
}
@Override
public URL addParameterIfAbsent(String key, String value) {
return new OverrideInstanceAddressURL(originUrl, overrideParams.addParameterIfAbsent(key, value));
}
@Override
public URL addServiceParameter(String protocolServiceKey, String key, String value) {
return originUrl.addServiceParameter(protocolServiceKey, key, value);
}
@Override
public URL addServiceParameterIfAbsent(String protocolServiceKey, String key, String value) {
return originUrl.addServiceParameterIfAbsent(protocolServiceKey, key, value);
}
@Override
public URL addConsumerParams(String protocolServiceKey, Map<String, String> params) {
return originUrl.addConsumerParams(protocolServiceKey, params);
}
@Override
public String getAnyMethodParameter(String key) {
String overrideParam = overrideParams.getAnyMethodParameter(key);
return StringUtils.isNotEmpty(overrideParam) ? overrideParam : originUrl.getAnyMethodParameter(key);
}
@Override
public URL addParameters(Map<String, String> parameters) {
return new OverrideInstanceAddressURL(originUrl, overrideParams.addParameters(parameters));
}
@Override
public URL addParametersIfAbsent(Map<String, String> parameters) {
return new OverrideInstanceAddressURL(originUrl, overrideParams.addParametersIfAbsent(parameters));
}
@Override
public URLParam getUrlParam() {
return originUrl.getUrlParam();
}
@Override
public URLAddress getUrlAddress() {
return originUrl.getUrlAddress();
}
public URLParam getOverrideParams() {
return overrideParams;
}
@Override
public String getRemoteApplication() {
return originUrl.getRemoteApplication();
}
@Override
public String getSide() {
return originUrl.getSide();
}
@Override
public ScopeModel getScopeModel() {
return originUrl.getScopeModel();
}
@Override
public FrameworkModel getOrDefaultFrameworkModel() {
return originUrl.getOrDefaultFrameworkModel();
}
@Override
public ApplicationModel getOrDefaultApplicationModel() {
return originUrl.getOrDefaultApplicationModel();
}
@Override
public ApplicationModel getApplicationModel() {
return originUrl.getApplicationModel();
}
@Override
public ModuleModel getOrDefaultModuleModel() {
return originUrl.getOrDefaultModuleModel();
}
@Override
public ServiceModel getServiceModel() {
return originUrl.getServiceModel();
}
@Override
public Set<String> getProviderFirstParams() {
return originUrl.getProviderFirstParams();
}
@Override
public void setProviderFirstParams(Set<String> providerFirstParams) {
originUrl.setProviderFirstParams(providerFirstParams);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
OverrideInstanceAddressURL that = (OverrideInstanceAddressURL) o;
return Objects.equals(overrideParams, that.overrideParams) && Objects.equals(originUrl, that.originUrl);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), overrideParams, originUrl);
}
@Override
public String toString() {
return originUrl.toString() + ", overrideParams: " + overrideParams.toString();
}
private Object readResolve() {
// create a new object from the deserialized one
return new OverrideInstanceAddressURL(this.originUrl, this.overrideParams);
}
@Override
protected OverrideInstanceAddressURL newURL(URLAddress urlAddress, URLParam urlParam) {
return new OverrideInstanceAddressURL(originUrl, overrideParams);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactory.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactory.java | /*
* 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.ConcurrentHashMapUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Abstract {@link ServiceDiscoveryFactory} implementation with cache, the subclass
* should implement {@link #createDiscovery(URL)} method to create an instance of {@link ServiceDiscovery}
*
* @see ServiceDiscoveryFactory
* @since 2.7.5
*/
public abstract class AbstractServiceDiscoveryFactory implements ServiceDiscoveryFactory, ScopeModelAware {
protected ApplicationModel applicationModel;
private final ConcurrentMap<String, ServiceDiscovery> discoveries = new ConcurrentHashMap<>();
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
public List<ServiceDiscovery> getAllServiceDiscoveries() {
return Collections.unmodifiableList(new LinkedList<>(discoveries.values()));
}
@Override
public ServiceDiscovery getServiceDiscovery(URL registryURL) {
String key = createRegistryCacheKey(registryURL);
return ConcurrentHashMapUtils.computeIfAbsent(discoveries, key, k -> createDiscovery(registryURL));
}
protected String createRegistryCacheKey(URL url) {
return url.toServiceStringWithoutResolving();
}
protected abstract ServiceDiscovery createDiscovery(URL registryURL);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java | /*
* 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.lang.Prioritized;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import java.util.List;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_DELAY_NOTIFICATION_KEY;
/**
* Defines the common operations of Service Discovery, extended and loaded by ServiceDiscoveryFactory
*/
public interface ServiceDiscovery extends RegistryService, Prioritized {
void register() throws RuntimeException;
void update() throws RuntimeException;
void unregister() throws RuntimeException;
/**
* Gets all service names
*
* @return non-null read-only {@link Set}
*/
Set<String> getServices();
List<ServiceInstance> getInstances(String serviceName) throws NullPointerException;
default void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener)
throws NullPointerException, IllegalArgumentException {}
/**
* unsubscribe to instance change event.
*
* @param listener
* @throws IllegalArgumentException
*/
default void removeServiceInstancesChangedListener(ServiceInstancesChangedListener listener)
throws IllegalArgumentException {}
default ServiceInstancesChangedListener createListener(Set<String> serviceNames) {
return new ServiceInstancesChangedListener(serviceNames, this);
}
ServiceInstance getLocalInstance();
MetadataInfo getLocalMetadata();
default MetadataInfo getLocalMetadata(String revision) {
return getLocalMetadata();
}
MetadataInfo getRemoteMetadata(String revision);
MetadataInfo getRemoteMetadata(String revision, List<ServiceInstance> instances);
/**
* Destroy the {@link ServiceDiscovery}
*
* @throws Exception If met with error
*/
void destroy() throws Exception;
boolean isDestroy();
default URL getUrl() {
return null;
}
default long getDelay() {
return getUrl().getParameter(REGISTRY_DELAY_NOTIFICATION_KEY, 5000);
}
/**
* Get services is the default way for service discovery to be available
*/
default boolean isAvailable() {
return !isDestroy() && CollectionUtils.isNotEmpty(getServices());
}
/**
* A human-readable description of the implementation
*
* @return The description.
*/
@Override
String toString();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/NopServiceDiscovery.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/NopServiceDiscovery.java | /*
* 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.rpc.model.ApplicationModel;
import java.util.List;
import java.util.Set;
public class NopServiceDiscovery extends AbstractServiceDiscovery {
public NopServiceDiscovery(String serviceName, URL registryURL) {
super(serviceName, registryURL);
}
public NopServiceDiscovery(ApplicationModel applicationModel, URL registryURL) {
super(applicationModel, registryURL);
}
@Override
public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {}
@Override
public void doUnregister(ServiceInstance serviceInstance) {}
@Override
public void doDestroy() throws Exception {}
@Override
public Set<String> getServices() {
return null;
}
@Override
public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException {
return null;
}
@Override
public boolean isAvailable() {
// NopServiceDiscovery is designed for compatibility, check availability is meaningless, just return true
return true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java | /*
* 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.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.DubboServiceAddressURL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.AddressListener;
import org.apache.dubbo.registry.Constants;
import org.apache.dubbo.registry.ProviderFirstParams;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.integration.AbstractConfiguratorListener;
import org.apache.dubbo.registry.integration.DynamicDirectory;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.RpcServiceContext;
import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.RouterChain;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INSTANCE_REGISTER_MODE;
import static org.apache.dubbo.common.constants.CommonConstants.IS_EXTRA;
import static org.apache.dubbo.common.constants.CommonConstants.PREFERRED_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DESTROY_INVOKER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REFER_INVOKER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_HASHMAP_LOAD_FACTOR;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE;
import static org.apache.dubbo.registry.Constants.CONFIGURATORS_SUFFIX;
import static org.apache.dubbo.rpc.model.ScopeModelUtil.getModuleModel;
public class ServiceDiscoveryRegistryDirectory<T> extends DynamicDirectory<T> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ServiceDiscoveryRegistryDirectory.class);
/**
* instance address to invoker mapping.
* The initial value is null and the midway may be assigned to null, please use the local variable reference
*/
private volatile Map<ProtocolServiceKeyWithAddress, Invoker<T>> urlInvokerMap;
private volatile ReferenceConfigurationListener referenceConfigurationListener;
private volatile boolean enableConfigurationListen = true;
private volatile List<URL> originalUrls = null;
private volatile Map<String, String> overrideQueryMap;
private final Set<String> providerFirstParams;
private final ModuleModel moduleModel;
private final ProtocolServiceKey consumerProtocolServiceKey;
private final ConcurrentMap<ProtocolServiceKey, URL> customizedConsumerUrlMap = new ConcurrentHashMap<>();
public ServiceDiscoveryRegistryDirectory(Class<T> serviceType, URL url) {
super(serviceType, url);
moduleModel = getModuleModel(url.getScopeModel());
Set<ProviderFirstParams> providerFirstParams = url.getOrDefaultApplicationModel()
.getExtensionLoader(ProviderFirstParams.class)
.getSupportedExtensionInstances();
if (CollectionUtils.isEmpty(providerFirstParams)) {
this.providerFirstParams = null;
} else {
if (providerFirstParams.size() == 1) {
this.providerFirstParams = Collections.unmodifiableSet(
providerFirstParams.iterator().next().params());
} else {
Set<String> params = new HashSet<>();
for (ProviderFirstParams paramsFilter : providerFirstParams) {
if (paramsFilter.params() == null) {
break;
}
params.addAll(paramsFilter.params());
}
this.providerFirstParams = Collections.unmodifiableSet(params);
}
}
String protocol = consumerUrl.getParameter(PROTOCOL_KEY, consumerUrl.getProtocol());
consumerProtocolServiceKey = new ProtocolServiceKey(
consumerUrl.getServiceInterface(),
consumerUrl.getVersion(),
consumerUrl.getGroup(),
!CommonConstants.CONSUMER.equals(protocol) ? protocol : null);
}
@Override
public void subscribe(URL url) {
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
enableConfigurationListen = true;
getConsumerConfigurationListener(moduleModel).addNotifyListener(this);
referenceConfigurationListener = new ReferenceConfigurationListener(this.moduleModel, this, url);
} else {
enableConfigurationListen = false;
}
super.subscribe(url);
}
private ConsumerConfigurationListener getConsumerConfigurationListener(ModuleModel moduleModel) {
return moduleModel
.getBeanFactory()
.getOrRegisterBean(
ConsumerConfigurationListener.class, type -> new ConsumerConfigurationListener(moduleModel));
}
@Override
public void unSubscribe(URL url) {
super.unSubscribe(url);
this.originalUrls = null;
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
getConsumerConfigurationListener(moduleModel).removeNotifyListener(this);
referenceConfigurationListener.stop();
}
}
@Override
public void destroy() {
super.destroy();
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
getConsumerConfigurationListener(moduleModel).removeNotifyListener(this);
referenceConfigurationListener.stop();
}
}
@Override
public void buildRouterChain(URL url) {
this.setRouterChain(
RouterChain.buildChain(getInterface(), url.addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)));
}
@Override
public synchronized void notify(List<URL> instanceUrls) {
if (isDestroyed()) {
return;
}
// Set the context of the address notification thread.
RpcServiceContext.getServiceContext().setConsumerUrl(getConsumerUrl());
// 3.x added for extend URL address
ExtensionLoader<AddressListener> addressListenerExtensionLoader =
getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class);
List<AddressListener> supportedListeners =
addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null);
if (supportedListeners != null && !supportedListeners.isEmpty()) {
for (AddressListener addressListener : supportedListeners) {
instanceUrls = addressListener.notify(instanceUrls, getConsumerUrl(), this);
}
}
refreshOverrideAndInvoker(instanceUrls);
}
// RefreshOverrideAndInvoker will be executed by registryCenter and configCenter, so it should be synchronized.
@Override
protected synchronized void refreshOverrideAndInvoker(List<URL> instanceUrls) {
// mock zookeeper://xxx?mock=return null
this.directoryUrl = overrideDirectoryWithConfigurator(getOriginalConsumerUrl());
refreshInvoker(instanceUrls);
}
protected URL overrideDirectoryWithConfigurator(URL url) {
// override url with configurator from "app-name.configurators"
url = overrideWithConfigurators(
getConsumerConfigurationListener(moduleModel).getConfigurators(), url);
// override url with configurator from configurators from "service-name.configurators"
if (referenceConfigurationListener != null) {
url = overrideWithConfigurators(referenceConfigurationListener.getConfigurators(), url);
}
return url;
}
private URL overrideWithConfigurators(List<Configurator> configurators, URL url) {
if (CollectionUtils.isNotEmpty(configurators)) {
if (url instanceof DubboServiceAddressURL) {
DubboServiceAddressURL interfaceAddressURL = (DubboServiceAddressURL) url;
URL overriddenURL = interfaceAddressURL.getOverrideURL();
if (overriddenURL == null) {
String appName = interfaceAddressURL.getApplication();
String side = interfaceAddressURL.getSide();
overriddenURL = URLBuilder.from(interfaceAddressURL)
.clearParameters()
.addParameter(APPLICATION_KEY, appName)
.addParameter(SIDE_KEY, side)
.build();
}
for (Configurator configurator : configurators) {
overriddenURL = configurator.configure(overriddenURL);
}
url = new DubboServiceAddressURL(
interfaceAddressURL.getUrlAddress(),
interfaceAddressURL.getUrlParam(),
interfaceAddressURL.getConsumerURL(),
(ServiceConfigURL) overriddenURL);
} else {
for (Configurator configurator : configurators) {
url = configurator.configure(url);
}
}
}
return url;
}
protected InstanceAddressURL overrideWithConfigurator(InstanceAddressURL providerUrl) {
// override url with configurator from "app-name.configurators"
providerUrl = overrideWithConfigurators(
getConsumerConfigurationListener(moduleModel).getConfigurators(), providerUrl);
// override url with configurator from configurators from "service-name.configurators"
if (referenceConfigurationListener != null) {
providerUrl = overrideWithConfigurators(referenceConfigurationListener.getConfigurators(), providerUrl);
}
return providerUrl;
}
private InstanceAddressURL overrideWithConfigurators(List<Configurator> configurators, InstanceAddressURL url) {
if (CollectionUtils.isNotEmpty(configurators)) {
// wrap url
OverrideInstanceAddressURL overrideInstanceAddressURL = new OverrideInstanceAddressURL(url);
if (overrideQueryMap != null) {
// override app-level configs
overrideInstanceAddressURL =
(OverrideInstanceAddressURL) overrideInstanceAddressURL.addParameters(overrideQueryMap);
}
for (Configurator configurator : configurators) {
overrideInstanceAddressURL =
(OverrideInstanceAddressURL) configurator.configure(overrideInstanceAddressURL);
}
return overrideInstanceAddressURL;
}
return url;
}
@Override
public boolean isServiceDiscovery() {
return true;
}
/**
* This implementation makes sure all application names related to serviceListener received address notification.
* <p>
* FIXME, make sure deprecated "interface-application" mapping item be cleared in time.
*/
@Override
public boolean isNotificationReceived() {
return serviceListener == null
|| serviceListener.isDestroyed()
|| serviceListener.getAllInstances().size()
== serviceListener.getServiceNames().size();
}
private void refreshInvoker(List<URL> invokerUrls) {
Assert.notNull(invokerUrls, "invokerUrls should not be null, use EMPTY url to clear current addresses.");
this.originalUrls = invokerUrls;
if (invokerUrls.size() == 1 && EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) {
logger.warn(
PROTOCOL_UNSUPPORTED,
"",
"",
String.format(
"Received url with EMPTY protocol from registry %s, will clear all available addresses.",
this));
refreshRouter(
BitList.emptyList(), () -> this.forbidden = true // Forbid to access
);
destroyAllInvokers(); // Close all invokers
} else {
this.forbidden = false; // Allow accessing
if (CollectionUtils.isEmpty(invokerUrls)) {
logger.warn(
PROTOCOL_UNSUPPORTED,
"",
"",
String.format(
"Received empty url list from registry %s, will ignore for protection purpose.", this));
return;
}
int originSize = invokerUrls.size();
invokerUrls = invokerUrls.stream().distinct().collect(Collectors.toList());
if (invokerUrls.size() != originSize) {
logger.info("Received duplicated invoker urls changed event from registry. "
+ "Registry type: instance. "
+ "Service Key: "
+ getConsumerUrl().getServiceKey() + ". "
+ "Notify Urls Size : " + originSize + ". "
+ "Distinct Urls Size: " + invokerUrls.size() + ".");
}
// use local reference to avoid NPE as this.urlInvokerMap will be set null concurrently at
// destroyAllInvokers().
Map<ProtocolServiceKeyWithAddress, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap;
// can't use local reference as oldUrlInvokerMap's mappings might be removed directly at toInvokers().
Map<ProtocolServiceKeyWithAddress, Invoker<T>> oldUrlInvokerMap = null;
if (localUrlInvokerMap != null) {
// the initial capacity should be set greater than the maximum number of entries divided by the load
// factor to avoid resizing.
oldUrlInvokerMap =
new LinkedHashMap<>(Math.round(1 + localUrlInvokerMap.size() / DEFAULT_HASHMAP_LOAD_FACTOR));
localUrlInvokerMap.forEach(oldUrlInvokerMap::put);
}
Map<ProtocolServiceKeyWithAddress, Invoker<T>> newUrlInvokerMap =
toInvokers(oldUrlInvokerMap, invokerUrls); // Translate url list to Invoker map
logger.info(String.format("Refreshed invoker size %s from registry %s", newUrlInvokerMap.size(), this));
if (CollectionUtils.isEmptyMap(newUrlInvokerMap)) {
logger.error(
PROTOCOL_UNSUPPORTED,
"",
"",
"Unsupported protocol.",
new IllegalStateException(String.format(
"Cannot create invokers from url address list (total %s)", invokerUrls.size())));
return;
}
List<Invoker<T>> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values()));
BitList<Invoker<T>> finalInvokers =
multiGroup ? new BitList<>(toMergeInvokerList(newInvokers)) : new BitList<>(newInvokers);
// pre-route and build cache
refreshRouter(finalInvokers.clone(), () -> this.setInvokers(finalInvokers));
this.urlInvokerMap = newUrlInvokerMap;
if (oldUrlInvokerMap != null) {
try {
destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // Close the unused Invoker
} catch (Exception e) {
logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", "destroyUnusedInvokers error. ", e);
}
}
}
// notify invokers refreshed
this.invokersChanged();
logger.info("Received invokers changed event from registry. " + "Registry type: instance. "
+ "Service Key: "
+ getConsumerUrl().getServiceKey() + ". " + "Urls Size : "
+ invokerUrls.size() + ". " + "Invokers Size : "
+ getInvokers().size() + ". " + "Available Size: "
+ getValidInvokers().size() + ". " + "Available Invokers : "
+ joinValidInvokerAddresses());
}
/**
* Turn urls into invokers, and if url has been refer, will not re-reference.
* the items that will be put into newUrlInvokeMap will be removed from oldUrlInvokerMap.
*
* @param oldUrlInvokerMap it might be modified during the process.
* @param urls
* @return invokers
*/
private Map<ProtocolServiceKeyWithAddress, Invoker<T>> toInvokers(
Map<ProtocolServiceKeyWithAddress, Invoker<T>> oldUrlInvokerMap, List<URL> urls) {
Map<ProtocolServiceKeyWithAddress, Invoker<T>> newUrlInvokerMap =
new ConcurrentHashMap<>(urls == null ? 1 : (int) (urls.size() / 0.75f + 1));
if (urls == null || urls.isEmpty()) {
return newUrlInvokerMap;
}
for (URL url : urls) {
InstanceAddressURL instanceAddressURL = (InstanceAddressURL) url;
if (EMPTY_PROTOCOL.equals(instanceAddressURL.getProtocol())) {
continue;
}
if (!getUrl().getOrDefaultFrameworkModel()
.getExtensionLoader(Protocol.class)
.hasExtension(instanceAddressURL.getProtocol())) {
// 4-1 - Unsupported protocol
logger.error(
PROTOCOL_UNSUPPORTED,
"protocol extension does not installed",
"",
"Unsupported protocol.",
new IllegalStateException("Unsupported protocol " + instanceAddressURL.getProtocol()
+ " in notified url: "
+ instanceAddressURL + " from registry " + getUrl().getAddress() + " to consumer "
+ NetUtils.getLocalHost() + ", supported protocol: "
+ getUrl().getOrDefaultFrameworkModel()
.getExtensionLoader(Protocol.class)
.getSupportedExtensions()));
continue;
}
instanceAddressURL.setProviderFirstParams(providerFirstParams);
// Override provider urls if needed
if (enableConfigurationListen) {
instanceAddressURL = overrideWithConfigurator(instanceAddressURL);
}
// filter all the service available (version wildcard, group wildcard, protocol wildcard)
List<ProtocolServiceKey> matchedProtocolServiceKeys =
getMatchedProtocolServiceKeys(instanceAddressURL, true);
if (CollectionUtils.isEmpty(matchedProtocolServiceKeys)) {
// if preferred protocol is not specified, use the default main protocol
matchedProtocolServiceKeys = getMatchedProtocolServiceKeys(instanceAddressURL, false);
}
// see org.apache.dubbo.common.ProtocolServiceKey.isSameWith
// check if needed to override the consumer url
boolean shouldWrap = matchedProtocolServiceKeys.size() != 1
|| !consumerProtocolServiceKey.isSameWith(matchedProtocolServiceKeys.get(0));
for (ProtocolServiceKey matchedProtocolServiceKey : matchedProtocolServiceKeys) {
ProtocolServiceKeyWithAddress protocolServiceKeyWithAddress =
new ProtocolServiceKeyWithAddress(matchedProtocolServiceKey, instanceAddressURL.getAddress());
Invoker<T> invoker =
oldUrlInvokerMap == null ? null : oldUrlInvokerMap.get(protocolServiceKeyWithAddress);
if (invoker == null
|| urlChanged(
invoker,
instanceAddressURL,
matchedProtocolServiceKey)) { // Not in the cache, refer again
try {
boolean enabled;
if (instanceAddressURL.hasParameter(DISABLED_KEY)) {
enabled = !instanceAddressURL.getParameter(DISABLED_KEY, false);
} else {
enabled = instanceAddressURL.getParameter(ENABLED_KEY, true);
}
if (enabled) {
if (shouldWrap) {
URL newConsumerUrl = ConcurrentHashMapUtils.computeIfAbsent(
customizedConsumerUrlMap, matchedProtocolServiceKey, k -> consumerUrl
.setProtocol(k.getProtocol())
.addParameter(CommonConstants.GROUP_KEY, k.getGroup())
.addParameter(CommonConstants.VERSION_KEY, k.getVersion()));
RpcContext.getServiceContext().setConsumerUrl(newConsumerUrl);
invoker = new InstanceWrappedInvoker<>(
protocol.refer(serviceType, instanceAddressURL),
newConsumerUrl,
matchedProtocolServiceKey);
} else {
invoker = protocol.refer(serviceType, instanceAddressURL);
}
}
} catch (Throwable t) {
logger.error(
PROTOCOL_FAILED_REFER_INVOKER,
"",
"",
"Failed to refer invoker for interface:" + serviceType + ",url:(" + instanceAddressURL
+ ")" + t.getMessage(),
t);
}
if (invoker != null) { // Put new invoker in cache
newUrlInvokerMap.put(protocolServiceKeyWithAddress, invoker);
}
} else {
newUrlInvokerMap.put(protocolServiceKeyWithAddress, invoker);
oldUrlInvokerMap.remove(protocolServiceKeyWithAddress, invoker);
}
}
}
return newUrlInvokerMap;
}
private List<ProtocolServiceKey> getMatchedProtocolServiceKeys(
InstanceAddressURL instanceAddressURL, boolean needPreferred) {
int port = instanceAddressURL.getPort();
return instanceAddressURL.getMetadataInfo().getMatchedServiceInfos(consumerProtocolServiceKey).stream()
.filter(serviceInfo -> serviceInfo.getPort() <= 0 || serviceInfo.getPort() == port)
// special filter for extra protocols.
.filter(serviceInfo -> {
if (StringUtils.isNotEmpty(
consumerProtocolServiceKey
.getProtocol())) { // if consumer side protocol is specified, use all
// the protocols we got in hand now directly
return true;
} else {
// if consumer side protocol is not specified, choose the preferred or default main protocol
if (needPreferred) {
return serviceInfo.getProtocol().equals(serviceInfo.getParameter(PREFERRED_PROTOCOL));
} else {
return StringUtils.isEmpty(serviceInfo.getParameter(IS_EXTRA));
}
}
})
.map(MetadataInfo.ServiceInfo::getProtocolServiceKey)
.collect(Collectors.toList());
}
private boolean urlChanged(Invoker<T> invoker, InstanceAddressURL newURL, ProtocolServiceKey protocolServiceKey) {
InstanceAddressURL oldURL = (InstanceAddressURL) invoker.getUrl();
if (!newURL.getInstance().equals(oldURL.getInstance())) {
return true;
}
if (oldURL instanceof OverrideInstanceAddressURL || newURL instanceof OverrideInstanceAddressURL) {
if (!(oldURL instanceof OverrideInstanceAddressURL && newURL instanceof OverrideInstanceAddressURL)) {
// sub-class changed
return true;
} else {
if (!((OverrideInstanceAddressURL) oldURL)
.getOverrideParams()
.equals(((OverrideInstanceAddressURL) newURL).getOverrideParams())) {
return true;
}
}
}
MetadataInfo.ServiceInfo oldServiceInfo =
oldURL.getMetadataInfo().getValidServiceInfo(protocolServiceKey.toString());
if (null == oldServiceInfo) {
return false;
}
return !oldServiceInfo.equals(newURL.getMetadataInfo().getValidServiceInfo(protocolServiceKey.toString()));
}
private List<Invoker<T>> toMergeInvokerList(List<Invoker<T>> invokers) {
List<Invoker<T>> mergedInvokers = new ArrayList<>();
Map<String, List<Invoker<T>>> groupMap = new HashMap<>();
for (Invoker<T> invoker : invokers) {
String group = invoker.getUrl().getGroup("");
groupMap.computeIfAbsent(group, k -> new ArrayList<>());
groupMap.get(group).add(invoker);
}
if (groupMap.size() == 1) {
mergedInvokers.addAll(groupMap.values().iterator().next());
} else if (groupMap.size() > 1) {
for (List<Invoker<T>> groupList : groupMap.values()) {
StaticDirectory<T> staticDirectory = new StaticDirectory<>(groupList);
staticDirectory.buildRouterChain();
mergedInvokers.add(cluster.join(staticDirectory, false));
}
} else {
mergedInvokers = invokers;
}
return mergedInvokers;
}
/**
* Close all invokers
*/
@Override
protected void destroyAllInvokers() {
Map<ProtocolServiceKeyWithAddress, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap; // local reference
if (localUrlInvokerMap != null) {
for (Invoker<T> invoker : new ArrayList<>(localUrlInvokerMap.values())) {
try {
invoker.destroy();
} catch (Throwable t) {
logger.warn(
PROTOCOL_FAILED_DESTROY_INVOKER,
"",
"",
"Failed to destroy service " + serviceKey + " to provider " + invoker.getUrl(),
t);
}
}
localUrlInvokerMap.clear();
}
this.urlInvokerMap = null;
this.destroyInvokers();
}
@Override
protected Map<String, String> getDirectoryMeta() {
String registryKey = Optional.ofNullable(getRegistry())
.map(Registry::getUrl)
.map(url -> url.getParameter(
RegistryConstants.REGISTRY_CLUSTER_KEY,
url.getParameter(RegistryConstants.REGISTRY_KEY, url.getProtocol())))
.orElse("unknown");
Map<String, String> metas = new HashMap<>();
metas.put(REGISTRY_KEY, registryKey);
metas.put(REGISTER_MODE_KEY, INSTANCE_REGISTER_MODE);
return metas;
}
/**
* Check whether the invoker in the cache needs to be destroyed
* If set attribute of url: refer.autodestroy=false, the invokers will only increase without decreasing,there may be a refer leak
*
* @param oldUrlInvokerMap
* @param newUrlInvokerMap
*/
private void destroyUnusedInvokers(
Map<ProtocolServiceKeyWithAddress, Invoker<T>> oldUrlInvokerMap,
Map<ProtocolServiceKeyWithAddress, Invoker<T>> newUrlInvokerMap) {
if (newUrlInvokerMap == null || newUrlInvokerMap.size() == 0) {
destroyAllInvokers();
return;
}
if (oldUrlInvokerMap == null || oldUrlInvokerMap.size() == 0) {
return;
}
for (Map.Entry<ProtocolServiceKeyWithAddress, Invoker<T>> entry : oldUrlInvokerMap.entrySet()) {
Invoker<T> invoker = entry.getValue();
if (invoker != null) {
try {
invoker.destroy();
if (logger.isDebugEnabled()) {
logger.debug("destroy invoker[" + invoker.getUrl() + "] success. ");
}
} catch (Exception e) {
logger.warn(
PROTOCOL_FAILED_DESTROY_INVOKER,
"",
"",
"destroy invoker[" + invoker.getUrl() + "]failed." + e.getMessage(),
e);
}
}
}
logger.info(oldUrlInvokerMap.size() + " deprecated invokers deleted.");
}
private class ReferenceConfigurationListener extends AbstractConfiguratorListener {
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/InstanceAddressURL.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/InstanceAddressURL.java | /*
* 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.url.component.ServiceConfigURL;
import org.apache.dubbo.common.url.component.URLAddress;
import org.apache.dubbo.common.url.component.URLParam;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ServiceModel;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
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.REMOTE_APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.common.utils.StringUtils.isEquals;
public class InstanceAddressURL extends URL {
private final ServiceInstance instance;
private final MetadataInfo metadataInfo;
// cached numbers
private transient volatile Set<String> providerFirstParams;
// one instance address url serves only one protocol.
private final transient String protocol;
protected InstanceAddressURL() {
this(null, null, null);
}
public InstanceAddressURL(ServiceInstance instance, MetadataInfo metadataInfo) {
this.instance = instance;
this.metadataInfo = metadataInfo;
this.protocol = DUBBO;
}
public InstanceAddressURL(ServiceInstance instance, MetadataInfo metadataInfo, String protocol) {
this.instance = instance;
this.metadataInfo = metadataInfo;
this.protocol = protocol;
}
public ServiceInstance getInstance() {
return instance;
}
public MetadataInfo getMetadataInfo() {
return metadataInfo;
}
@Override
public String getServiceInterface() {
return RpcContext.getServiceContext().getInterfaceName();
}
@Override
public String getGroup() {
return RpcContext.getServiceContext().getGroup();
}
@Override
public String getVersion() {
return RpcContext.getServiceContext().getVersion();
}
@Override
public String getProtocol() {
return protocol;
}
@Override
public String getProtocolServiceKey() {
// if protocol is not specified on consumer side, return serviceKey.
URL consumerURL = RpcContext.getServiceContext().getConsumerUrl();
String consumerProtocol = consumerURL == null ? null : consumerURL.getProtocol();
if (isEquals(consumerProtocol, CONSUMER)) {
return RpcContext.getServiceContext().getServiceKey();
}
// if protocol is specified on consumer side, return accurate protocolServiceKey
else {
return RpcContext.getServiceContext().getProtocolServiceKey();
}
}
@Override
public String getServiceKey() {
return RpcContext.getServiceContext().getServiceKey();
}
@Override
public URL setProtocol(String protocol) {
return new ServiceConfigURL(
protocol, getUsername(), getPassword(), getHost(), getPort(), getPath(), getParameters(), attributes);
}
@Override
public URL setHost(String host) {
return new ServiceConfigURL(
getProtocol(), getUsername(), getPassword(), host, getPort(), getPath(), getParameters(), attributes);
}
@Override
public URL setPort(int port) {
return new ServiceConfigURL(
getProtocol(), getUsername(), getPassword(), getHost(), port, getPath(), getParameters(), attributes);
}
@Override
public URL setPath(String path) {
return new ServiceConfigURL(
getProtocol(), getUsername(), getPassword(), getHost(), getPort(), path, getParameters(), attributes);
}
@Override
public String getAddress() {
return instance.getAddress();
}
@Override
public String getHost() {
return instance.getHost();
}
@Override
public int getPort() {
return instance.getPort();
}
@Override
public String getIp() {
return instance.getHost();
}
@Override
public String getRemoteApplication() {
return instance.getServiceName();
}
@Override
public String getSide() {
return CONSUMER_SIDE;
}
@Override
public String getPath() {
MetadataInfo.ServiceInfo serviceInfo = null;
String protocolServiceKey = getProtocolServiceKey();
if (StringUtils.isNotEmpty(protocolServiceKey)) {
serviceInfo = getServiceInfo(protocolServiceKey);
}
if (serviceInfo == null) {
return getServiceInterface();
}
return serviceInfo.getPath();
}
@Override
public String getOriginalParameter(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();
} else if (REMOTE_APPLICATION_KEY.equals(key)) {
return instance.getServiceName();
} else if (SIDE_KEY.equals(key)) {
return getSide();
}
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return getInstanceParameter(key);
}
return getServiceParameter(protocolServiceKey, key);
}
@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();
} else if (REMOTE_APPLICATION_KEY.equals(key)) {
return instance.getServiceName();
} else if (SIDE_KEY.equals(key)) {
return getSide();
}
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
String v = consumerUrl.getParameter(key);
if (StringUtils.isNotEmpty(v)) {
return v;
}
}
}
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return getInstanceParameter(key);
}
return getServiceParameter(protocolServiceKey, key);
}
@Override
public String getOriginalServiceParameter(String service, String key) {
if (metadataInfo != null) {
String value = metadataInfo.getParameter(key, service);
if (StringUtils.isNotEmpty(value)) {
return value;
}
}
return getInstanceParameter(key);
}
@Override
public String getServiceParameter(String service, String key) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
String v = consumerUrl.getServiceParameter(service, key);
if (StringUtils.isNotEmpty(v)) {
return v;
}
}
}
if (metadataInfo != null) {
String value = metadataInfo.getParameter(key, service);
if (StringUtils.isNotEmpty(value)) {
return value;
}
}
return getInstanceParameter(key);
}
/**
* method parameter only exists in ServiceInfo
*
* @param method
* @param key
* @return
*/
@Override
public String getServiceMethodParameter(String protocolServiceKey, String method, String key) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
String v = consumerUrl.getServiceMethodParameter(protocolServiceKey, method, key);
if (StringUtils.isNotEmpty(v)) {
return v;
}
}
}
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null == serviceInfo) {
return getParameter(key);
}
String value = serviceInfo.getMethodParameter(method, key, null);
if (StringUtils.isNotEmpty(value)) {
return value;
}
return getParameter(key);
}
@Override
public String getMethodParameter(String method, String key) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
String v = consumerUrl.getMethodParameter(method, key);
if (StringUtils.isNotEmpty(v)) {
return v;
}
}
}
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
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) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
if (consumerUrl.hasServiceMethodParameter(protocolServiceKey, method, key)) {
return true;
}
}
}
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (isEmpty(method)) {
String suffix = "." + key;
for (String fullKey : getParameters().keySet()) {
if (fullKey.endsWith(suffix)) {
return true;
}
}
return false;
}
if (isEmpty(key)) {
String prefix = method + ".";
for (String fullKey : getParameters().keySet()) {
if (fullKey.startsWith(prefix)) {
return true;
}
}
return false;
}
if (null == serviceInfo) {
return false;
}
return serviceInfo.hasMethodParameter(method, key);
}
@Override
public boolean hasMethodParameter(String method, String key) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
if (consumerUrl.hasMethodParameter(method, key)) {
return true;
}
}
}
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return false;
}
return hasServiceMethodParameter(protocolServiceKey, method, key);
}
/**
* method parameter only exists in ServiceInfo
*
* @param method
* @return
*/
@Override
public boolean hasServiceMethodParameter(String protocolServiceKey, String method) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
if (consumerUrl.hasServiceMethodParameter(protocolServiceKey, method)) {
return true;
}
}
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null == serviceInfo) {
return false;
}
return serviceInfo.hasMethodParameter(method);
}
@Override
public boolean hasMethodParameter(String method) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
if (consumerUrl.hasMethodParameter(method)) {
return true;
}
}
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return false;
}
return hasServiceMethodParameter(protocolServiceKey, method);
}
@Override
public Map<String, String> getOriginalServiceParameters(String protocolServiceKey) {
Map<String, String> instanceParams = getInstance().getAllParams();
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;
}
/**
* Avoid calling this method in RPC call.
*
* @return
*/
@Override
public Map<String, String> getServiceParameters(String protocolServiceKey) {
Map<String, String> instanceParams = getInstance().getAllParams();
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);
}
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
Map<String, String> consumerParams = new HashMap<>(consumerUrl.getParameters());
if (CollectionUtils.isNotEmpty(providerFirstParams)) {
providerFirstParams.forEach(consumerParams::remove);
}
params.putAll(consumerParams);
}
return params;
}
@Override
public Map<String, String> getOriginalParameters() {
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return getInstance().getAllParams();
}
return getOriginalServiceParameters(protocolServiceKey);
}
@Override
public Map<String, String> getParameters() {
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return getInstance().getAllParams();
}
return getServiceParameters(protocolServiceKey);
}
@Override
public URL addParameter(String key, String value) {
if (isEmpty(key) || isEmpty(value)) {
return this;
}
getInstance().putExtendParam(key, value);
return this;
}
@Override
public URL addParameterIfAbsent(String key, String value) {
if (isEmpty(key) || isEmpty(value)) {
return this;
}
getInstance().putExtendParamIfAbsent(key, value);
return this;
}
public URL addServiceParameter(String protocolServiceKey, String key, String value) {
if (isEmpty(key) || isEmpty(value)) {
return this;
}
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null != serviceInfo) {
serviceInfo.addParameter(key, value);
}
return this;
}
public URL addServiceParameterIfAbsent(String protocolServiceKey, String key, String value) {
if (isEmpty(key) || isEmpty(value)) {
return this;
}
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null != serviceInfo) {
serviceInfo.addParameterIfAbsent(key, value);
}
return this;
}
public URL addConsumerParams(String protocolServiceKey, Map<String, String> params) {
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null != serviceInfo) {
serviceInfo.addConsumerParams(params);
}
return this;
}
/**
* Gets method level value of the specified key.
*
* @param key
* @return
*/
@Override
public String getAnyMethodParameter(String key) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
String v = consumerUrl.getAnyMethodParameter(key);
if (StringUtils.isNotEmpty(v)) {
return v;
}
}
}
String suffix = "." + key;
String protocolServiceKey = getProtocolServiceKey();
if (StringUtils.isNotEmpty(protocolServiceKey)) {
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null == serviceInfo) {
return null;
}
for (String fullKey : serviceInfo.getAllParams().keySet()) {
if (fullKey.endsWith(suffix)) {
return getParameter(fullKey);
}
}
}
return null;
}
@Override
public URLParam getUrlParam() {
throw new UnsupportedOperationException("URLParam is replaced with MetadataInfo in instance url");
}
@Override
public URLAddress getUrlAddress() {
throw new UnsupportedOperationException("URLAddress is replaced with ServiceInstance in instance url");
}
private MetadataInfo.ServiceInfo getServiceInfo(String protocolServiceKey) {
return metadataInfo.getValidServiceInfo(protocolServiceKey);
}
private String getInstanceParameter(String key) {
String value = this.instance.getMetadata().get(key);
if (StringUtils.isNotEmpty(value)) {
return value;
}
return this.instance.getExtendParam(key);
}
private Map<String, String> getInstanceMetadata() {
return this.instance.getMetadata();
}
@Override
public FrameworkModel getOrDefaultFrameworkModel() {
return instance.getOrDefaultApplicationModel().getFrameworkModel();
}
@Override
public ApplicationModel getOrDefaultApplicationModel() {
return instance.getOrDefaultApplicationModel();
}
@Override
public ApplicationModel getApplicationModel() {
return instance.getApplicationModel();
}
@Override
public ScopeModel getScopeModel() {
return Optional.ofNullable(RpcContext.getServiceContext().getConsumerUrl())
.map(URL::getScopeModel)
.orElse(super.getScopeModel());
}
@Override
public ServiceModel getServiceModel() {
return RpcContext.getServiceContext().getConsumerUrl().getServiceModel();
}
public Set<String> getProviderFirstParams() {
return providerFirstParams;
}
public void setProviderFirstParams(Set<String> providerFirstParams) {
this.providerFirstParams = providerFirstParams;
}
private boolean consumerParamFirst(String key) {
if (CollectionUtils.isNotEmpty(providerFirstParams)) {
return !providerFirstParams.contains(key);
} else {
return true;
}
}
@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();
}
@Override
public String toString() {
if (instance == null) {
return "{}";
}
if (metadataInfo == null) {
return instance.toString();
}
String protocolServiceKey = getProtocolServiceKey();
if (StringUtils.isNotEmpty(protocolServiceKey)) {
return instance.toString() + ", " + metadataInfo.getServiceString(protocolServiceKey);
}
return instance.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ReflectionBasedServiceDiscovery.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ReflectionBasedServiceDiscovery.java | /*
* 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.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.InstanceMetadataChangedListener;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metadata.RevisionResolver;
import org.apache.dubbo.registry.Constants;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation;
import org.apache.dubbo.registry.client.metadata.MetadataUtils;
import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.service.Destroyable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT;
public class ReflectionBasedServiceDiscovery extends AbstractServiceDiscovery {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
/**
* Echo check if consumer is still work
* echo task may take a lot of time when consumer offline, create a new ScheduledThreadPool
*/
private final ScheduledExecutorService echoCheckExecutor =
Executors.newScheduledThreadPool(1, new NamedThreadFactory("Dubbo-Registry-EchoCheck-Consumer"));
// =================================== Provider side =================================== //
/**
* Local {@link ServiceInstance} Metadata's revision
*/
private String lastMetadataRevision;
// =================================== Consumer side =================================== //
/**
* Local Cache of {@link ServiceInstance} Metadata
* <p>
* Key - {@link ServiceInstance} ID ( usually ip + port )
* Value - Json processed metadata string
*/
private final ConcurrentHashMap<String, String> metadataMap = new ConcurrentHashMap<>();
/**
* Local Cache of {@link ServiceInstance}
* <p>
* Key - Service Name
* Value - List {@link ServiceInstance}
*/
private final ConcurrentHashMap<String, List<ServiceInstance>> cachedServiceInstances = new ConcurrentHashMap<>();
private final MetadataServiceDelegation metadataService;
public ConcurrentMap<String, MetadataService> metadataServiceProxies = new ConcurrentHashMap<>();
/**
* Local Cache of Service's {@link ServiceInstance} list revision,
* used to check if {@link ServiceInstance} list has been updated
* <p>
* Key - ServiceName
* Value - a revision calculate from {@link List} of {@link ServiceInstance}
*/
private final ConcurrentHashMap<String, String> serviceInstanceRevisionMap = new ConcurrentHashMap<>();
public ReflectionBasedServiceDiscovery(ApplicationModel applicationModel, URL registryURL) {
super(applicationModel, registryURL);
long echoPollingCycle =
registryURL.getParameter(Constants.ECHO_POLLING_CYCLE_KEY, Constants.DEFAULT_ECHO_POLLING_CYCLE);
this.metadataService = applicationModel.getBeanFactory().getOrRegisterBean(MetadataServiceDelegation.class);
// Echo check: test if consumer is offline, remove MetadataChangeListener,
// reduce the probability of failure when metadata update
echoCheckExecutor.scheduleAtFixedRate(
() -> {
Map<String, InstanceMetadataChangedListener> listenerMap =
metadataService.getInstanceMetadataChangedListenerMap();
Iterator<Map.Entry<String, InstanceMetadataChangedListener>> iterator =
listenerMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, InstanceMetadataChangedListener> entry = iterator.next();
try {
entry.getValue().echo(CommonConstants.DUBBO);
} catch (RpcException e) {
if (logger.isInfoEnabled()) {
logger.info(
"Send echo message to consumer error. Possible cause: consumer is offline.");
}
iterator.remove();
}
}
},
echoPollingCycle,
echoPollingCycle,
TimeUnit.MILLISECONDS);
}
public void doInitialize(URL registryURL) {}
@Override
public void doDestroy() throws Exception {
metadataMap.clear();
serviceInstanceRevisionMap.clear();
echoCheckExecutor.shutdown();
}
private void updateInstanceMetadata(ServiceInstance serviceInstance) {
String metadataString = JsonUtils.toJson(serviceInstance.getMetadata());
String metadataRevision = RevisionResolver.calRevision(metadataString);
// check if metadata updated
if (!metadataRevision.equalsIgnoreCase(lastMetadataRevision)) {
if (logger.isDebugEnabled()) {
logger.debug("Update Service Instance Metadata of DNS registry. Newer metadata: " + metadataString);
}
lastMetadataRevision = metadataRevision;
// save the newest metadata to local
metadataService.exportInstanceMetadata(metadataString);
// notify to consumer
Map<String, InstanceMetadataChangedListener> listenerMap =
metadataService.getInstanceMetadataChangedListenerMap();
Iterator<Map.Entry<String, InstanceMetadataChangedListener>> iterator =
listenerMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, InstanceMetadataChangedListener> entry = iterator.next();
try {
entry.getValue().onEvent(metadataString);
} catch (RpcException e) {
// 1-7 - Failed to notify registry event.
// The updating of metadata to consumer is a type of registry event.
logger.warn(
REGISTRY_FAILED_NOTIFY_EVENT,
"consumer is offline",
"",
"Notify to consumer error, removing listener.");
// remove listener if consumer is offline
iterator.remove();
}
}
}
}
@Override
public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {
updateInstanceMetadata(serviceInstance);
}
@Override
public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException {
// notify empty message to consumer
metadataService.exportInstanceMetadata("");
metadataService.getInstanceMetadataChangedListenerMap().forEach((consumerId, listener) -> listener.onEvent(""));
metadataService.getInstanceMetadataChangedListenerMap().clear();
}
@SuppressWarnings("unchecked")
public final void fillServiceInstance(DefaultServiceInstance serviceInstance) {
String hostId = serviceInstance.getAddress();
if (metadataMap.containsKey(hostId)) {
// Use cached metadata.
// Metadata will be updated by provider callback
String metadataString = metadataMap.get(hostId);
serviceInstance.setMetadata(JsonUtils.toJavaObject(metadataString, Map.class));
} else {
// refer from MetadataUtils, this proxy is different from the one used to refer exportedURL
MetadataService metadataService = getMetadataServiceProxy(serviceInstance);
String consumerId = ScopeModelUtil.getApplicationModel(registryURL.getScopeModel())
.getApplicationName()
+ NetUtils.getLocalHost();
String metadata = metadataService.getAndListenInstanceMetadata(consumerId, metadataString -> {
if (logger.isDebugEnabled()) {
logger.debug("Receive callback: " + metadataString + serviceInstance);
}
if (StringUtils.isEmpty(metadataString)) {
// provider is shutdown
metadataMap.remove(hostId);
} else {
metadataMap.put(hostId, metadataString);
}
});
metadataMap.put(hostId, metadata);
serviceInstance.setMetadata(JsonUtils.toJavaObject(metadata, Map.class));
}
}
public final void notifyListener(
String serviceName, ServiceInstancesChangedListener listener, List<ServiceInstance> instances) {
String serviceInstanceRevision = RevisionResolver.calRevision(JsonUtils.toJson(instances));
boolean changed = !serviceInstanceRevision.equalsIgnoreCase(
serviceInstanceRevisionMap.put(serviceName, serviceInstanceRevision));
if (logger.isDebugEnabled()) {
logger.debug("Service changed event received (possibly because of DNS polling). "
+ "Service Instance changed: " + changed + " Service Name: " + serviceName);
}
if (changed) {
List<ServiceInstance> oldServiceInstances =
cachedServiceInstances.getOrDefault(serviceName, new LinkedList<>());
// remove expired invoker
Set<ServiceInstance> allServiceInstances = new HashSet<>(oldServiceInstances.size() + instances.size());
allServiceInstances.addAll(oldServiceInstances);
allServiceInstances.addAll(instances);
oldServiceInstances.forEach(allServiceInstances::remove);
allServiceInstances.forEach(this::destroyMetadataServiceProxy);
cachedServiceInstances.put(serviceName, instances);
listener.onEvent(new ServiceInstancesChangedEvent(serviceName, instances));
}
}
@Override
public Set<String> getServices() {
return Collections.emptySet();
}
@Override
public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException {
return Collections.emptyList();
}
private String computeKey(ServiceInstance serviceInstance) {
return serviceInstance.getServiceName() + "##" + serviceInstance.getAddress() + "##"
+ ServiceInstanceMetadataUtils.getExportedServicesRevision(serviceInstance);
}
private synchronized MetadataService getMetadataServiceProxy(ServiceInstance instance) {
Object internalProxy = MetadataUtils.referMetadataService(instance).getInternalProxy();
if (internalProxy instanceof MetadataService) {
return ConcurrentHashMapUtils.computeIfAbsent(
metadataServiceProxies, computeKey(instance), k -> (MetadataService) internalProxy);
}
throw new RuntimeException("Service " + instance.getServiceName() + " at " + instance.getHost() + ":"
+ instance.getPort() + "are using MetadataServiceV2, which is not support ");
}
private synchronized void destroyMetadataServiceProxy(ServiceInstance instance) {
String key = computeKey(instance);
if (metadataServiceProxies.containsKey(key)) {
Object metadataServiceProxy = metadataServiceProxies.remove(key);
if (metadataServiceProxy instanceof Destroyable) {
((Destroyable) metadataServiceProxy).$destroy();
}
}
}
/**
* UT used only
*/
@Deprecated
public final ConcurrentHashMap<String, List<ServiceInstance>> getCachedServiceInstances() {
return cachedServiceInstances;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryService.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryService.java | /*
* 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;
public interface ServiceDiscoveryService {
void register() throws RuntimeException;
void update() throws RuntimeException;
void unregister() throws RuntimeException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryFactory.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryFactory.java | /*
* 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.UrlUtils;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.support.AbstractRegistryFactory;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY;
public class ServiceDiscoveryRegistryFactory extends AbstractRegistryFactory {
@Override
protected String createRegistryCacheKey(URL url) {
return url.toFullString();
}
@Override
protected Registry createRegistry(URL url) {
if (UrlUtils.hasServiceDiscoveryRegistryProtocol(url)) {
String protocol = url.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY);
url = url.setProtocol(protocol).removeParameter(REGISTRY_KEY);
}
return new ServiceDiscoveryRegistry(url, applicationModel);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java | /*
* 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.metadata.MetadataInfo;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.beans.Transient;
import java.io.Serializable;
import java.util.Map;
import java.util.SortedMap;
/**
* The model class of an instance of a service, which is used for service registration and discovery.
* <p>
*
* @since 2.7.5
*/
public interface ServiceInstance extends Serializable {
/**
* The name of service that current instance belongs to.
*
* @return non-null
*/
String getServiceName();
/**
* The hostname of the registered service instance.
*
* @return non-null
*/
String getHost();
/**
* The port of the registered service instance.
*
* @return the positive integer if present
*/
int getPort();
String getAddress();
/**
* The enabled status of the registered service instance.
*
* @return if <code>true</code>, indicates current instance is enabled, or disable, the client should remove this one.
* The default value is <code>true</code>
*/
default boolean isEnabled() {
return true;
}
/**
* The registered service instance is health or not.
*
* @return if <code>true</code>, indicates current instance is healthy, or unhealthy, the client may ignore this one.
* The default value is <code>true</code>
*/
default boolean isHealthy() {
return true;
}
/**
* The key / value pair metadata associated with the service instance.
*
* @return non-null, mutable and unsorted {@link Map}
*/
Map<String, String> getMetadata();
SortedMap<String, String> getSortedMetadata();
String getRegistryCluster();
void setRegistryCluster(String registryCluster);
Map<String, String> getExtendParams();
String getExtendParam(String key);
String putExtendParam(String key, String value);
String putExtendParamIfAbsent(String key, String value);
String removeExtendParam(String key);
Map<String, String> getAllParams();
void setApplicationModel(ApplicationModel applicationModel);
@Transient
ApplicationModel getApplicationModel();
@Transient
default ApplicationModel getOrDefaultApplicationModel() {
return ScopeModelUtil.getApplicationModel(getApplicationModel());
}
/**
* Get the value of metadata by the specified name
*
* @param name the specified name
* @return the value of metadata if found, or <code>null</code>
* @since 2.7.8
*/
default String getMetadata(String name) {
return getMetadata(name, null);
}
/**
* Get the value of metadata by the specified name
*
* @param name the specified name
* @return the value of metadata if found, or <code>defaultValue</code>
* @since 2.7.8
*/
default String getMetadata(String name, String defaultValue) {
return getMetadata().getOrDefault(name, defaultValue);
}
MetadataInfo getServiceMetadata();
void setServiceMetadata(MetadataInfo serviceMetadata);
InstanceAddressURL toURL(String protocol);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java | /*
* 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.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.ENDPOINTS;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME;
/**
* The default implementation of {@link ServiceInstance}.
*
* @since 2.7.5
*/
public class DefaultServiceInstance implements ServiceInstance {
private static final long serialVersionUID = 1149677083747278100L;
private String rawAddress;
private String serviceName;
private String host;
private int port;
private boolean enabled = true;
private boolean healthy = true;
private Map<String, String> metadata = new HashMap<>();
private transient String address;
private transient MetadataInfo serviceMetadata;
/**
* used at runtime
*/
private transient String registryCluster;
/**
* extendParams can be more flexible, but one single property uses less space
*/
private transient Map<String, String> extendParams;
private transient List<Endpoint> endpoints;
private transient ApplicationModel applicationModel;
private transient ConcurrentHashMap<String, InstanceAddressURL> instanceAddressURL = new ConcurrentHashMap<>();
public DefaultServiceInstance() {}
public DefaultServiceInstance(DefaultServiceInstance other) {
this.serviceName = other.serviceName;
this.host = other.host;
this.port = other.port;
this.enabled = other.enabled;
this.healthy = other.healthy;
this.serviceMetadata = other.serviceMetadata;
this.registryCluster = other.registryCluster;
this.address = null;
this.metadata = new HashMap<>(other.metadata);
this.applicationModel = other.applicationModel;
this.extendParams = other.extendParams != null ? new HashMap<>(other.extendParams) : other.extendParams;
this.endpoints = other.endpoints != null ? new ArrayList<>(other.endpoints) : other.endpoints;
}
public DefaultServiceInstance(String serviceName, String host, Integer port, ApplicationModel applicationModel) {
if (port == null || port < 1) {
throw new IllegalArgumentException("The port value is illegal, the value is " + port);
}
this.serviceName = serviceName;
this.host = host;
this.port = port;
setApplicationModel(applicationModel);
}
public DefaultServiceInstance(String serviceName, ApplicationModel applicationModel) {
this.serviceName = serviceName;
setApplicationModel(applicationModel);
}
public void setRawAddress(String rawAddress) {
this.rawAddress = rawAddress;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public void setHost(String host) {
this.host = host;
}
@Override
public String getServiceName() {
return serviceName;
}
@Override
public String getHost() {
return host;
}
public void setPort(int port) {
this.port = port;
}
@Override
public int getPort() {
return port;
}
@Override
public String getAddress() {
if (address == null) {
address = getAddress(host, port);
}
return address;
}
private static String getAddress(String host, Integer port) {
return port != null && port <= 0 ? host : host + ':' + port;
}
@Override
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public boolean isHealthy() {
return healthy;
}
public void setHealthy(boolean healthy) {
this.healthy = healthy;
}
@Override
public Map<String, String> getMetadata() {
return metadata;
}
@Override
public SortedMap<String, String> getSortedMetadata() {
return new TreeMap<>(getMetadata());
}
@Override
public String getRegistryCluster() {
return registryCluster;
}
@Override
public void setRegistryCluster(String registryCluster) {
this.registryCluster = registryCluster;
}
@Override
public Map<String, String> getExtendParams() {
if (extendParams == null) {
return Collections.emptyMap();
}
return extendParams;
}
@Override
public String getExtendParam(String key) {
if (extendParams == null) {
return null;
}
return extendParams.get(key);
}
@Override
public String putExtendParam(String key, String value) {
if (extendParams == null) {
extendParams = new HashMap<>();
}
return extendParams.put(key, value);
}
@Override
public String putExtendParamIfAbsent(String key, String value) {
if (extendParams == null) {
extendParams = new HashMap<>();
}
return extendParams.putIfAbsent(key, value);
}
@Override
public String removeExtendParam(String key) {
if (extendParams == null) {
return null;
}
return extendParams.remove(key);
}
public void setEndpoints(List<Endpoint> endpoints) {
this.endpoints = endpoints;
}
public List<Endpoint> getEndpoints() {
if (endpoints == null) {
endpoints = new LinkedList<>(JsonUtils.toJavaList(metadata.get(ENDPOINTS), Endpoint.class));
}
return endpoints;
}
public DefaultServiceInstance copyFrom(Endpoint endpoint) {
DefaultServiceInstance copyOfInstance = new DefaultServiceInstance(this);
copyOfInstance.setPort(endpoint.getPort());
return copyOfInstance;
}
public DefaultServiceInstance copyFrom(int port) {
DefaultServiceInstance copyOfInstance = new DefaultServiceInstance(this);
copyOfInstance.setPort(port);
return copyOfInstance;
}
@Override
public Map<String, String> getAllParams() {
if (extendParams == null) {
return metadata;
} else {
Map<String, String> allParams = new HashMap<>((int) ((metadata.size() + extendParams.size()) / 0.75f + 1));
allParams.putAll(metadata);
allParams.putAll(extendParams);
return allParams;
}
}
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
@Transient
public ApplicationModel getApplicationModel() {
return applicationModel;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
@Override
public MetadataInfo getServiceMetadata() {
return serviceMetadata;
}
@Override
public void setServiceMetadata(MetadataInfo serviceMetadata) {
this.serviceMetadata = serviceMetadata;
this.instanceAddressURL.clear();
}
@Override
public InstanceAddressURL toURL(String protocol) {
return ConcurrentHashMapUtils.computeIfAbsent(
instanceAddressURL, protocol, key -> new InstanceAddressURL(this, serviceMetadata, protocol));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof DefaultServiceInstance)) {
return false;
}
DefaultServiceInstance that = (DefaultServiceInstance) o;
boolean equals = Objects.equals(getServiceName(), that.getServiceName())
&& Objects.equals(getHost(), that.getHost())
&& Objects.equals(getPort(), that.getPort());
for (Map.Entry<String, String> entry : this.getMetadata().entrySet()) {
if (entry.getKey().equals(EXPORTED_SERVICES_REVISION_PROPERTY_NAME)) {
continue;
}
if (entry.getValue() == null) {
equals = equals && (entry.getValue() == that.getMetadata().get(entry.getKey()));
} else {
equals = equals && entry.getValue().equals(that.getMetadata().get(entry.getKey()));
}
}
return equals;
}
@Override
public int hashCode() {
int result = Objects.hash(getServiceName(), getHost(), getPort());
for (Map.Entry<String, String> entry : this.getMetadata().entrySet()) {
if (entry.getKey().equals(EXPORTED_SERVICES_REVISION_PROPERTY_NAME)) {
continue;
}
result = 31 * result
+ (entry.getValue() == null ? 0 : entry.getValue().hashCode());
}
return result;
}
@Override
public String toString() {
return rawAddress == null ? toFullString() : rawAddress;
}
public String toFullString() {
return "DefaultServiceInstance{" + "serviceName='"
+ serviceName + '\'' + ", host='"
+ host + '\'' + ", port="
+ port + ", enabled="
+ enabled + ", healthy="
+ healthy + ", metadata="
+ metadata + '}';
}
public static class Endpoint {
int port;
String protocol;
public Endpoint() {}
public Endpoint(int port, String protocol) {
this.port = port;
this.protocol = protocol;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryClusterIdentifier.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryClusterIdentifier.java | /*
* 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.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_TYPE_KEY;
@SPI
public interface RegistryClusterIdentifier {
String providerKey(URL url);
String consumerKey(URL url);
static RegistryClusterIdentifier getExtension(URL url) {
ExtensionLoader<RegistryClusterIdentifier> loader =
ScopeModelUtil.getExtensionLoader(RegistryClusterIdentifier.class, url.getScopeModel());
return loader.getExtension(url.getParameter(REGISTRY_CLUSTER_TYPE_KEY, "default"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.registry.event.RegistryEvent;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.DefaultServiceInstance.Endpoint;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
import org.apache.dubbo.registry.support.RegistryManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.utils.StringUtils.isBlank;
import static org.apache.dubbo.registry.integration.InterfaceCompatibleRegistryProtocol.DEFAULT_REGISTER_PROVIDER_KEYS;
import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY;
/**
* The Utilities class for the {@link ServiceInstance#getMetadata() metadata of the service instance}
*
* @see StandardMetadataServiceURLBuilder
* @see ServiceInstance#getMetadata()
* @see MetadataService
* @see URL
* @since 2.7.5
*/
public class ServiceInstanceMetadataUtils {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(ServiceInstanceMetadataUtils.class);
/**
* The prefix of {@link MetadataService} : "dubbo.metadata-service."
*/
public static final String METADATA_SERVICE_PREFIX = "dubbo.metadata-service.";
public static final String ENDPOINTS = "dubbo.endpoints";
/**
* The property name of metadata JSON of {@link MetadataService}'s {@link URL}
*/
public static final String METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME = METADATA_SERVICE_PREFIX + "url-params";
/**
* The {@link URL URLs} property name of {@link MetadataService} :
* "dubbo.metadata-service.urls", which is used to be compatible with Dubbo Spring Cloud and
* discovery the metadata of instance
*/
public static final String METADATA_SERVICE_URLS_PROPERTY_NAME = METADATA_SERVICE_PREFIX + "urls";
/**
* The property name of The revision for all exported Dubbo services.
*/
public static final String EXPORTED_SERVICES_REVISION_PROPERTY_NAME = "dubbo.metadata.revision";
/**
* The property name of metadata storage type.
*/
public static final String METADATA_STORAGE_TYPE_PROPERTY_NAME = "dubbo.metadata.storage-type";
public static final String METADATA_SERVICE_VERSION_NAME = "meta-v";
public static final String METADATA_CLUSTER_PROPERTY_NAME = "dubbo.metadata.cluster";
public static String getMetadataServiceParameter(URL url) {
if (url == null) {
return "";
}
url = url.removeParameters(APPLICATION_KEY, GROUP_KEY, DEPRECATED_KEY, TIMESTAMP_KEY);
Map<String, String> params = getParams(url);
if (params.isEmpty()) {
return null;
}
return JsonUtils.toJson(params);
}
private static Map<String, String> getParams(URL providerURL) {
Map<String, String> params = new LinkedHashMap<>();
setDefaultParams(params, providerURL);
params.put(PORT_KEY, String.valueOf(providerURL.getPort()));
params.put(PROTOCOL_KEY, providerURL.getProtocol());
return params;
}
/**
* The revision for all exported Dubbo services from the specified {@link ServiceInstance}.
*
* @param serviceInstance the specified {@link ServiceInstance}
* @return <code>null</code> if not exits
*/
public static String getExportedServicesRevision(ServiceInstance serviceInstance) {
return Optional.ofNullable(serviceInstance.getServiceMetadata())
.map(MetadataInfo::getRevision)
.filter(StringUtils::isNotEmpty)
.orElse(serviceInstance.getMetadata(EXPORTED_SERVICES_REVISION_PROPERTY_NAME));
}
/**
* Get metadata's storage type
*
* @param registryURL the {@link URL} to connect the registry
* @return if not found in {@link URL#getParameters() parameters} of {@link URL registry URL}, return
*/
public static String getMetadataStorageType(URL registryURL) {
return registryURL.getParameter(METADATA_STORAGE_TYPE_PROPERTY_NAME, DEFAULT_METADATA_STORAGE_TYPE);
}
/**
* Get the metadata storage type specified by the peer instance.
*
* @return storage type, remote or local
*/
public static String getMetadataStorageType(ServiceInstance serviceInstance) {
Map<String, String> metadata = serviceInstance.getMetadata();
return metadata.getOrDefault(METADATA_STORAGE_TYPE_PROPERTY_NAME, DEFAULT_METADATA_STORAGE_TYPE);
}
/**
* Set the metadata storage type in specified {@link ServiceInstance service instance}
*
* @param serviceInstance {@link ServiceInstance service instance}
* @param metadataType remote or local
*/
public static void setMetadataStorageType(ServiceInstance serviceInstance, String metadataType) {
Map<String, String> metadata = serviceInstance.getMetadata();
metadata.put(METADATA_STORAGE_TYPE_PROPERTY_NAME, metadataType);
}
public static String getRemoteCluster(ServiceInstance serviceInstance) {
Map<String, String> metadata = serviceInstance.getMetadata();
return metadata.get(METADATA_CLUSTER_PROPERTY_NAME);
}
public static boolean hasEndpoints(ServiceInstance serviceInstance) {
return StringUtils.isNotEmpty(serviceInstance.getMetadata().get(ENDPOINTS));
}
public static void setEndpoints(ServiceInstance serviceInstance, Map<String, Integer> protocolPorts) {
Map<String, String> metadata = serviceInstance.getMetadata();
List<Endpoint> endpoints = new ArrayList<>();
protocolPorts.forEach((k, v) -> {
Endpoint endpoint = new Endpoint(v, k);
endpoints.add(endpoint);
});
metadata.put(ENDPOINTS, JsonUtils.toJson(endpoints));
}
/**
* Get the property value of port by the specified {@link ServiceInstance#getMetadata() the metadata of
* service instance} and protocol
*
* @param serviceInstance {@link ServiceInstance service instance}
* @param protocol the name of protocol, e.g, dubbo, rest, and so on
* @return if not found, return <code>null</code>
*/
public static Endpoint getEndpoint(ServiceInstance serviceInstance, String protocol) {
List<Endpoint> endpoints = ((DefaultServiceInstance) serviceInstance).getEndpoints();
if (endpoints != null) {
for (Endpoint endpoint : endpoints) {
if (endpoint.getProtocol().equals(protocol)) {
return endpoint;
}
}
}
return null;
}
public static void registerMetadataAndInstance(ApplicationModel applicationModel) {
RegistryManager registryManager = applicationModel.getBeanFactory().getBean(RegistryManager.class);
// register service instance
if (CollectionUtils.isNotEmpty(registryManager.getServiceDiscoveries())) {
LOGGER.info("[METADATA_REGISTER] Start registering instance address to registry.");
List<ServiceDiscovery> serviceDiscoveries = registryManager.getServiceDiscoveries();
for (ServiceDiscovery serviceDiscovery : serviceDiscoveries) {
MetricsEventBus.post(
RegistryEvent.toRegisterEvent(
applicationModel, Collections.singletonList(getServiceDiscoveryName(serviceDiscovery))),
() -> {
// register service instance
serviceDiscovery.register();
return null;
});
}
}
}
private static String getServiceDiscoveryName(ServiceDiscovery serviceDiscovery) {
return serviceDiscovery
.getUrl()
.getParameter(
RegistryConstants.REGISTRY_CLUSTER_KEY,
serviceDiscovery.getUrl().getParameter(REGISTRY_KEY));
}
public static void refreshMetadataAndInstance(ApplicationModel applicationModel) {
RegistryManager registryManager = applicationModel.getBeanFactory().getBean(RegistryManager.class);
// update service instance revision
registryManager.getServiceDiscoveries().forEach(ServiceDiscovery::update);
}
public static void unregisterMetadataAndInstance(ApplicationModel applicationModel) {
RegistryManager registryManager = applicationModel.getBeanFactory().getBean(RegistryManager.class);
registryManager.getServiceDiscoveries().forEach(serviceDiscovery -> {
try {
serviceDiscovery.unregister();
} catch (Exception ignored) {
// ignored
}
});
}
public static void customizeInstance(ServiceInstance instance, ApplicationModel applicationModel) {
ExtensionLoader<ServiceInstanceCustomizer> loader =
instance.getOrDefaultApplicationModel().getExtensionLoader(ServiceInstanceCustomizer.class);
// FIXME, sort customizer before apply
loader.getSupportedExtensionInstances().forEach(customizer -> {
// customize
customizer.customize(instance, applicationModel);
});
}
public static boolean isValidInstance(ServiceInstance instance) {
return instance != null && instance.getHost() != null && instance.getPort() != 0;
}
/**
* Set the default parameters via the specified {@link URL providerURL}
*
* @param params the parameters
* @param providerURL the provider's {@link URL}
*/
private static void setDefaultParams(Map<String, String> params, URL providerURL) {
for (String parameterName : DEFAULT_REGISTER_PROVIDER_KEYS) {
String parameterValue = providerURL.getParameter(parameterName);
if (!isBlank(parameterValue)) {
params.put(parameterName, parameterValue);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/SpringCloudMetadataServiceURLBuilder.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/SpringCloudMetadataServiceURLBuilder.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.client.ServiceInstance;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_URLS_PROPERTY_NAME;
/**
* Supporting interaction with Dubbo Spring Cloud at https://github.com/alibaba/spring-cloud-alibaba
* Dubbo Spring Cloud is a Dubbo extension that favours a per instance registry model and exposes metadata service.
*
* @since 2.7.5
*/
public class SpringCloudMetadataServiceURLBuilder implements MetadataServiceURLBuilder {
public static final String NAME = "spring-cloud";
@Override
public List<URL> build(ServiceInstance serviceInstance) {
Map<String, String> metadata = serviceInstance.getMetadata();
String dubboUrlsForJson = metadata.get(METADATA_SERVICE_URLS_PROPERTY_NAME);
if (StringUtils.isBlank(dubboUrlsForJson)) {
return Collections.emptyList();
}
List<String> urlStrings = JsonUtils.toJavaList(dubboUrlsForJson, String.class);
return urlStrings.stream().map(URL::valueOf).collect(Collectors.toList());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizer.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizer.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Set;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER;
/**
* The {@link ServiceInstanceCustomizer} to customize the {@link ServiceInstance#getPort() port} of service instance.
*/
public class ServiceInstanceHostPortCustomizer implements ServiceInstanceCustomizer {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ServiceInstanceHostPortCustomizer.class);
@Override
public void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel) {
if (serviceInstance.getPort() > 0) {
return;
}
MetadataInfo metadataInfo = serviceInstance.getServiceMetadata();
if (metadataInfo == null || CollectionUtils.isEmptyMap(metadataInfo.getExportedServiceURLs())) {
return;
}
String host = null;
int port = -1;
Set<URL> urls = metadataInfo.collectExportedURLSet();
if (CollectionUtils.isNotEmpty(urls)) {
String preferredProtocol = applicationModel.getCurrentConfig().getProtocol();
if (preferredProtocol != null) {
for (URL exportedURL : urls) {
if (preferredProtocol.equals(exportedURL.getProtocol())) {
host = exportedURL.getHost();
port = exportedURL.getPort();
break;
}
}
if (host == null || port == -1) {
// 4-2 - Can't find an instance URL using the default preferredProtocol.
logger.warn(
PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER,
"typo in preferred protocol",
"",
"Can't find an instance URL using the default preferredProtocol \"" + preferredProtocol
+ "\", " + "falling back to the strategy that pick the first found protocol. "
+ "Please try modifying the config of dubbo.application.protocol");
URL url = urls.iterator().next();
host = url.getHost();
port = url.getPort();
}
} else {
URL url = urls.iterator().next();
host = url.getHost();
port = url.getPort();
}
if (serviceInstance instanceof DefaultServiceInstance) {
DefaultServiceInstance instance = (DefaultServiceInstance) serviceInstance;
instance.setHost(host);
instance.setPort(port);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegationV2.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegationV2.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.DubboMetadataServiceV2Triple.MetadataServiceV2ImplBase;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataRequest;
import org.apache.dubbo.metadata.OpenAPIFormat;
import org.apache.dubbo.metadata.OpenAPIInfo;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.support.RegistryManager;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest;
import org.apache.dubbo.remoting.http12.rest.OpenAPIService;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.TripleProtocol;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_LOAD_METADATA;
import static org.apache.dubbo.metadata.util.MetadataServiceVersionUtils.toV2;
public class MetadataServiceDelegationV2 extends MetadataServiceV2ImplBase {
ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private final FrameworkModel frameworkModel;
private final RegistryManager registryManager;
private URL metadataUrl;
public static final String VERSION = "2.0.0";
public MetadataServiceDelegationV2(ApplicationModel applicationModel) {
frameworkModel = applicationModel.getFrameworkModel();
registryManager = RegistryManager.getInstance(applicationModel);
}
@Override
public org.apache.dubbo.metadata.MetadataInfoV2 getMetadataInfo(MetadataRequest metadataRequestV2) {
String revision = metadataRequestV2.getRevision();
MetadataInfo info;
if (StringUtils.isEmpty(revision)) {
return null;
}
for (ServiceDiscovery sd : registryManager.getServiceDiscoveries()) {
info = sd.getLocalMetadata(revision);
if (info != null && revision.equals(info.getRevision())) {
return toV2(info);
}
}
if (logger.isWarnEnabled()) {
logger.warn(
REGISTRY_FAILED_LOAD_METADATA, "", "", "metadataV2 not found for revision: " + metadataRequestV2);
}
return null;
}
@Override
public OpenAPIInfo getOpenAPIInfo(org.apache.dubbo.metadata.OpenAPIRequest request) {
if (TripleProtocol.OPENAPI_ENABLED) {
OpenAPIService openAPIService = frameworkModel.getBean(OpenAPIService.class);
if (openAPIService != null) {
OpenAPIRequest oRequest = new OpenAPIRequest();
oRequest.setGroup(request.getGroup());
oRequest.setVersion(request.getVersion());
oRequest.setTag(request.getTagList().toArray(StringUtils.EMPTY_STRING_ARRAY));
oRequest.setService(request.getServiceList().toArray(StringUtils.EMPTY_STRING_ARRAY));
oRequest.setOpenapi(request.getOpenapi());
OpenAPIFormat format = request.getFormat();
if (request.hasFormat()) {
oRequest.setFormat(format.name());
}
if (request.hasPretty()) {
oRequest.setPretty(request.getPretty());
}
String document = openAPIService.getDocument(oRequest);
return OpenAPIInfo.newBuilder().setDefinition(document).build();
}
}
throw new HttpStatusException(HttpStatus.NOT_FOUND.getCode(), "OpenAPI is not available");
}
public URL getMetadataUrl() {
return metadataUrl;
}
public void setMetadataUrl(URL metadataUrl) {
this.metadataUrl = metadataUrl;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegation.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegation.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.resource.Disposable;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.InstanceMetadataChangedListener;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.support.RegistryManager;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest;
import org.apache.dubbo.remoting.http12.rest.OpenAPIService;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.protocol.tri.TripleProtocol;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static java.util.Collections.emptySortedSet;
import static java.util.Collections.unmodifiableSortedSet;
import static org.apache.dubbo.common.URL.buildKey;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_LOAD_METADATA;
import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty;
/**
* Implementation providing remote RPC service to facilitate the query of metadata information.
*/
public class MetadataServiceDelegation implements MetadataService, Disposable {
ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private final ApplicationModel applicationModel;
private final RegistryManager registryManager;
private final ConcurrentMap<String, InstanceMetadataChangedListener> instanceMetadataChangedListenerMap =
new ConcurrentHashMap<>();
private URL url;
// works only for DNS service discovery
private String instanceMetadata;
public static final String VERSION = "1.0.0";
public MetadataServiceDelegation(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
registryManager = RegistryManager.getInstance(applicationModel);
}
/**
* Gets the current Dubbo Service name
*
* @return non-null
*/
@Override
public String serviceName() {
return ApplicationModel.ofNullable(applicationModel).getApplicationName();
}
@Override
public URL getMetadataURL() {
return url;
}
public void setMetadataURL(URL url) {
this.url = url;
}
@Override
public SortedSet<String> getSubscribedURLs() {
return getAllUnmodifiableSubscribedURLs();
}
private SortedSet<String> getAllUnmodifiableServiceURLs() {
SortedSet<URL> bizURLs = new TreeSet<>(URLComparator.INSTANCE);
List<ServiceDiscovery> serviceDiscoveries = registryManager.getServiceDiscoveries();
for (ServiceDiscovery sd : serviceDiscoveries) {
MetadataInfo metadataInfo = sd.getLocalMetadata();
Map<String, SortedSet<URL>> serviceURLs = metadataInfo.getExportedServiceURLs();
joinNonMetadataServiceUrls(bizURLs, serviceURLs);
}
return MetadataService.toSortedStrings(bizURLs);
}
private void joinNonMetadataServiceUrls(SortedSet<URL> bizURLs, Map<String, SortedSet<URL>> serviceURLs) {
if (serviceURLs == null) {
return;
}
for (Map.Entry<String, SortedSet<URL>> entry : serviceURLs.entrySet()) {
SortedSet<URL> urls = entry.getValue();
if (urls != null) {
for (URL url : urls) {
if (!MetadataService.class.getName().equals(url.getServiceInterface())) {
bizURLs.add(url);
}
}
}
}
}
private SortedSet<String> getAllUnmodifiableSubscribedURLs() {
SortedSet<URL> bizURLs = new TreeSet<>(URLComparator.INSTANCE);
List<ServiceDiscovery> serviceDiscoveries = registryManager.getServiceDiscoveries();
for (ServiceDiscovery sd : serviceDiscoveries) {
MetadataInfo metadataInfo = sd.getLocalMetadata();
Map<String, SortedSet<URL>> serviceURLs = metadataInfo.getSubscribedServiceURLs();
joinNonMetadataServiceUrls(bizURLs, serviceURLs);
}
return MetadataService.toSortedStrings(bizURLs);
}
@Override
public SortedSet<String> getExportedURLs(String serviceInterface, String group, String version, String protocol) {
if (ALL_SERVICE_INTERFACES.equals(serviceInterface)) {
return getAllUnmodifiableServiceURLs();
}
String serviceKey = buildKey(serviceInterface, group, version);
return unmodifiableSortedSet(getServiceURLs(getAllServiceURLs(), serviceKey, protocol));
}
private Map<String, SortedSet<URL>> getAllServiceURLs() {
List<ServiceDiscovery> serviceDiscoveries = registryManager.getServiceDiscoveries();
Map<String, SortedSet<URL>> allServiceURLs = new HashMap<>();
for (ServiceDiscovery sd : serviceDiscoveries) {
MetadataInfo metadataInfo = sd.getLocalMetadata();
Map<String, SortedSet<URL>> serviceURLs = metadataInfo.getExportedServiceURLs();
allServiceURLs.putAll(serviceURLs);
}
return allServiceURLs;
}
@Override
public Set<URL> getExportedServiceURLs() {
Set<URL> set = new HashSet<>();
registryManager.getRegistries();
for (Map.Entry<String, SortedSet<URL>> entry : getAllServiceURLs().entrySet()) {
set.addAll(entry.getValue());
}
return set;
}
@Override
public String getServiceDefinition(String interfaceName, String version, String group) {
return "";
}
@Override
public String getServiceDefinition(String serviceKey) {
return "";
}
@Override
public MetadataInfo getMetadataInfo(String revision) {
if (StringUtils.isEmpty(revision)) {
return null;
}
for (ServiceDiscovery sd : registryManager.getServiceDiscoveries()) {
MetadataInfo metadataInfo = sd.getLocalMetadata(revision);
if (metadataInfo != null && revision.equals(metadataInfo.getRevision())) {
return metadataInfo;
}
}
if (logger.isWarnEnabled()) {
logger.warn(REGISTRY_FAILED_LOAD_METADATA, "", "", "metadata not found for revision: " + revision);
}
return null;
}
@Override
public List<MetadataInfo> getMetadataInfos() {
List<MetadataInfo> metadataInfos = new ArrayList<>();
for (ServiceDiscovery sd : registryManager.getServiceDiscoveries()) {
metadataInfos.add(sd.getLocalMetadata());
}
return metadataInfos;
}
@Override
public void exportInstanceMetadata(String instanceMetadata) {
this.instanceMetadata = instanceMetadata;
}
@Override
public Map<String, InstanceMetadataChangedListener> getInstanceMetadataChangedListenerMap() {
return instanceMetadataChangedListenerMap;
}
@Override
public String getAndListenInstanceMetadata(String consumerId, InstanceMetadataChangedListener listener) {
instanceMetadataChangedListenerMap.put(consumerId, listener);
return instanceMetadata;
}
@Override
public String getOpenAPI(OpenAPIRequest request) {
if (TripleProtocol.OPENAPI_ENABLED) {
OpenAPIService openAPIService = applicationModel.getBean(OpenAPIService.class);
if (openAPIService != null) {
return openAPIService.getDocument(request);
}
}
throw new HttpStatusException(HttpStatus.NOT_FOUND.getCode(), "OpenAPI is not available");
}
private SortedSet<String> getServiceURLs(
Map<String, SortedSet<URL>> exportedServiceURLs, String serviceKey, String protocol) {
SortedSet<URL> serviceURLs = exportedServiceURLs.get(serviceKey);
if (isEmpty(serviceURLs)) {
return emptySortedSet();
}
return MetadataService.toSortedStrings(serviceURLs.stream().filter(url -> isAcceptableProtocol(protocol, url)));
}
private boolean isAcceptableProtocol(String protocol, URL url) {
return protocol == null
|| protocol.equals(url.getParameter(PROTOCOL_KEY))
|| protocol.equals(url.getProtocol());
}
@Override
public void destroy() {}
static class URLComparator implements Comparator<URL> {
public static final URLComparator INSTANCE = new URLComparator();
@Override
public int compare(URL o1, URL o2) {
return o1.toFullString().compareTo(o2.toFullString());
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceNotificationCustomizer.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceNotificationCustomizer.java | /*
* 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.metadata;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.registry.client.ServiceInstance;
import java.util.List;
@SPI
public interface ServiceInstanceNotificationCustomizer {
void customize(List<ServiceInstance> serviceInstance);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.AbstractServiceNameMapping;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.MetadataReportInstance;
import org.apache.dubbo.registry.client.RegistryClusterIdentifier;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.registry.Constants.CAS_RETRY_TIMES_KEY;
import static org.apache.dubbo.registry.Constants.CAS_RETRY_WAIT_TIME_KEY;
import static org.apache.dubbo.registry.Constants.DEFAULT_CAS_RETRY_TIMES;
import static org.apache.dubbo.registry.Constants.DEFAULT_CAS_RETRY_WAIT_TIME;
public class MetadataServiceNameMapping extends AbstractServiceNameMapping {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private static final List<String> IGNORED_SERVICE_INTERFACES =
Collections.singletonList(MetadataService.class.getName());
private final int casRetryTimes;
private final int casRetryWaitTime;
protected MetadataReportInstance metadataReportInstance;
public MetadataServiceNameMapping(ApplicationModel applicationModel) {
super(applicationModel);
metadataReportInstance = applicationModel.getBeanFactory().getBean(MetadataReportInstance.class);
casRetryTimes = ConfigurationUtils.getGlobalConfiguration(applicationModel)
.getInt(CAS_RETRY_TIMES_KEY, DEFAULT_CAS_RETRY_TIMES);
casRetryWaitTime = ConfigurationUtils.getGlobalConfiguration(applicationModel)
.getInt(CAS_RETRY_WAIT_TIME_KEY, DEFAULT_CAS_RETRY_WAIT_TIME);
}
@Override
public boolean hasValidMetadataCenter() {
return !CollectionUtils.isEmpty(
applicationModel.getApplicationConfigManager().getMetadataConfigs());
}
/**
* Simply register to all metadata center
*/
@Override
public boolean map(URL url) {
if (CollectionUtils.isEmpty(
applicationModel.getApplicationConfigManager().getMetadataConfigs())) {
logger.warn(
COMMON_PROPERTY_TYPE_MISMATCH,
"",
"",
"[METADATA_REGISTER] No valid metadata config center found for mapping report.");
return false;
}
String serviceInterface = url.getServiceInterface();
if (IGNORED_SERVICE_INTERFACES.contains(serviceInterface)) {
return true;
}
boolean result = true;
for (Map.Entry<String, MetadataReport> entry :
metadataReportInstance.getMetadataReports(true).entrySet()) {
MetadataReport metadataReport = entry.getValue();
String appName = applicationModel.getApplicationName();
try {
if (metadataReport.registerServiceAppMapping(serviceInterface, appName, url)) {
// MetadataReport support directly register service-app mapping
continue;
}
boolean succeeded = false;
int currentRetryTimes = 1;
String newConfigContent = appName;
do {
ConfigItem configItem = metadataReport.getConfigItem(serviceInterface, DEFAULT_MAPPING_GROUP);
String oldConfigContent = configItem.getContent();
if (StringUtils.isNotEmpty(oldConfigContent)) {
String[] oldAppNames = oldConfigContent.split(",");
if (oldAppNames.length > 0) {
for (String oldAppName : oldAppNames) {
if (StringUtils.trim(oldAppName).equals(appName)) {
succeeded = true;
break;
}
}
}
if (succeeded) {
break;
}
newConfigContent = oldConfigContent + COMMA_SEPARATOR + appName;
}
succeeded = metadataReport.registerServiceAppMapping(
serviceInterface, DEFAULT_MAPPING_GROUP, newConfigContent, configItem.getTicket());
if (!succeeded) {
int waitTime = ThreadLocalRandom.current().nextInt(casRetryWaitTime);
logger.info("Failed to publish service name mapping to metadata center by cas operation. "
+ "Times: "
+ currentRetryTimes + ". " + "Next retry delay: "
+ waitTime + ". " + "Service Interface: "
+ serviceInterface + ". " + "Origin Content: "
+ oldConfigContent + ". " + "Ticket: "
+ configItem.getTicket() + ". " + "Expected Content: "
+ newConfigContent);
Thread.sleep(waitTime);
}
} while (!succeeded && currentRetryTimes++ <= casRetryTimes);
if (!succeeded) {
result = false;
}
} catch (Exception e) {
result = false;
logger.warn(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Failed registering mapping to remote." + metadataReport,
e);
}
}
return result;
}
@Override
public Set<String> get(URL url) {
String serviceInterface = url.getServiceInterface();
String registryCluster = getRegistryCluster(url);
MetadataReport metadataReport = metadataReportInstance.getMetadataReport(registryCluster);
if (metadataReport == null) {
return Collections.emptySet();
}
return metadataReport.getServiceAppMapping(serviceInterface, url);
}
@Override
public Set<String> getAndListen(URL url, MappingListener mappingListener) {
String serviceInterface = url.getServiceInterface();
// randomly pick one metadata report is ok for it's guaranteed all metadata report will have the same mapping
// data.
String registryCluster = getRegistryCluster(url);
MetadataReport metadataReport = metadataReportInstance.getMetadataReport(registryCluster);
if (metadataReport == null) {
return Collections.emptySet();
}
return metadataReport.getServiceAppMapping(serviceInterface, mappingListener, url);
}
@Override
protected void removeListener(URL url, MappingListener mappingListener) {
String serviceInterface = url.getServiceInterface();
// randomly pick one metadata report is ok for it's guaranteed each metadata report will have the same mapping
// content.
String registryCluster = getRegistryCluster(url);
MetadataReport metadataReport = metadataReportInstance.getMetadataReport(registryCluster);
if (metadataReport == null) {
return;
}
metadataReport.removeServiceAppMappingListener(serviceInterface, mappingListener);
}
protected String getRegistryCluster(URL url) {
String registryCluster = RegistryClusterIdentifier.getExtension(url).providerKey(url);
if (registryCluster == null) {
registryCluster = DEFAULT_KEY;
}
int i = registryCluster.indexOf(",");
if (i > 0) {
registryCluster = registryCluster.substring(0, i);
}
return registryCluster;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataUtils.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataUtils.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.aot.NativeDetector;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataRequest;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metadata.MetadataServiceV2;
import org.apache.dubbo.metadata.MetadataServiceV2Detector;
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 org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metadata.util.MetadataServiceVersionUtils;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.service.Destroyable;
import org.apache.dubbo.rpc.stub.StubSuppliers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.FILTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.NATIVE_STUB;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.PROXY_CLASS_REF;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_CREATE_INSTANCE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_LOAD_METADATA;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY;
import static org.apache.dubbo.metadata.util.MetadataServiceVersionUtils.V2;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_URLS_PROPERTY_NAME;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_VERSION_NAME;
import static org.apache.dubbo.rpc.Constants.AUTH_KEY;
import static org.apache.dubbo.rpc.Constants.PROXY_KEY;
public class MetadataUtils {
public static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MetadataUtils.class);
public static void publishServiceDefinition(
URL url, ServiceDescriptor serviceDescriptor, ApplicationModel applicationModel) {
if (getMetadataReports(applicationModel).isEmpty()) {
logger.info("[METADATA_REGISTER] Remote Metadata Report Server is not provided or unavailable, "
+ "will stop registering service definition to remote center!");
return;
}
try {
String side = url.getSide();
if (PROVIDER_SIDE.equalsIgnoreCase(side)) {
String serviceKey = url.getServiceKey();
FullServiceDefinition serviceDefinition = serviceDescriptor.getFullServiceDefinition(serviceKey);
if (StringUtils.isNotEmpty(serviceKey) && serviceDefinition != null) {
serviceDefinition.setParameters(url.getParameters());
for (Map.Entry<String, MetadataReport> entry :
getMetadataReports(applicationModel).entrySet()) {
MetadataReport metadataReport = entry.getValue();
if (!metadataReport.shouldReportDefinition()) {
logger.info("Report of service definition is disabled for " + entry.getKey());
continue;
}
metadataReport.storeProviderMetadata(
new MetadataIdentifier(
url.getServiceInterface(),
url.getVersion() == null ? "" : url.getVersion(),
url.getGroup() == null ? "" : url.getGroup(),
PROVIDER_SIDE,
applicationModel.getApplicationName()),
serviceDefinition);
}
}
} else {
for (Map.Entry<String, MetadataReport> entry :
getMetadataReports(applicationModel).entrySet()) {
MetadataReport metadataReport = entry.getValue();
if (!metadataReport.shouldReportDefinition()) {
logger.info("Report of service definition is disabled for " + entry.getKey());
continue;
}
metadataReport.storeConsumerMetadata(
new MetadataIdentifier(
url.getServiceInterface(),
url.getVersion() == null ? "" : url.getVersion(),
url.getGroup() == null ? "" : url.getGroup(),
CONSUMER_SIDE,
applicationModel.getApplicationName()),
url.getParameters());
}
}
} catch (Exception e) {
// ignore error
logger.error(REGISTRY_FAILED_CREATE_INSTANCE, "", "", "publish service definition metadata error.", e);
}
}
public static RemoteMetadataService referMetadataService(ServiceInstance instance) {
URL url = buildMetadataUrl(instance);
// Simply rely on the first metadata url, as stated in MetadataServiceURLBuilder.
ApplicationModel applicationModel = instance.getApplicationModel();
ModuleModel internalModel = applicationModel.getInternalModule();
ConsumerModel consumerModel;
boolean useV2 = MetadataServiceDelegationV2.VERSION.equals(url.getAttribute(METADATA_SERVICE_VERSION_NAME));
if (!MetadataServiceV2Detector.support()) {
useV2 = false;
}
boolean inNativeImage = NativeDetector.inNativeImage();
if (useV2 && !inNativeImage) {
// If provider supports, we use MetadataServiceV2 in priority
url = url.addParameter(PROXY_KEY, NATIVE_STUB);
url = url.setPath(MetadataServiceV2.class.getName());
url = url.addParameter(VERSION_KEY, V2);
consumerModel = applicationModel
.getInternalModule()
.registerInternalConsumer(
MetadataServiceV2.class,
url,
StubSuppliers.getServiceDescriptor(MetadataServiceV2.class.getName()));
} else {
consumerModel = applicationModel.getInternalModule().registerInternalConsumer(MetadataService.class, url);
}
if (inNativeImage) {
url = url.addParameter(PROXY_KEY, "jdk");
}
Protocol protocol = applicationModel.getExtensionLoader(Protocol.class).getExtension(url.getProtocol(), false);
url = url.setServiceModel(consumerModel);
if (url.getParameter(AUTH_KEY, false)) {
url = url.addParameter(FILTER_KEY, "-default,consumersign");
}
RemoteMetadataService remoteMetadataService;
ProxyFactory proxyFactory =
applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
if (useV2 && !inNativeImage) {
Invoker<MetadataServiceV2> invoker = protocol.refer(MetadataServiceV2.class, url);
if (url.getParameter(AUTH_KEY, false)) {
FilterChainBuilder filterChainBuilder = ScopeModelUtil.getExtensionLoader(
FilterChainBuilder.class, url.getScopeModel())
.getDefaultExtension();
invoker = filterChainBuilder.buildInvokerChain(invoker, REFERENCE_FILTER_KEY, CommonConstants.CONSUMER);
}
remoteMetadataService =
new RemoteMetadataService(consumerModel, proxyFactory.getProxy(invoker), internalModel);
} else {
Invoker<MetadataService> invoker = protocol.refer(MetadataService.class, url);
if (url.getParameter(AUTH_KEY, false)) {
FilterChainBuilder filterChainBuilder = ScopeModelUtil.getExtensionLoader(
FilterChainBuilder.class, url.getScopeModel())
.getDefaultExtension();
invoker = filterChainBuilder.buildInvokerChain(invoker, REFERENCE_FILTER_KEY, CommonConstants.CONSUMER);
}
remoteMetadataService =
new RemoteMetadataService(consumerModel, proxyFactory.getProxy(invoker), internalModel);
}
Object metadataServiceProxy = remoteMetadataService.getInternalProxy();
consumerModel.getServiceMetadata().setTarget(metadataServiceProxy);
consumerModel.getServiceMetadata().addAttribute(PROXY_CLASS_REF, metadataServiceProxy);
consumerModel.setProxyObject(metadataServiceProxy);
consumerModel.initMethodModels();
return remoteMetadataService;
}
private static URL buildMetadataUrl(ServiceInstance instance) {
MetadataServiceURLBuilder builder;
ExtensionLoader<MetadataServiceURLBuilder> loader =
instance.getApplicationModel().getExtensionLoader(MetadataServiceURLBuilder.class);
Map<String, String> metadata = instance.getMetadata();
// METADATA_SERVICE_URLS_PROPERTY_NAME is a unique key exists only on instances of spring-cloud-alibaba.
String dubboUrlsForJson = metadata.get(METADATA_SERVICE_URLS_PROPERTY_NAME);
if (metadata.isEmpty() || StringUtils.isEmpty(dubboUrlsForJson)) {
builder = loader.getExtension(StandardMetadataServiceURLBuilder.NAME);
} else {
builder = loader.getExtension(SpringCloudMetadataServiceURLBuilder.NAME);
}
List<URL> urls = builder.build(instance);
if (CollectionUtils.isEmpty(urls)) {
throw new IllegalStateException("Introspection service discovery mode is enabled " + instance
+ ", but no metadata service can build from it.");
}
URL url = urls.get(0);
String version = metadata.get(METADATA_SERVICE_VERSION_NAME);
url = url.putAttribute(METADATA_SERVICE_VERSION_NAME, version);
url = url.addParameter(CHECK_KEY, false);
return url;
}
public static MetadataInfo getRemoteMetadata(
String revision, List<ServiceInstance> instances, MetadataReport metadataReport) {
ServiceInstance instance = selectInstance(instances);
String metadataType = ServiceInstanceMetadataUtils.getMetadataStorageType(instance);
MetadataInfo metadataInfo;
try {
if (logger.isDebugEnabled()) {
logger.debug("Instance " + instance.getAddress() + " is using metadata type " + metadataType);
}
if (REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) {
metadataInfo = MetadataUtils.getMetadata(revision, instance, metadataReport);
} else {
// change the instance used to communicate to avoid all requests route to the same instance
RemoteMetadataService remoteMetadataService = null;
try {
remoteMetadataService = MetadataUtils.referMetadataService(instance);
metadataInfo = remoteMetadataService.getRemoteMetadata(
ServiceInstanceMetadataUtils.getExportedServicesRevision(instance));
} finally {
MetadataUtils.destroyProxy(remoteMetadataService);
}
}
} catch (Exception e) {
logger.error(
REGISTRY_FAILED_LOAD_METADATA,
"",
"",
"Failed to get app metadata for revision " + revision + " for type " + metadataType
+ " from instance " + instance.getAddress(),
e);
metadataInfo = null;
}
if (metadataInfo == null) {
metadataInfo = MetadataInfo.EMPTY;
}
return metadataInfo;
}
public static void destroyProxy(RemoteMetadataService remoteMetadataService) {
if (remoteMetadataService != null) {
remoteMetadataService.destroy();
}
}
public static MetadataInfo getMetadata(String revision, ServiceInstance instance, MetadataReport metadataReport) {
SubscriberMetadataIdentifier identifier = new SubscriberMetadataIdentifier(instance.getServiceName(), revision);
if (metadataReport == null) {
throw new IllegalStateException("No valid remote metadata report specified.");
}
String registryCluster = instance.getRegistryCluster();
Map<String, String> params = new HashMap<>(instance.getExtendParams());
if (registryCluster != null && !registryCluster.equalsIgnoreCase(params.get(REGISTRY_CLUSTER_KEY))) {
params.put(REGISTRY_CLUSTER_KEY, registryCluster);
}
return metadataReport.getAppMetadata(identifier, params);
}
private static Map<String, MetadataReport> getMetadataReports(ApplicationModel applicationModel) {
return applicationModel
.getBeanFactory()
.getBean(MetadataReportInstance.class)
.getMetadataReports(false);
}
private static ServiceInstance selectInstance(List<ServiceInstance> instances) {
if (instances.size() == 1) {
return instances.get(0);
}
return instances.get(ThreadLocalRandom.current().nextInt(0, instances.size()));
}
public static class RemoteMetadataService {
private final ConsumerModel consumerModel;
@Deprecated
private MetadataService proxy;
private MetadataServiceV2 proxyV2;
private final ModuleModel internalModel;
public RemoteMetadataService(ConsumerModel consumerModel, MetadataService proxy, ModuleModel internalModel) {
this.consumerModel = consumerModel;
this.proxy = proxy;
this.internalModel = internalModel;
}
public RemoteMetadataService(
ConsumerModel consumerModel, MetadataServiceV2 proxyV2, ModuleModel internalModel) {
this.consumerModel = consumerModel;
this.proxyV2 = proxyV2;
this.internalModel = internalModel;
}
public void destroy() {
if (proxy instanceof Destroyable) {
((Destroyable) proxy).$destroy();
}
if (proxyV2 instanceof Destroyable) {
((Destroyable) proxyV2).$destroy();
}
internalModel.getServiceRepository().unregisterConsumer(consumerModel);
}
public ConsumerModel getConsumerModel() {
return consumerModel;
}
public Object getInternalProxy() {
return proxy == null ? proxyV2 : proxy;
}
public ModuleModel getInternalModel() {
return internalModel;
}
public MetadataInfo getRemoteMetadata(String revision) {
Object existProxy = getInternalProxy();
if (existProxy instanceof MetadataService) {
return ((MetadataService) existProxy).getMetadataInfo(revision);
} else {
return MetadataServiceVersionUtils.toV1(((MetadataServiceV2) existProxy)
.getMetadataInfo(MetadataRequest.newBuilder()
.setRevision(revision)
.build()));
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizer.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizer.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.setEndpoints;
/**
* A Class to customize the ports of {@link Protocol protocols} into
* {@link ServiceInstance#getMetadata() the metadata of service instance}
*
* @since 2.7.5
*/
public class ProtocolPortsMetadataCustomizer implements ServiceInstanceCustomizer {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(ProtocolPortsMetadataCustomizer.class);
@Override
public void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel) {
MetadataInfo metadataInfo = serviceInstance.getServiceMetadata();
if (metadataInfo == null || CollectionUtils.isEmptyMap(metadataInfo.getExportedServiceURLs())) {
return;
}
Map<String, Integer> protocols = new HashMap<>();
Set<URL> urls = metadataInfo.collectExportedURLSet();
urls.forEach(url -> {
// TODO, same protocol listen on different ports will override with each other.
String protocol = url.getProtocol();
Integer oldPort = protocols.get(protocol);
int newPort = url.getPort();
if (oldPort != null && oldPort != newPort) {
LOGGER.warn(
LoggerCodeConstants.PROTOCOL_INCORRECT_PARAMETER_VALUES,
"the protocol is listening multiple ports",
"",
"Same protocol " + "[" + protocol + "]" + " listens on different ports " + "[" + oldPort + ","
+ newPort + "]" + " will override with each other" + ". The port [" + oldPort
+ "] is overridden with port [" + newPort + "].");
}
protocols.put(protocol, newPort);
});
if (protocols.size() > 0) { // set endpoints only for multi-protocol scenario
setEndpoints(serviceInstance, protocols);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizer.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizer.java | /*
* 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.metadata;
import org.apache.dubbo.common.infra.InfraAdapter;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
/**
* <p>Intercepting instance to load instance-level params from different sources before being registered into registry.</p>
*
* The sources can be one or both of the following:
* <ul>
* <li>os environment</li>
* <li>vm options</li>
* </ul>
*
* So, finally, the keys left in order will be:
* <ul>
* <li>all keys specified by sources above</li>
* <li>keys found in metadata info</li>
* </ul>
*
*
*/
public class ServiceInstanceMetadataCustomizer implements ServiceInstanceCustomizer {
@Override
public void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel) {
MetadataInfo metadataInfo = serviceInstance.getServiceMetadata();
if (metadataInfo == null || CollectionUtils.isEmptyMap(metadataInfo.getServices())) {
return;
}
// try to load instance params that do not appear in service urls
// TODO, duplicate snippet in ApplicationConfig
Map<String, String> extraParameters = Collections.emptyMap();
Set<InfraAdapter> adapters =
applicationModel.getExtensionLoader(InfraAdapter.class).getSupportedExtensionInstances();
if (CollectionUtils.isNotEmpty(adapters)) {
Map<String, String> inputParameters = new HashMap<>();
inputParameters.put(APPLICATION_KEY, applicationModel.getApplicationName());
for (InfraAdapter adapter : adapters) {
extraParameters = adapter.getExtraAttributes(inputParameters);
}
}
serviceInstance.getMetadata().putAll(extraParameters);
if (CollectionUtils.isNotEmptyMap(metadataInfo.getInstanceParams())) {
serviceInstance.getMetadata().putAll(metadataInfo.getInstanceParams());
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilder.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilder.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.registry.client.ServiceInstance;
import java.util.List;
/**
* Used to build metadata service url from ServiceInstance.
*
* @since 2.7.5
*/
@SPI
public interface MetadataServiceURLBuilder {
/**
* Build the {@link URL URLs} from the specified {@link ServiceInstance}
*
* @param serviceInstance {@link ServiceInstance}
* @return TODO, usually, we generate one metadata url from one instance. There's no scenario to return a metadata url list.
*/
List<URL> build(ServiceInstance serviceInstance);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilder.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilder.java | /*
* 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.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static java.util.Collections.emptyMap;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RETRIES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_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.common.constants.LoggerCodeConstants.REGISTRY_MISSING_METADATA_CONFIG_PORT;
import static org.apache.dubbo.common.utils.StringUtils.isBlank;
import static org.apache.dubbo.metadata.MetadataConstants.DEFAULT_METADATA_TIMEOUT_VALUE;
import static org.apache.dubbo.metadata.MetadataConstants.METADATA_PROXY_TIMEOUT_KEY;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME;
import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY;
/**
* Standard Dubbo provider enabling introspection service discovery mode.
*
* @see MetadataService
* @since 2.7.5
*/
public class StandardMetadataServiceURLBuilder implements MetadataServiceURLBuilder {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
public static final String NAME = "standard";
private ApplicationModel applicationModel;
private Integer metadataServicePort;
public StandardMetadataServiceURLBuilder(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
metadataServicePort = applicationModel.getCurrentConfig().getMetadataServicePort();
}
/**
* Build the {@link URL urls} from {@link ServiceInstance#getMetadata() the metadata} of {@link ServiceInstance}
*
* @param serviceInstance {@link ServiceInstance}
* @return the not-null {@link List}
*/
@Override
public List<URL> build(ServiceInstance serviceInstance) {
Map<String, String> paramsMap = getMetadataServiceURLsParams(serviceInstance);
String serviceName = serviceInstance.getServiceName();
String host = serviceInstance.getHost();
URL url;
if (paramsMap.isEmpty()) {
// ServiceInstance Metadata is empty. Happened when registry not support metadata write.
url = generateUrlWithoutMetadata(serviceName, host, serviceInstance.getPort());
} else {
url = generateWithMetadata(serviceName, host, paramsMap);
}
url = url.setScopeModel(serviceInstance.getApplicationModel().getInternalModule());
return Collections.singletonList(url);
}
private URL generateWithMetadata(String serviceName, String host, Map<String, String> params) {
String protocol = params.get(PROTOCOL_KEY);
int port = Integer.parseInt(params.get(PORT_KEY));
URLBuilder urlBuilder = new URLBuilder()
.setHost(host)
.setPort(port)
.setProtocol(protocol)
.setPath(MetadataService.class.getName())
.addParameter(
TIMEOUT_KEY,
ConfigurationUtils.get(
applicationModel, METADATA_PROXY_TIMEOUT_KEY, DEFAULT_METADATA_TIMEOUT_VALUE))
.addParameter(CONNECTIONS_KEY, 1)
.addParameter(THREADPOOL_KEY, "cached")
.addParameter(THREADS_KEY, "100")
.addParameter(CORE_THREADS_KEY, "2")
.addParameter(RETRIES_KEY, 0);
// add parameters
params.forEach(urlBuilder::addParameter);
// add the default parameters
urlBuilder.addParameter(GROUP_KEY, serviceName);
urlBuilder.addParameter(SIDE_KEY, CONSUMER);
return urlBuilder.build();
}
private URL generateUrlWithoutMetadata(String serviceName, String host, Integer instancePort) {
Integer port = metadataServicePort;
if (port == null || port < 1) {
// 1-18 - Metadata Service Port should be specified for consumer.
logger.warn(
REGISTRY_MISSING_METADATA_CONFIG_PORT,
"missing configuration of metadata service port",
"",
"Metadata Service Port is not provided. Since DNS is not able to negotiate the metadata port "
+ "between Provider and Consumer, Dubbo will try using instance port as the default metadata port.");
port = instancePort;
}
if (port == null || port < 1) {
// 1-18 - Metadata Service Port should be specified for consumer.
String message = "Metadata Service Port should be specified for consumer. "
+ "Please set dubbo.application.metadataServicePort and "
+ "make sure it has been set on provider side. "
+ "ServiceName: "
+ serviceName + " Host: " + host;
IllegalStateException illegalStateException = new IllegalStateException(message);
logger.error(
REGISTRY_MISSING_METADATA_CONFIG_PORT,
"missing configuration of metadata service port",
"",
message,
illegalStateException);
throw illegalStateException;
}
URLBuilder urlBuilder = new URLBuilder()
.setHost(host)
.setPort(port)
.setProtocol(DUBBO_PROTOCOL)
.setPath(MetadataService.class.getName())
.addParameter(
TIMEOUT_KEY,
ConfigurationUtils.get(
applicationModel, METADATA_PROXY_TIMEOUT_KEY, DEFAULT_METADATA_TIMEOUT_VALUE))
.addParameter(Constants.RECONNECT_KEY, false)
.addParameter(SIDE_KEY, CONSUMER)
.addParameter(GROUP_KEY, serviceName)
.addParameter(VERSION_KEY, MetadataService.VERSION)
.addParameter(RETRIES_KEY, 0);
// add ServiceInstance Metadata notify support
urlBuilder.addParameter("getAndListenInstanceMetadata.1.callback", true);
return urlBuilder.build();
}
/**
* Get the multiple {@link URL urls'} parameters of {@link MetadataService MetadataService's} Metadata
*
* @param serviceInstance the instance of {@link ServiceInstance}
* @return non-null {@link Map}, the key is {@link URL#getProtocol() the protocol of URL}, the value is
*/
private Map<String, String> getMetadataServiceURLsParams(ServiceInstance serviceInstance) {
Map<String, String> metadata = serviceInstance.getMetadata();
String param = metadata.get(METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME);
return isBlank(param) ? emptyMap() : (Map) JsonUtils.toJavaObject(param, Map.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/store/MetaCacheManager.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/store/MetaCacheManager.java | /*
* 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.metadata.store;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.metadata.AbstractCacheManager;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.util.Objects;
import java.util.concurrent.ScheduledExecutorService;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_META_CACHE_ENTRYSIZE;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_META_CACHE_FILENAME;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_META_CACHE_FILEPATH;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_META_CACHE_MAXFILESIZE;
/**
* Metadata cache with limited size that uses LRU expiry policy.
*/
public class MetaCacheManager extends AbstractCacheManager<MetadataInfo> {
private static final String DEFAULT_FILE_NAME = ".metadata";
private static final int DEFAULT_ENTRY_SIZE = 100;
public static MetaCacheManager getInstance(ScopeModel scopeModel) {
return scopeModel.getBeanFactory().getOrRegisterBean(MetaCacheManager.class);
}
public MetaCacheManager(boolean enableFileCache, String registryName, ScheduledExecutorService executorService) {
String filePath = SystemPropertyConfigUtils.getSystemProperty(DUBBO_META_CACHE_FILEPATH);
String fileName = SystemPropertyConfigUtils.getSystemProperty(DUBBO_META_CACHE_FILENAME);
if (StringUtils.isEmpty(fileName)) {
fileName = DEFAULT_FILE_NAME;
}
if (StringUtils.isNotEmpty(registryName)) {
fileName = fileName + "." + registryName;
}
String rawEntrySize = SystemPropertyConfigUtils.getSystemProperty(DUBBO_META_CACHE_ENTRYSIZE);
int entrySize = StringUtils.parseInteger(rawEntrySize);
entrySize = (entrySize == 0 ? DEFAULT_ENTRY_SIZE : entrySize);
String rawMaxFileSize = SystemPropertyConfigUtils.getSystemProperty(DUBBO_META_CACHE_MAXFILESIZE);
long maxFileSize = StringUtils.parseLong(rawMaxFileSize);
init(enableFileCache, filePath, fileName, entrySize, maxFileSize, 60, executorService);
}
// for unit test only
public MetaCacheManager() {
this(true, "", null);
}
@Override
protected MetadataInfo toValueType(String value) {
return JsonUtils.toJavaObject(value, MetadataInfo.class);
}
@Override
protected String getName() {
return "meta";
}
@Override
protected boolean validate(String key, MetadataInfo value) {
if (!super.validate(key, value)) {
return false;
}
String revision = value.calRevision();
return Objects.equals(key, revision);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java | /*
* 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.event;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import java.util.Collections;
import java.util.List;
import static java.util.Collections.unmodifiableList;
/**
* An event raised after the {@link ServiceInstance instances} of one service has been changed.
*
* @see ServiceInstancesChangedListener
* @since 2.7.5
*/
public class ServiceInstancesChangedEvent {
private final String serviceName;
private final List<ServiceInstance> serviceInstances;
/**
* @param serviceName The name of service that was changed
* @param serviceInstances all {@link ServiceInstance service instances}
* @throws IllegalArgumentException if source is null.
*/
public ServiceInstancesChangedEvent(String serviceName, List<ServiceInstance> serviceInstances) {
this.serviceName = serviceName;
this.serviceInstances = unmodifiableList(serviceInstances);
}
protected ServiceInstancesChangedEvent() {
this.serviceInstances = Collections.emptyList();
this.serviceName = "";
}
/**
* @return The name of service that was changed
*/
public String getServiceName() {
return serviceName;
}
/**
* @return all {@link ServiceInstance service instances}
*/
public List<ServiceInstance> getServiceInstances() {
return serviceInstances;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.