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/main/java/org/apache/dubbo/registry/client/event/RetryServiceInstancesChangedEvent.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RetryServiceInstancesChangedEvent.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 java.util.Collections; /** * A retry task when is failed. */ public class RetryServiceInstancesChangedEvent extends ServiceInstancesChangedEvent { private volatile long failureRecordTime; public RetryServiceInstancesChangedEvent(String serviceName) { super(serviceName, Collections.emptyList()); // instance list has been stored by ServiceInstancesChangedListener this.failureRecordTime = System.currentTimeMillis(); } public long getFailureRecordTime() { return failureRecordTime; } }
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/listener/ServiceInstancesChangedListener.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.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.URLBuilder; 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.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.metadata.MetadataInfo; import org.apache.dubbo.metadata.MetadataInfo.ServiceInfo; 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.DefaultServiceInstance; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.event.RetryServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils; import org.apache.dubbo.registry.client.metadata.ServiceInstanceNotificationCustomizer; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; 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.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_REFRESH_ADDRESS; 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.metadata.RevisionResolver.EMPTY_REVISION; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getExportedServicesRevision; /** * TODO, refactor to move revision-metadata mapping to ServiceDiscovery. Instances should have already been mapped with metadata when reached here. * <p> * The operations of ServiceInstancesChangedListener should be synchronized. */ public class ServiceInstancesChangedListener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ServiceInstancesChangedListener.class); protected final Set<String> serviceNames; protected final ServiceDiscovery serviceDiscovery; protected ConcurrentHashMap<String, Set<NotifyListenerWithKey>> listeners; protected AtomicBoolean destroyed = new AtomicBoolean(false); protected Map<String, List<ServiceInstance>> allInstances; protected Map<String, List<ProtocolServiceKeyWithUrls>> serviceUrls; private volatile long lastRefreshTime; private final Semaphore retryPermission; private volatile ScheduledFuture<?> retryFuture; private final ScheduledExecutorService scheduler; private volatile boolean hasEmptyMetadata; private final Set<ServiceInstanceNotificationCustomizer> serviceInstanceNotificationCustomizers; private final ApplicationModel applicationModel; public ServiceInstancesChangedListener(Set<String> serviceNames, ServiceDiscovery serviceDiscovery) { this.serviceNames = serviceNames; this.serviceDiscovery = serviceDiscovery; this.listeners = new ConcurrentHashMap<>(); this.allInstances = new HashMap<>(); this.serviceUrls = new HashMap<>(); retryPermission = new Semaphore(1); ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel( serviceDiscovery == null || serviceDiscovery.getUrl() == null ? null : serviceDiscovery.getUrl().getScopeModel()); this.scheduler = applicationModel .getBeanFactory() .getBean(FrameworkExecutorRepository.class) .getMetadataRetryExecutor(); this.serviceInstanceNotificationCustomizers = applicationModel .getExtensionLoader(ServiceInstanceNotificationCustomizer.class) .getSupportedExtensionInstances(); this.applicationModel = applicationModel; } /** * On {@link ServiceInstancesChangedEvent the service instances change event} * * @param event {@link ServiceInstancesChangedEvent} */ public void onEvent(ServiceInstancesChangedEvent event) { if (destroyed.get() || !accept(event) || isRetryAndExpired(event)) { return; } doOnEvent(event); } /** * @param event */ private synchronized void doOnEvent(ServiceInstancesChangedEvent event) { if (destroyed.get() || !accept(event) || isRetryAndExpired(event)) { return; } refreshInstance(event); if (logger.isDebugEnabled()) { logger.debug(event.getServiceInstances().toString()); } Map<String, List<ServiceInstance>> revisionToInstances = new HashMap<>(); Map<ServiceInfo, Set<String>> localServiceToRevisions = new HashMap<>(); // grouping all instances of this app(service name) by revision for (Map.Entry<String, List<ServiceInstance>> entry : allInstances.entrySet()) { List<ServiceInstance> instances = entry.getValue(); for (ServiceInstance instance : instances) { String revision = getExportedServicesRevision(instance); if (revision == null || EMPTY_REVISION.equals(revision)) { if (logger.isDebugEnabled()) { logger.debug("Find instance without valid service metadata: " + instance.getAddress()); } continue; } List<ServiceInstance> subInstances = revisionToInstances.computeIfAbsent(revision, r -> new LinkedList<>()); subInstances.add(instance); } } // get MetadataInfo with revision for (Map.Entry<String, List<ServiceInstance>> entry : revisionToInstances.entrySet()) { String revision = entry.getKey(); List<ServiceInstance> subInstances = entry.getValue(); MetadataInfo metadata = subInstances.stream() .map(ServiceInstance::getServiceMetadata) .filter(Objects::nonNull) .filter(m -> revision.equals(m.getRevision())) .findFirst() .orElseGet(() -> serviceDiscovery.getRemoteMetadata(revision, subInstances)); parseMetadata(revision, metadata, localServiceToRevisions); // update metadata into each instance, in case new instance created. for (ServiceInstance tmpInstance : subInstances) { MetadataInfo originMetadata = tmpInstance.getServiceMetadata(); if (originMetadata == null || !Objects.equals(originMetadata.getRevision(), metadata.getRevision())) { tmpInstance.setServiceMetadata(metadata); } } } int emptyNum = hasEmptyMetadata(revisionToInstances); if (emptyNum != 0) { hasEmptyMetadata = true; // return if all metadata is empty, this notification will not take effect. if (emptyNum == revisionToInstances.size()) { // 1-17 - Address refresh failed. logger.error( REGISTRY_FAILED_REFRESH_ADDRESS, "metadata Server failure", "", "Address refresh failed because of Metadata Server failure, wait for retry or new address refresh event."); submitRetryTask(event); return; } } else { hasEmptyMetadata = false; } Map<String, Map<Integer, Map<Set<String>, Object>>> protocolRevisionsToUrls = new HashMap<>(); Map<String, List<ProtocolServiceKeyWithUrls>> newServiceUrls = new HashMap<>(); for (Map.Entry<ServiceInfo, Set<String>> entry : localServiceToRevisions.entrySet()) { ServiceInfo serviceInfo = entry.getKey(); Set<String> revisions = entry.getValue(); Map<Integer, Map<Set<String>, Object>> portToRevisions = protocolRevisionsToUrls.computeIfAbsent(serviceInfo.getProtocol(), k -> new HashMap<>()); Map<Set<String>, Object> revisionsToUrls = portToRevisions.computeIfAbsent(serviceInfo.getPort(), k -> new HashMap<>()); Object urls = revisionsToUrls.computeIfAbsent( revisions, k -> getServiceUrlsCache( revisionToInstances, revisions, serviceInfo.getProtocol(), serviceInfo.getPort())); List<ProtocolServiceKeyWithUrls> list = newServiceUrls.computeIfAbsent(serviceInfo.getPath(), k -> new LinkedList<>()); list.add(new ProtocolServiceKeyWithUrls(serviceInfo.getProtocolServiceKey(), (List<URL>) urls)); } this.serviceUrls = newServiceUrls; this.notifyAddressChanged(); if (hasEmptyMetadata) { submitRetryTask(event); } } private void submitRetryTask(ServiceInstancesChangedEvent event) { // retry every 10 seconds if (retryPermission.tryAcquire()) { if (retryFuture != null && !retryFuture.isDone()) { // cancel last retryFuture because only one retryFuture will be canceled at destroy(). retryFuture.cancel(true); } try { retryFuture = scheduler.schedule( new AddressRefreshRetryTask(retryPermission, event.getServiceName()), 10_000L, TimeUnit.MILLISECONDS); } catch (Exception e) { logger.error( INTERNAL_ERROR, "unknown error in registry module", "", "Error submitting async retry task."); } logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "Address refresh try task submitted"); } } public synchronized void addListenerAndNotify(URL url, NotifyListener listener) { if (destroyed.get()) { return; } Set<NotifyListenerWithKey> notifyListeners = ConcurrentHashMapUtils.computeIfAbsent( this.listeners, url.getServiceKey(), _k -> new ConcurrentHashSet<>()); String protocol = listener.getConsumerUrl().getParameter(PROTOCOL_KEY, url.getProtocol()); ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey( url.getServiceInterface(), url.getVersion(), url.getGroup(), !CommonConstants.CONSUMER.equals(protocol) ? protocol : null); NotifyListenerWithKey listenerWithKey = new NotifyListenerWithKey(protocolServiceKey, listener); notifyListeners.add(listenerWithKey); // Aggregate address and notify on subscription. List<URL> urls = getAddresses(protocolServiceKey, listener.getConsumerUrl()); if (CollectionUtils.isNotEmpty(urls)) { logger.info(String.format( "Notify serviceKey: %s, listener: %s with %s urls on subscription", protocolServiceKey, listener, urls.size())); listener.notify(urls); } } public synchronized void removeListener(String serviceKey, NotifyListener notifyListener) { if (destroyed.get()) { return; } // synchronized method, no need to use DCL Set<NotifyListenerWithKey> notifyListeners = this.listeners.get(serviceKey); if (notifyListeners != null) { notifyListeners.removeIf(listener -> listener.getNotifyListener().equals(notifyListener)); // ServiceKey has no listener, remove set if (notifyListeners.isEmpty()) { this.listeners.remove(serviceKey); } } } public boolean hasListeners() { return CollectionUtils.isNotEmptyMap(listeners); } /** * Get the correlative service name * * @return the correlative service name */ public final Set<String> getServiceNames() { return serviceNames; } public Map<String, List<ServiceInstance>> getAllInstances() { return allInstances; } /** * @param event {@link ServiceInstancesChangedEvent event} * @return If service name matches, return <code>true</code>, or <code>false</code> */ private boolean accept(ServiceInstancesChangedEvent event) { return serviceNames.contains(event.getServiceName()); } protected boolean isRetryAndExpired(ServiceInstancesChangedEvent event) { if (event instanceof RetryServiceInstancesChangedEvent) { RetryServiceInstancesChangedEvent retryEvent = (RetryServiceInstancesChangedEvent) event; logger.warn( INTERNAL_ERROR, "unknown error in registry module", "", "Received address refresh retry event, " + retryEvent.getFailureRecordTime()); if (retryEvent.getFailureRecordTime() < lastRefreshTime && !hasEmptyMetadata) { logger.warn( INTERNAL_ERROR, "unknown error in registry module", "", "Ignore retry event, event time: " + retryEvent.getFailureRecordTime() + ", last refresh time: " + lastRefreshTime); return true; } logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "Retrying address notification..."); } return false; } private void refreshInstance(ServiceInstancesChangedEvent event) { if (event instanceof RetryServiceInstancesChangedEvent) { return; } String appName = event.getServiceName(); List<ServiceInstance> appInstances = event.getServiceInstances(); logger.info("Received instance notification, serviceName: " + appName + ", instances: " + appInstances.size()); for (ServiceInstanceNotificationCustomizer serviceInstanceNotificationCustomizer : serviceInstanceNotificationCustomizers) { serviceInstanceNotificationCustomizer.customize(appInstances); } allInstances.put(appName, appInstances); lastRefreshTime = System.currentTimeMillis(); } /** * Calculate the number of revisions that failed to find metadata info. * * @param revisionToInstances instance list classified by revisions * @return the number of revisions that failed at fetching MetadataInfo */ protected int hasEmptyMetadata(Map<String, List<ServiceInstance>> revisionToInstances) { if (revisionToInstances == null) { return 0; } StringBuilder builder = new StringBuilder(); int emptyMetadataNum = 0; for (Map.Entry<String, List<ServiceInstance>> entry : revisionToInstances.entrySet()) { DefaultServiceInstance serviceInstance = (DefaultServiceInstance) entry.getValue().get(0); if (serviceInstance == null || serviceInstance.getServiceMetadata() == MetadataInfo.EMPTY) { emptyMetadataNum++; } builder.append(entry.getKey()); builder.append(' '); } if (emptyMetadataNum > 0) { builder.insert( 0, emptyMetadataNum + "/" + revisionToInstances.size() + " revisions failed to get metadata from remote: "); logger.error(INTERNAL_ERROR, "unknown error in registry module", "", builder.toString()); } else { builder.insert(0, revisionToInstances.size() + " unique working revisions: "); logger.info(builder.toString()); } return emptyMetadataNum; } protected Map<ServiceInfo, Set<String>> parseMetadata( String revision, MetadataInfo metadata, Map<ServiceInfo, Set<String>> localServiceToRevisions) { Map<String, ServiceInfo> serviceInfos = metadata.getServices(); for (Map.Entry<String, ServiceInfo> entry : serviceInfos.entrySet()) { Set<String> set = localServiceToRevisions.computeIfAbsent(entry.getValue(), _k -> new TreeSet<>()); set.add(revision); } return localServiceToRevisions; } protected Object getServiceUrlsCache( Map<String, List<ServiceInstance>> revisionToInstances, Set<String> revisions, String protocol, int port) { List<URL> urls = new ArrayList<>(); for (String r : revisions) { for (ServiceInstance i : revisionToInstances.get(r)) { if (port > 0) { if (i.getPort() == port) { urls.add(i.toURL(protocol).setScopeModel(i.getApplicationModel())); } else { urls.add(((DefaultServiceInstance) i) .copyFrom(port) .toURL(protocol) .setScopeModel(i.getApplicationModel())); } continue; } // different protocols may have ports specified in meta if (ServiceInstanceMetadataUtils.hasEndpoints(i)) { DefaultServiceInstance.Endpoint endpoint = ServiceInstanceMetadataUtils.getEndpoint(i, protocol); if (endpoint != null && endpoint.getPort() != i.getPort()) { urls.add(((DefaultServiceInstance) i).copyFrom(endpoint).toURL(endpoint.getProtocol())); continue; } } urls.add(i.toURL(protocol).setScopeModel(i.getApplicationModel())); } } return urls; } protected List<URL> getAddresses(ProtocolServiceKey protocolServiceKey, URL consumerURL) { List<ProtocolServiceKeyWithUrls> protocolServiceKeyWithUrlsList = serviceUrls.get(protocolServiceKey.getInterfaceName()); List<URL> urls = new ArrayList<>(); if (protocolServiceKeyWithUrlsList != null) { for (ProtocolServiceKeyWithUrls protocolServiceKeyWithUrls : protocolServiceKeyWithUrlsList) { if (ProtocolServiceKey.Matcher.isMatch( protocolServiceKey, protocolServiceKeyWithUrls.getProtocolServiceKey())) { urls.addAll(protocolServiceKeyWithUrls.getUrls()); } } } if (serviceUrls.containsKey(CommonConstants.ANY_VALUE)) { for (ProtocolServiceKeyWithUrls protocolServiceKeyWithUrls : serviceUrls.get(CommonConstants.ANY_VALUE)) { urls.addAll(protocolServiceKeyWithUrls.getUrls()); } } return urls; } /** * race condition is protected by onEvent/doOnEvent */ protected void notifyAddressChanged() { MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), () -> { Map<String, Integer> lastNumMap = new HashMap<>(); // 1 different services listeners.forEach((serviceKey, listenerSet) -> { // 2 multiple subscription listener of the same service for (NotifyListenerWithKey listenerWithKey : listenerSet) { NotifyListener notifyListener = listenerWithKey.getNotifyListener(); List<URL> urls = toUrlsWithEmpty( getAddresses(listenerWithKey.getProtocolServiceKey(), notifyListener.getConsumerUrl())); logger.info( "Notify service " + listenerWithKey.getProtocolServiceKey() + " with urls " + urls.size()); notifyListener.notify(urls); lastNumMap.put(serviceKey, urls.size()); } }); return lastNumMap; }); } protected List<URL> toUrlsWithEmpty(List<URL> urls) { boolean emptyProtectionEnabled = serviceDiscovery.getUrl().getParameter(ENABLE_EMPTY_PROTECTION_KEY, DEFAULT_ENABLE_EMPTY_PROTECTION); if (!emptyProtectionEnabled && urls == null) { urls = new ArrayList<>(); } else if (emptyProtectionEnabled && urls == null) { urls = Collections.emptyList(); } if (CollectionUtils.isEmpty(urls) && !emptyProtectionEnabled) { // notice that the service of this.url may not be the same as notify listener. URL empty = URLBuilder.from(serviceDiscovery.getUrl()) .setProtocol(EMPTY_PROTOCOL) .build(); urls.add(empty); } return urls; } /** * Since this listener is shared among interfaces, destroy this listener only when all interface listener are unsubscribed */ public void destroy() { if (destroyed.compareAndSet(false, true)) { logger.info("Destroying instance listener of " + this.getServiceNames()); serviceDiscovery.removeServiceInstancesChangedListener(this); synchronized (this) { allInstances.clear(); serviceUrls.clear(); listeners.clear(); if (retryFuture != null && !retryFuture.isDone()) { retryFuture.cancel(true); } } } } public boolean isDestroyed() { return destroyed.get(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ServiceInstancesChangedListener)) { return false; } ServiceInstancesChangedListener that = (ServiceInstancesChangedListener) o; return Objects.equals(getServiceNames(), that.getServiceNames()) && Objects.equals(listeners, that.listeners); } @Override public int hashCode() { return Objects.hash(getClass(), getServiceNames()); } protected class AddressRefreshRetryTask implements Runnable { private final RetryServiceInstancesChangedEvent retryEvent; private final Semaphore retryPermission; public AddressRefreshRetryTask(Semaphore semaphore, String serviceName) { this.retryEvent = new RetryServiceInstancesChangedEvent(serviceName); this.retryPermission = semaphore; } @Override public void run() { retryPermission.release(); ServiceInstancesChangedListener.this.onEvent(retryEvent); } } public static class NotifyListenerWithKey { private final ProtocolServiceKey protocolServiceKey; private final NotifyListener notifyListener; public NotifyListenerWithKey(ProtocolServiceKey protocolServiceKey, NotifyListener notifyListener) { this.protocolServiceKey = protocolServiceKey; this.notifyListener = notifyListener; } public ProtocolServiceKey getProtocolServiceKey() { return protocolServiceKey; } public NotifyListener getNotifyListener() { return notifyListener; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NotifyListenerWithKey that = (NotifyListenerWithKey) o; return Objects.equals(protocolServiceKey, that.protocolServiceKey) && Objects.equals(notifyListener, that.notifyListener); } @Override public int hashCode() { return Objects.hash(protocolServiceKey, notifyListener); } } public static class ProtocolServiceKeyWithUrls { private final ProtocolServiceKey protocolServiceKey; private final List<URL> urls; public ProtocolServiceKeyWithUrls(ProtocolServiceKey protocolServiceKey, List<URL> urls) { this.protocolServiceKey = protocolServiceKey; this.urls = urls; } public ProtocolServiceKey getProtocolServiceKey() { return protocolServiceKey; } public List<URL> getUrls() { return 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/client/migration/MigrationAddressComparator.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationAddressComparator.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.extension.SPI; import org.apache.dubbo.registry.client.migration.model.MigrationRule; import org.apache.dubbo.rpc.cluster.ClusterInvoker; import java.util.Map; @SPI public interface MigrationAddressComparator { <T> boolean shouldMigrate(ClusterInvoker<T> newInvoker, ClusterInvoker<T> oldInvoker, MigrationRule rule); Map<String, Integer> getAddressSize(String displayServiceKey); }
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/migration/MigrationRuleListener.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleListener.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.ConfigurationUtils; 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.extension.Activate; 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.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.client.migration.model.MigrationRule; import org.apache.dubbo.registry.integration.RegistryProtocol; import org.apache.dubbo.registry.integration.RegistryProtocolListener; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.cluster.ClusterInvoker; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_THREAD_INTERRUPTED_EXCEPTION; 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.RegistryConstants.INIT; /** * Listens to {@MigrationRule} from Config Center. * <p> * - Migration rule is of consumer application scope. * - Listener is shared among all invokers (interfaces), it keeps the relation between interface and handler. * <p> * There are two execution points: * - Refer, invoker behaviour is determined with default rule. * - Rule change, invoker behaviour is changed according to the newly received rule. */ @Activate public class MigrationRuleListener implements RegistryProtocolListener, ConfigurationListener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MigrationRuleListener.class); private static final String DUBBO_SERVICEDISCOVERY_MIGRATION = "DUBBO_SERVICEDISCOVERY_MIGRATION"; private static final String MIGRATION_DELAY_KEY = "dubbo.application.migration.delay"; private static final int MIGRATION_DEFAULT_DELAY_TIME = 60000; private String ruleKey; protected final ConcurrentMap<MigrationInvoker<?>, MigrationRuleHandler<?>> handlers = new ConcurrentHashMap<>(); protected final LinkedBlockingQueue<String> ruleQueue = new LinkedBlockingQueue<>(); private final AtomicBoolean executorSubmit = new AtomicBoolean(false); private final ExecutorService ruleManageExecutor = Executors.newFixedThreadPool(1, new NamedThreadFactory("Dubbo-Migration-Listener")); protected ScheduledFuture<?> localRuleMigrationFuture; protected Future<?> ruleMigrationFuture; private DynamicConfiguration configuration; private volatile String rawRule; private volatile MigrationRule rule; private final ModuleModel moduleModel; public MigrationRuleListener(ModuleModel moduleModel) { this.moduleModel = moduleModel; init(); } private void init() { this.ruleKey = moduleModel.getApplicationModel().getApplicationName() + ".migration"; this.configuration = moduleModel.modelEnvironment().getDynamicConfiguration().orElse(null); if (this.configuration != null) { logger.info("Listening for migration rules on dataId " + ruleKey + ", group " + DUBBO_SERVICEDISCOVERY_MIGRATION); configuration.addListener(ruleKey, DUBBO_SERVICEDISCOVERY_MIGRATION, this); String rawRule = configuration.getConfig(ruleKey, DUBBO_SERVICEDISCOVERY_MIGRATION); if (StringUtils.isEmpty(rawRule)) { rawRule = INIT; } setRawRule(rawRule); } else { if (logger.isWarnEnabled()) { logger.warn( REGISTRY_EMPTY_ADDRESS, "", "", "Using default configuration rule because config center is not configured!"); } setRawRule(INIT); } String localRawRule = moduleModel.modelEnvironment().getLocalMigrationRule(); if (!StringUtils.isEmpty(localRawRule)) { localRuleMigrationFuture = moduleModel .getApplicationModel() .getFrameworkModel() .getBeanFactory() .getBean(FrameworkExecutorRepository.class) .getSharedScheduledExecutor() .schedule( () -> { if (this.rawRule.equals(INIT)) { this.process(new ConfigChangedEvent(null, null, localRawRule)); } }, getDelay(), TimeUnit.MILLISECONDS); } } private int getDelay() { int delay = MIGRATION_DEFAULT_DELAY_TIME; String delayStr = ConfigurationUtils.getProperty(moduleModel, MIGRATION_DELAY_KEY); if (StringUtils.isEmpty(delayStr)) { return delay; } try { delay = Integer.parseInt(delayStr); } catch (Exception e) { logger.warn(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Invalid migration delay param " + delayStr); } return delay; } @Override public synchronized void process(ConfigChangedEvent event) { String rawRule = event.getContent(); if (StringUtils.isEmpty(rawRule)) { // fail back to startup status rawRule = INIT; // logger.warn(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Received empty migration rule, will ignore."); } try { ruleQueue.put(rawRule); } catch (InterruptedException e) { logger.error( COMMON_THREAD_INTERRUPTED_EXCEPTION, "", "", "Put rawRule to rule management queue failed. rawRule: " + rawRule, e); } if (executorSubmit.compareAndSet(false, true)) { ruleMigrationFuture = ruleManageExecutor.submit(() -> { while (true) { String rule = ""; try { rule = ruleQueue.take(); if (StringUtils.isEmpty(rule)) { Thread.sleep(1000); } } catch (InterruptedException e) { logger.error( COMMON_THREAD_INTERRUPTED_EXCEPTION, "", "", "Poll Rule from config center failed.", e); } if (StringUtils.isEmpty(rule)) { continue; } if (Objects.equals(this.rawRule, rule)) { logger.info("Ignore duplicated rule"); continue; } logger.info("Using the following migration rule to migrate:"); logger.info(rule); setRawRule(rule); if (CollectionUtils.isEmptyMap(handlers)) { continue; } ExecutorService executorService = null; try { executorService = Executors.newFixedThreadPool( Math.min(handlers.size(), 100), new NamedThreadFactory("Dubbo-Invoker-Migrate")); List<Future<?>> migrationFutures = new ArrayList<>(handlers.size()); for (MigrationRuleHandler<?> handler : handlers.values()) { Future<?> future = executorService.submit(() -> handler.doMigrate(this.rule)); migrationFutures.add(future); } for (Future<?> future : migrationFutures) { try { future.get(); } catch (InterruptedException ie) { logger.warn( INTERNAL_ERROR, "unknown error in registry module", "", "Interrupted while waiting for migration async task to finish."); } catch (ExecutionException ee) { logger.error( INTERNAL_ERROR, "unknown error in registry module", "", "Migration async task failed.", ee.getCause()); } } } catch (Throwable t) { logger.error( INTERNAL_ERROR, "unknown error in registry module", "", "Error occurred when migration.", t); } finally { if (executorService != null) { executorService.shutdown(); } } } }); } } public void setRawRule(String rawRule) { this.rawRule = rawRule; this.rule = parseRule(this.rawRule); } private MigrationRule parseRule(String rawRule) { MigrationRule tmpRule = rule == null ? MigrationRule.getInitRule() : rule; if (INIT.equals(rawRule)) { tmpRule = MigrationRule.getInitRule(); } else { try { tmpRule = MigrationRule.parse(rawRule); } catch (Exception e) { logger.error(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Failed to parse migration rule...", e); } } return tmpRule; } @Override public void onExport(RegistryProtocol registryProtocol, Exporter<?> exporter) {} @Override public void onRefer( RegistryProtocol registryProtocol, ClusterInvoker<?> invoker, URL consumerUrl, URL registryURL) { MigrationRuleHandler<?> migrationRuleHandler = ConcurrentHashMapUtils.computeIfAbsent(handlers, (MigrationInvoker<?>) invoker, _key -> { ((MigrationInvoker<?>) invoker).setMigrationRuleListener(this); return new MigrationRuleHandler<>((MigrationInvoker<?>) invoker, consumerUrl); }); migrationRuleHandler.doMigrate(rule); } @Override public void onDestroy() { if (configuration != null) { configuration.removeListener(ruleKey, DUBBO_SERVICEDISCOVERY_MIGRATION, this); } if (ruleMigrationFuture != null) { ruleMigrationFuture.cancel(true); } if (localRuleMigrationFuture != null) { localRuleMigrationFuture.cancel(true); } ruleManageExecutor.shutdown(); ruleQueue.clear(); } public Map<MigrationInvoker<?>, MigrationRuleHandler<?>> getHandlers() { return handlers; } protected void removeMigrationInvoker(MigrationInvoker<?> migrationInvoker) { handlers.remove(migrationInvoker); } public MigrationRule getRule() { return 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/main/java/org/apache/dubbo/registry/client/migration/MigrationInvoker.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationInvoker.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.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.client.migration.model.MigrationRule; import org.apache.dubbo.registry.client.migration.model.MigrationStep; import org.apache.dubbo.registry.integration.DynamicDirectory; import org.apache.dubbo.registry.integration.RegistryProtocol; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; 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.Directory; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT; import static org.apache.dubbo.registry.client.migration.model.MigrationStep.APPLICATION_FIRST; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; public class MigrationInvoker<T> implements MigrationClusterInvoker<T> { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MigrationInvoker.class); private URL url; private final URL consumerUrl; private final Cluster cluster; private final Registry registry; private final Class<T> type; private final RegistryProtocol registryProtocol; private MigrationRuleListener migrationRuleListener; private final ConsumerModel consumerModel; private final FrameworkStatusReportService reportService; private volatile ClusterInvoker<T> invoker; private volatile ClusterInvoker<T> serviceDiscoveryInvoker; private volatile ClusterInvoker<T> currentAvailableInvoker; private volatile MigrationStep step; private volatile MigrationRule rule; private volatile int promotion = 100; public MigrationInvoker( RegistryProtocol registryProtocol, Cluster cluster, Registry registry, Class<T> type, URL url, URL consumerUrl) { this(null, null, registryProtocol, cluster, registry, type, url, consumerUrl); } @SuppressWarnings("unchecked") public MigrationInvoker( ClusterInvoker<T> invoker, ClusterInvoker<T> serviceDiscoveryInvoker, RegistryProtocol registryProtocol, Cluster cluster, Registry registry, Class<T> type, URL url, URL consumerUrl) { this.invoker = invoker; this.serviceDiscoveryInvoker = serviceDiscoveryInvoker; this.registryProtocol = registryProtocol; this.cluster = cluster; this.registry = registry; this.type = type; this.url = url; this.consumerUrl = consumerUrl; this.consumerModel = (ConsumerModel) consumerUrl.getServiceModel(); this.reportService = consumerUrl.getOrDefaultApplicationModel().getBeanFactory().getBean(FrameworkStatusReportService.class); if (consumerModel != null) { Object object = consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY); Map<Registry, MigrationInvoker<?>> invokerMap; if (object instanceof Map) { invokerMap = (Map<Registry, MigrationInvoker<?>>) object; } else { invokerMap = new ConcurrentHashMap<>(); } invokerMap.put(registry, this); consumerModel.getServiceMetadata().addAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY, invokerMap); } } public ClusterInvoker<T> getInvoker() { return invoker; } public void setInvoker(ClusterInvoker<T> invoker) { this.invoker = invoker; } public ClusterInvoker<T> getServiceDiscoveryInvoker() { return serviceDiscoveryInvoker; } public void setServiceDiscoveryInvoker(ClusterInvoker<T> serviceDiscoveryInvoker) { this.serviceDiscoveryInvoker = serviceDiscoveryInvoker; } public ClusterInvoker<T> getCurrentAvailableInvoker() { return currentAvailableInvoker; } @Override public Class<T> getInterface() { return type; } @Override public void reRefer(URL newSubscribeUrl) { // update url to prepare for migration refresh this.url = url.addParameter(REFER_KEY, StringUtils.toQueryString(newSubscribeUrl.getParameters())); // re-subscribe immediately if (invoker != null && !invoker.isDestroyed()) { doReSubscribe(invoker, newSubscribeUrl); } if (serviceDiscoveryInvoker != null && !serviceDiscoveryInvoker.isDestroyed()) { doReSubscribe(serviceDiscoveryInvoker, newSubscribeUrl); } } private void doReSubscribe(ClusterInvoker<T> invoker, URL newSubscribeUrl) { DynamicDirectory<T> directory = (DynamicDirectory<T>) invoker.getDirectory(); URL oldSubscribeUrl = directory.getRegisteredConsumerUrl(); Registry registry = directory.getRegistry(); registry.unregister(directory.getRegisteredConsumerUrl()); directory.unSubscribe(RegistryProtocol.toSubscribeUrl(oldSubscribeUrl)); if (directory.isShouldRegister()) { registry.register(directory.getRegisteredConsumerUrl()); directory.setRegisteredConsumerUrl(newSubscribeUrl); } directory.buildRouterChain(newSubscribeUrl); directory.subscribe(RegistryProtocol.toSubscribeUrl(newSubscribeUrl)); } @Override public boolean migrateToForceInterfaceInvoker(MigrationRule newRule) { CountDownLatch latch = new CountDownLatch(1); refreshInterfaceInvoker(latch); if (serviceDiscoveryInvoker == null) { // serviceDiscoveryInvoker is absent, ignore threshold check this.currentAvailableInvoker = invoker; return true; } // wait and compare threshold waitAddressNotify(newRule, latch); if (newRule.getForce(consumerUrl)) { // force migrate, ignore threshold check this.currentAvailableInvoker = invoker; this.destroyServiceDiscoveryInvoker(); return true; } Set<MigrationAddressComparator> detectors = ScopeModelUtil.getApplicationModel( consumerUrl == null ? null : consumerUrl.getScopeModel()) .getExtensionLoader(MigrationAddressComparator.class) .getSupportedExtensionInstances(); if (CollectionUtils.isNotEmpty(detectors)) { if (detectors.stream() .allMatch(comparator -> comparator.shouldMigrate(invoker, serviceDiscoveryInvoker, newRule))) { this.currentAvailableInvoker = invoker; this.destroyServiceDiscoveryInvoker(); return true; } } // compare failed, will not change state if (step == MigrationStep.FORCE_APPLICATION) { destroyInterfaceInvoker(); } return false; } @Override public boolean migrateToForceApplicationInvoker(MigrationRule newRule) { CountDownLatch latch = new CountDownLatch(1); refreshServiceDiscoveryInvoker(latch); if (invoker == null) { // invoker is absent, ignore threshold check this.currentAvailableInvoker = serviceDiscoveryInvoker; return true; } // wait and compare threshold waitAddressNotify(newRule, latch); if (newRule.getForce(consumerUrl)) { // force migrate, ignore threshold check this.currentAvailableInvoker = serviceDiscoveryInvoker; this.destroyInterfaceInvoker(); return true; } Set<MigrationAddressComparator> detectors = ScopeModelUtil.getApplicationModel( consumerUrl == null ? null : consumerUrl.getScopeModel()) .getExtensionLoader(MigrationAddressComparator.class) .getSupportedExtensionInstances(); if (CollectionUtils.isNotEmpty(detectors)) { if (detectors.stream() .allMatch(comparator -> comparator.shouldMigrate(serviceDiscoveryInvoker, invoker, newRule))) { this.currentAvailableInvoker = serviceDiscoveryInvoker; this.destroyInterfaceInvoker(); return true; } } // compare failed, will not change state if (step == MigrationStep.FORCE_INTERFACE) { destroyServiceDiscoveryInvoker(); } return false; } @Override public void migrateToApplicationFirstInvoker(MigrationRule newRule) { CountDownLatch latch = new CountDownLatch(0); refreshInterfaceInvoker(latch); refreshServiceDiscoveryInvoker(latch); // directly calculate preferred invoker, will not wait until address notify // calculation will re-occurred when address notify later calcPreferredInvoker(newRule); } @SuppressWarnings("all") private void waitAddressNotify(MigrationRule newRule, CountDownLatch latch) { // wait and compare threshold int delay = newRule.getDelay(consumerUrl); if (delay > 0) { try { Thread.sleep(delay * 1000L); } catch (InterruptedException e) { logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Interrupted when waiting for address notify!" + e); } } else { // do not wait address notify by default delay = 0; } try { latch.await(delay, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Interrupted when waiting for address notify!" + e); } } @Override public Result invoke(Invocation invocation) throws RpcException { if (currentAvailableInvoker != null) { if (step == APPLICATION_FIRST) { // call ratio calculation based on random value if (promotion < 100 && ThreadLocalRandom.current().nextDouble(100) > promotion) { // fall back to interface mode return invoker.invoke(invocation); } // check if invoker available for each time return decideInvoker().invoke(invocation); } return currentAvailableInvoker.invoke(invocation); } switch (step) { case APPLICATION_FIRST: currentAvailableInvoker = decideInvoker(); break; case FORCE_APPLICATION: currentAvailableInvoker = serviceDiscoveryInvoker; break; case FORCE_INTERFACE: default: currentAvailableInvoker = invoker; } return currentAvailableInvoker.invoke(invocation); } private ClusterInvoker<T> decideInvoker() { if (currentAvailableInvoker == serviceDiscoveryInvoker) { if (checkInvokerAvailable(serviceDiscoveryInvoker)) { return serviceDiscoveryInvoker; } return invoker; } else { return currentAvailableInvoker; } } @Override public boolean isAvailable() { return currentAvailableInvoker != null ? currentAvailableInvoker.isAvailable() : (invoker != null && invoker.isAvailable()) || (serviceDiscoveryInvoker != null && serviceDiscoveryInvoker.isAvailable()); } @SuppressWarnings("unchecked") @Override public void destroy() { if (migrationRuleListener != null) { migrationRuleListener.removeMigrationInvoker(this); } if (invoker != null) { invoker.destroy(); } if (serviceDiscoveryInvoker != null) { serviceDiscoveryInvoker.destroy(); } if (consumerModel != null) { Object object = consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY); Map<Registry, MigrationInvoker<?>> invokerMap; if (object instanceof Map) { invokerMap = (Map<Registry, MigrationInvoker<?>>) object; invokerMap.remove(registry); if (invokerMap.isEmpty()) { consumerModel .getServiceMetadata() .getAttributeMap() .remove(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY); } } } } @Override public URL getUrl() { if (currentAvailableInvoker != null) { return currentAvailableInvoker.getUrl(); } else if (invoker != null) { return invoker.getUrl(); } else if (serviceDiscoveryInvoker != null) { return serviceDiscoveryInvoker.getUrl(); } return consumerUrl; } @Override public URL getRegistryUrl() { if (currentAvailableInvoker != null) { return currentAvailableInvoker.getRegistryUrl(); } else if (invoker != null) { return invoker.getRegistryUrl(); } else if (serviceDiscoveryInvoker != null) { return serviceDiscoveryInvoker.getRegistryUrl(); } return url; } @Override public Directory<T> getDirectory() { if (currentAvailableInvoker != null) { return currentAvailableInvoker.getDirectory(); } else if (invoker != null) { return invoker.getDirectory(); } else if (serviceDiscoveryInvoker != null) { return serviceDiscoveryInvoker.getDirectory(); } return null; } @Override public boolean isDestroyed() { return currentAvailableInvoker != null ? currentAvailableInvoker.isDestroyed() : (invoker == null || invoker.isDestroyed()) && (serviceDiscoveryInvoker == null || serviceDiscoveryInvoker.isDestroyed()); } @Override public boolean isServiceDiscovery() { return false; } @Override public MigrationStep getMigrationStep() { return step; } @Override public void setMigrationStep(MigrationStep step) { this.step = step; } @Override public MigrationRule getMigrationRule() { return rule; } @Override public void setMigrationRule(MigrationRule rule) { this.rule = rule; promotion = rule.getProportion(consumerUrl); } protected void destroyServiceDiscoveryInvoker() { if (this.invoker != null) { this.currentAvailableInvoker = this.invoker; } if (serviceDiscoveryInvoker != null && !serviceDiscoveryInvoker.isDestroyed()) { if (logger.isInfoEnabled()) { logger.info( "Destroying instance address invokers, will not listen for address changes until re-subscribed, " + type.getName()); } serviceDiscoveryInvoker.destroy(); serviceDiscoveryInvoker = null; } } protected void refreshServiceDiscoveryInvoker(CountDownLatch latch) { clearListener(serviceDiscoveryInvoker); if (needRefresh(serviceDiscoveryInvoker)) { if (logger.isDebugEnabled()) { logger.debug("Re-subscribing instance addresses, current interface " + type.getName()); } if (serviceDiscoveryInvoker != null) { serviceDiscoveryInvoker.destroy(); } serviceDiscoveryInvoker = registryProtocol.getServiceDiscoveryInvoker(cluster, registry, type, url); } setListener(serviceDiscoveryInvoker, () -> { latch.countDown(); if (reportService.hasReporter()) { reportService.reportConsumptionStatus(reportService.createConsumptionReport( consumerUrl.getServiceInterface(), consumerUrl.getVersion(), consumerUrl.getGroup(), "app")); } if (step == APPLICATION_FIRST) { calcPreferredInvoker(rule); } }); } protected void refreshInterfaceInvoker(CountDownLatch latch) { clearListener(invoker); if (needRefresh(invoker)) { if (logger.isDebugEnabled()) { logger.debug("Re-subscribing interface addresses for interface " + type.getName()); } if (invoker != null) { invoker.destroy(); } invoker = registryProtocol.getInvoker(cluster, registry, type, url); } setListener(invoker, () -> { latch.countDown(); if (reportService.hasReporter()) { reportService.reportConsumptionStatus(reportService.createConsumptionReport( consumerUrl.getServiceInterface(), consumerUrl.getVersion(), consumerUrl.getGroup(), "interface")); } if (step == APPLICATION_FIRST) { calcPreferredInvoker(rule); } }); } private synchronized void calcPreferredInvoker(MigrationRule migrationRule) { if (serviceDiscoveryInvoker == null || invoker == null) { return; } Set<MigrationAddressComparator> detectors = ScopeModelUtil.getApplicationModel( consumerUrl == null ? null : consumerUrl.getScopeModel()) .getExtensionLoader(MigrationAddressComparator.class) .getSupportedExtensionInstances(); if (CollectionUtils.isNotEmpty(detectors)) { // pick preferred invoker // the real invoker choice in invocation will be affected by promotion if (detectors.stream() .allMatch( comparator -> comparator.shouldMigrate(serviceDiscoveryInvoker, invoker, migrationRule))) { this.currentAvailableInvoker = serviceDiscoveryInvoker; } else { this.currentAvailableInvoker = invoker; } } } protected void destroyInterfaceInvoker() { if (this.serviceDiscoveryInvoker != null) { this.currentAvailableInvoker = this.serviceDiscoveryInvoker; } if (invoker != null && !invoker.isDestroyed()) { if (logger.isInfoEnabled()) { logger.info( "Destroying interface address invokers, will not listen for address changes until re-subscribed, " + type.getName()); } invoker.destroy(); invoker = null; } } private void clearListener(ClusterInvoker<T> invoker) { if (invoker == null) { return; } DynamicDirectory<T> directory = (DynamicDirectory<T>) invoker.getDirectory(); directory.setInvokersChangedListener(null); } private void setListener(ClusterInvoker<T> invoker, InvokersChangedListener listener) { if (invoker == null) { return; } DynamicDirectory<T> directory = (DynamicDirectory<T>) invoker.getDirectory(); directory.setInvokersChangedListener(listener); } private boolean needRefresh(ClusterInvoker<T> invoker) { return invoker == null || invoker.isDestroyed() || !invoker.hasProxyInvokers(); } public boolean checkInvokerAvailable(ClusterInvoker<T> invoker) { return invoker != null && !invoker.isDestroyed() && invoker.isAvailable(); } protected void setCurrentAvailableInvoker(ClusterInvoker<T> currentAvailableInvoker) { this.currentAvailableInvoker = currentAvailableInvoker; } protected void setMigrationRuleListener(MigrationRuleListener migrationRuleListener) { this.migrationRuleListener = migrationRuleListener; } public Cluster getCluster() { return cluster; } public URL getConsumerUrl() { return consumerUrl; } @Override public String toString() { return "MigrationInvoker{" + "serviceKey=" + consumerUrl.getServiceKey() + ", invoker=" + decideInvoker() + ", step=" + step + '}'; } }
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/migration/MigrationClusterInvoker.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationClusterInvoker.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.cluster.ClusterInvoker; /** * FIXME, some methods need to be further optimized. * * @param <T> */ public interface MigrationClusterInvoker<T> extends ClusterInvoker<T> { @Override boolean isServiceDiscovery(); MigrationStep getMigrationStep(); void setMigrationStep(MigrationStep step); MigrationRule getMigrationRule(); void setMigrationRule(MigrationRule rule); boolean migrateToForceInterfaceInvoker(MigrationRule newRule); boolean migrateToForceApplicationInvoker(MigrationRule newRule); void migrateToApplicationFirstInvoker(MigrationRule newRule); void reRefer(URL newSubscribeUrl); }
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/migration/MigrationRuleHandler.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.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.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService; import org.apache.dubbo.registry.client.migration.model.MigrationRule; import org.apache.dubbo.registry.client.migration.model.MigrationStep; import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NO_PARAMETERS_URL; public class MigrationRuleHandler<T> { public static final String DUBBO_SERVICEDISCOVERY_MIGRATION = "dubbo.application.migration.step"; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MigrationRuleHandler.class); private final MigrationClusterInvoker<T> migrationInvoker; private volatile MigrationStep currentStep; private volatile Float currentThreshold = 0f; private final URL consumerURL; private final ReentrantLock lock = new ReentrantLock(); public MigrationRuleHandler(MigrationClusterInvoker<T> invoker, URL url) { this.migrationInvoker = invoker; this.consumerURL = url; } public void doMigrate(MigrationRule rule) { lock.lock(); try { if (migrationInvoker instanceof ServiceDiscoveryMigrationInvoker) { refreshInvoker(MigrationStep.FORCE_APPLICATION, 1.0f, rule); return; } // initial step : APPLICATION_FIRST MigrationStep step = MigrationStep.APPLICATION_FIRST; float threshold = -1f; try { step = rule.getStep(consumerURL); threshold = rule.getThreshold(consumerURL); } catch (Exception e) { logger.error( REGISTRY_NO_PARAMETERS_URL, "", "", "Failed to get step and threshold info from rule: " + rule, e); } if (refreshInvoker(step, threshold, rule)) { // refresh success, update rule setMigrationRule(rule); } } finally { lock.unlock(); } } private boolean refreshInvoker(MigrationStep step, Float threshold, MigrationRule newRule) { if (step == null || threshold == null) { throw new IllegalStateException("Step or threshold of migration rule cannot be null"); } MigrationStep originStep = currentStep; if ((currentStep == null || currentStep != step) || !currentThreshold.equals(threshold)) { boolean success = true; switch (step) { case APPLICATION_FIRST: migrationInvoker.migrateToApplicationFirstInvoker(newRule); break; case FORCE_APPLICATION: success = migrationInvoker.migrateToForceApplicationInvoker(newRule); break; case FORCE_INTERFACE: default: success = migrationInvoker.migrateToForceInterfaceInvoker(newRule); } if (success) { setCurrentStepAndThreshold(step, threshold); logger.info( "Succeed Migrated to " + step + " mode. Service Name: " + consumerURL.getDisplayServiceKey()); report(step, originStep, "true"); } else { // migrate failed, do not save new step and rule logger.warn( INTERNAL_ERROR, "unknown error in registry module", "", "Migrate to " + step + " mode failed. Probably not satisfy the threshold you set " + threshold + ". Please try re-publish configuration if you still after check."); report(step, originStep, "false"); } return success; } // ignore if step is same with previous, will continue override rule for MigrationInvoker return true; } private void report(MigrationStep step, MigrationStep originStep, String success) { FrameworkStatusReportService reportService = consumerURL.getOrDefaultApplicationModel().getBeanFactory().getBean(FrameworkStatusReportService.class); if (reportService.hasReporter()) { reportService.reportMigrationStepStatus(reportService.createMigrationStepReport( consumerURL.getServiceInterface(), consumerURL.getVersion(), consumerURL.getGroup(), String.valueOf(originStep), String.valueOf(step), success)); } } private void setMigrationRule(MigrationRule rule) { this.migrationInvoker.setMigrationRule(rule); } private void setCurrentStepAndThreshold(MigrationStep currentStep, Float currentThreshold) { if (currentThreshold != null) { this.currentThreshold = currentThreshold; } if (currentStep != null) { this.currentStep = currentStep; this.migrationInvoker.setMigrationStep(currentStep); } } // for test purpose public MigrationStep getMigrationStep() { return currentStep; } }
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/migration/DefaultMigrationAddressComparator.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparator.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.config.ConfigurationUtils; 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.StringUtils; import org.apache.dubbo.registry.client.migration.model.MigrationRule; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.cluster.ClusterInvoker; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH; public class DefaultMigrationAddressComparator implements MigrationAddressComparator { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultMigrationAddressComparator.class); private static final String MIGRATION_THRESHOLD = "dubbo.application.migration.threshold"; private static final String DEFAULT_THRESHOLD_STRING = "0.0"; private static final float DEFAULT_THREAD = 0f; public static final String OLD_ADDRESS_SIZE = "OLD_ADDRESS_SIZE"; public static final String NEW_ADDRESS_SIZE = "NEW_ADDRESS_SIZE"; private final ConcurrentMap<String, Map<String, Integer>> serviceMigrationData = new ConcurrentHashMap<>(); @Override public <T> boolean shouldMigrate(ClusterInvoker<T> newInvoker, ClusterInvoker<T> oldInvoker, MigrationRule rule) { Map<String, Integer> migrationData = ConcurrentHashMapUtils.computeIfAbsent( serviceMigrationData, oldInvoker.getUrl().getDisplayServiceKey(), _k -> new ConcurrentHashMap<>()); if (!newInvoker.hasProxyInvokers()) { migrationData.put(OLD_ADDRESS_SIZE, getAddressSize(oldInvoker)); migrationData.put(NEW_ADDRESS_SIZE, -1); logger.info("No " + getInvokerType(newInvoker) + " address available, stop compare."); return false; } if (!oldInvoker.hasProxyInvokers()) { migrationData.put(OLD_ADDRESS_SIZE, -1); migrationData.put(NEW_ADDRESS_SIZE, getAddressSize(newInvoker)); logger.info("No " + getInvokerType(oldInvoker) + " address available, stop compare."); return true; } int newAddressSize = getAddressSize(newInvoker); int oldAddressSize = getAddressSize(oldInvoker); migrationData.put(OLD_ADDRESS_SIZE, oldAddressSize); migrationData.put(NEW_ADDRESS_SIZE, newAddressSize); String rawThreshold = null; Float configuredThreshold = rule == null ? null : rule.getThreshold(oldInvoker.getUrl()); if (configuredThreshold != null && configuredThreshold >= 0) { rawThreshold = String.valueOf(configuredThreshold); } rawThreshold = StringUtils.isNotEmpty(rawThreshold) ? rawThreshold : ConfigurationUtils.getCachedDynamicProperty( newInvoker.getUrl().getScopeModel(), MIGRATION_THRESHOLD, DEFAULT_THRESHOLD_STRING); float threshold; try { threshold = Float.parseFloat(rawThreshold); } catch (Exception e) { logger.error(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Invalid migration threshold " + rawThreshold); threshold = DEFAULT_THREAD; } logger.info("serviceKey:" + oldInvoker.getUrl().getServiceKey() + " Instance address size " + newAddressSize + ", interface address size " + oldAddressSize + ", threshold " + threshold); if (newAddressSize != 0 && oldAddressSize == 0) { return true; } if (newAddressSize == 0 && oldAddressSize == 0) { return false; } return ((float) newAddressSize / (float) oldAddressSize) >= threshold; } private <T> int getAddressSize(ClusterInvoker<T> invoker) { if (invoker == null) { return -1; } List<Invoker<T>> invokers = invoker.getDirectory().getAllInvokers(); return CollectionUtils.isNotEmpty(invokers) ? invokers.size() : 0; } @Override public Map<String, Integer> getAddressSize(String displayServiceKey) { return serviceMigrationData.get(displayServiceKey); } private String getInvokerType(ClusterInvoker<?> invoker) { if (invoker.isServiceDiscovery()) { return "instance"; } return "interface"; } }
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/migration/InvokersChangedListener.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/InvokersChangedListener.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; public interface InvokersChangedListener { void onChange(); }
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/migration/ServiceDiscoveryMigrationInvoker.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/ServiceDiscoveryMigrationInvoker.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.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.client.migration.model.MigrationRule; import org.apache.dubbo.registry.integration.RegistryProtocol; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.Cluster; import org.apache.dubbo.rpc.cluster.ClusterInvoker; import java.util.concurrent.CountDownLatch; public class ServiceDiscoveryMigrationInvoker<T> extends MigrationInvoker<T> { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ServiceDiscoveryMigrationInvoker.class); public ServiceDiscoveryMigrationInvoker( RegistryProtocol registryProtocol, Cluster cluster, Registry registry, Class<T> type, URL url, URL consumerUrl) { super(registryProtocol, cluster, registry, type, url, consumerUrl); } @Override public boolean isServiceDiscovery() { return true; } @Override public boolean migrateToForceInterfaceInvoker(MigrationRule newRule) { CountDownLatch latch = new CountDownLatch(0); refreshServiceDiscoveryInvoker(latch); setCurrentAvailableInvoker(getServiceDiscoveryInvoker()); return true; } @Override public void migrateToApplicationFirstInvoker(MigrationRule newRule) { CountDownLatch latch = new CountDownLatch(0); refreshServiceDiscoveryInvoker(latch); setCurrentAvailableInvoker(getServiceDiscoveryInvoker()); } @Override public Result invoke(Invocation invocation) throws RpcException { ClusterInvoker<T> invoker = getServiceDiscoveryInvoker(); if (invoker == null) { throw new IllegalStateException( "There's no service discovery invoker available for service " + invocation.getServiceName()); } return invoker.invoke(invocation); } }
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/migration/PreMigratingConditionChecker.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/PreMigratingConditionChecker.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.extension.SPI; @SPI public interface PreMigratingConditionChecker { boolean checkCondition(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/client/migration/model/SubMigrationRule.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/SubMigrationRule.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 java.util.Map; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_DELAY_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_FORCE_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_PROPORTION_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_STEP_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_THRESHOLD_KEY; public class SubMigrationRule { private String serviceKey; private MigrationStep step; private Float threshold; private Integer proportion; private Integer delay; private Boolean force; public static SubMigrationRule parseFromMap(Map<String, Object> map) { SubMigrationRule interfaceMigrationRule = new SubMigrationRule(); interfaceMigrationRule.setServiceKey((String) map.get("serviceKey")); Object step = map.get(MIGRATION_RULE_STEP_KEY); if (step != null) { interfaceMigrationRule.setStep(MigrationStep.valueOf(step.toString())); } Object threshold = map.get(MIGRATION_RULE_THRESHOLD_KEY); if (threshold != null) { interfaceMigrationRule.setThreshold(Float.valueOf(threshold.toString())); } Object proportion = map.get(MIGRATION_RULE_PROPORTION_KEY); if (proportion != null) { interfaceMigrationRule.setProportion(Integer.valueOf(proportion.toString())); } Object delay = map.get(MIGRATION_RULE_DELAY_KEY); if (delay != null) { interfaceMigrationRule.setDelay(Integer.valueOf(delay.toString())); } Object force = map.get(MIGRATION_RULE_FORCE_KEY); if (force != null) { interfaceMigrationRule.setForce(Boolean.valueOf(force.toString())); } return interfaceMigrationRule; } public SubMigrationRule() {} public SubMigrationRule(String serviceKey, MigrationStep step, Float threshold, Integer proportion) { this.serviceKey = serviceKey; this.step = step; this.threshold = threshold; this.proportion = proportion; } public String getServiceKey() { return serviceKey; } public void setServiceKey(String serviceKey) { this.serviceKey = serviceKey; } public MigrationStep getStep() { return step; } public void setStep(MigrationStep step) { this.step = step; } public Float getThreshold() { return threshold; } public void setThreshold(Float threshold) { this.threshold = threshold; } public Integer getProportion() { return proportion; } public void setProportion(Integer proportion) { this.proportion = proportion; } public Integer getDelay() { return delay; } public void setDelay(Integer delay) { this.delay = delay; } public Boolean getForce() { return force; } public void setForce(Boolean force) { this.force = force; } }
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/migration/model/MigrationRule.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/MigrationRule.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.common.config.ConfigurationUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metadata.ServiceNameMapping; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.constructor.SafeConstructor; import static org.apache.dubbo.registry.Constants.MIGRATION_DELAY_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_FORCE_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_PROMOTION_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_APPLICATIONS_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_DELAY_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_FORCE_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_INTERFACES_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_PROPORTION_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_STEP_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_THRESHOLD_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_STEP_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_THRESHOLD_KEY; import static org.apache.dubbo.registry.client.migration.MigrationRuleHandler.DUBBO_SERVICEDISCOVERY_MIGRATION; /** * # key = demo-consumer.migration * # group = DUBBO_SERVICEDISCOVERY_MIGRATION * # content * key: demo-consumer * step: APPLICATION_FIRST * threshold: 1.0 * proportion: 60 * delay: 60 * force: false * interfaces: * - serviceKey: DemoService:1.0.0 * threshold: 0.5 * proportion: 30 * delay: 30 * force: true * step: APPLICATION_FIRST * - serviceKey: GreetingService:1.0.0 * step: FORCE_APPLICATION * applications: * - serviceKey: TestApplication * threshold: 0.3 * proportion: 20 * delay: 10 * force: false * step: FORCE_INTERFACE */ public class MigrationRule { private String key; private MigrationStep step; private Float threshold; private Integer proportion; private Integer delay; private Boolean force; private List<SubMigrationRule> interfaces; private List<SubMigrationRule> applications; private transient Map<String, SubMigrationRule> interfaceRules; private transient Map<String, SubMigrationRule> applicationRules; public static MigrationRule getInitRule() { return new MigrationRule(); } @SuppressWarnings("unchecked") private static MigrationRule parseFromMap(Map<String, Object> map) { MigrationRule migrationRule = new MigrationRule(); migrationRule.setKey((String) map.get(MIGRATION_RULE_KEY)); Object step = map.get(MIGRATION_RULE_STEP_KEY); if (step != null) { migrationRule.setStep(MigrationStep.valueOf(step.toString())); } Object threshold = map.get(MIGRATION_RULE_THRESHOLD_KEY); if (threshold != null) { migrationRule.setThreshold(Float.valueOf(threshold.toString())); } Object proportion = map.get(MIGRATION_RULE_PROPORTION_KEY); if (proportion != null) { migrationRule.setProportion(Integer.valueOf(proportion.toString())); } Object delay = map.get(MIGRATION_RULE_DELAY_KEY); if (delay != null) { migrationRule.setDelay(Integer.valueOf(delay.toString())); } Object force = map.get(MIGRATION_RULE_FORCE_KEY); if (force != null) { migrationRule.setForce(Boolean.valueOf(force.toString())); } Object interfaces = map.get(MIGRATION_RULE_INTERFACES_KEY); if (interfaces != null && List.class.isAssignableFrom(interfaces.getClass())) { migrationRule.setInterfaces(((List<Map<String, Object>>) interfaces) .stream().map(SubMigrationRule::parseFromMap).collect(Collectors.toList())); } Object applications = map.get(MIGRATION_RULE_APPLICATIONS_KEY); if (applications != null && List.class.isAssignableFrom(applications.getClass())) { migrationRule.setApplications(((List<Map<String, Object>>) applications) .stream().map(SubMigrationRule::parseFromMap).collect(Collectors.toList())); } return migrationRule; } public MigrationRule() {} public MigrationRule(String key) { this.key = key; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public MigrationStep getStep(URL consumerURL) { MigrationStep value = getValue(consumerURL, SubMigrationRule::getStep); if (value != null) { return value; } /** * FIXME, it's really hard to follow setting default values here. */ if (step == null) { // initial step : APPLICATION_FIRST return Enum.valueOf( MigrationStep.class, consumerURL.getParameter( MIGRATION_STEP_KEY, getDefaultStep(consumerURL, MigrationStep.APPLICATION_FIRST.name()))); } return step; } private String getDefaultStep(URL consumerURL, String defaultStep) { String globalDefaultStep = ConfigurationUtils.getCachedDynamicProperty( consumerURL.getScopeModel(), DUBBO_SERVICEDISCOVERY_MIGRATION, null); if (StringUtils.isEmpty(globalDefaultStep)) { // check 'dubbo.application.service-discovery.migration' for compatibility globalDefaultStep = ConfigurationUtils.getCachedDynamicProperty( consumerURL.getScopeModel(), "dubbo.application.service-discovery.migration", defaultStep); } return globalDefaultStep; } public MigrationStep getStep() { return step; } public float getThreshold(URL consumerURL) { Float value = getValue(consumerURL, SubMigrationRule::getThreshold); if (value != null) { return value; } return threshold == null ? consumerURL.getParameter(MIGRATION_THRESHOLD_KEY, -1f) : threshold; } public Float getThreshold() { return threshold; } public void setThreshold(Float threshold) { this.threshold = threshold; } public Integer getProportion() { return proportion; } public int getProportion(URL consumerURL) { Integer value = getValue(consumerURL, SubMigrationRule::getProportion); if (value != null) { return value; } return proportion == null ? consumerURL.getParameter(MIGRATION_PROMOTION_KEY, 100) : proportion; } public void setProportion(Integer proportion) { this.proportion = proportion; } public Integer getDelay() { return delay; } public int getDelay(URL consumerURL) { Integer value = getValue(consumerURL, SubMigrationRule::getDelay); if (value != null) { return value; } return delay == null ? consumerURL.getParameter(MIGRATION_DELAY_KEY, 0) : delay; } public void setDelay(Integer delay) { this.delay = delay; } public void setStep(MigrationStep step) { this.step = step; } public Boolean getForce() { return force; } public boolean getForce(URL consumerURL) { Boolean value = getValue(consumerURL, SubMigrationRule::getForce); if (value != null) { return value; } return force == null ? consumerURL.getParameter(MIGRATION_FORCE_KEY, false) : force; } public <T> T getValue(URL consumerURL, Function<SubMigrationRule, T> function) { if (interfaceRules != null) { SubMigrationRule rule = interfaceRules.get(consumerURL.getDisplayServiceKey()); if (rule != null) { T value = function.apply(rule); if (value != null) { return value; } } } if (applications != null) { ServiceNameMapping serviceNameMapping = ServiceNameMapping.getDefaultExtension(consumerURL.getScopeModel()); Set<String> services = serviceNameMapping.getRemoteMapping(consumerURL); if (CollectionUtils.isNotEmpty(services)) { for (String service : services) { SubMigrationRule rule = applicationRules.get(service); if (rule != null) { T value = function.apply(rule); if (value != null) { return value; } } } } } return null; } public void setForce(Boolean force) { this.force = force; } public List<SubMigrationRule> getInterfaces() { return interfaces; } public void setInterfaces(List<SubMigrationRule> interfaces) { this.interfaces = interfaces; if (interfaces != null) { this.interfaceRules = new HashMap<>(); interfaces.forEach(rule -> { interfaceRules.put(rule.getServiceKey(), rule); }); } } public List<SubMigrationRule> getApplications() { return applications; } public void setApplications(List<SubMigrationRule> applications) { this.applications = applications; if (applications != null) { this.applicationRules = new HashMap<>(); applications.forEach(rule -> { applicationRules.put(rule.getServiceKey(), rule); }); } } public static MigrationRule parse(String rawRule) { Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); Map<String, Object> map = yaml.load(rawRule); return parseFromMap(map); } public static String toYaml(MigrationRule rule) { Constructor constructor = new Constructor(MigrationRule.class, new LoaderOptions()); Yaml yaml = new Yaml(constructor); return yaml.dump(rule); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MigrationRule that = (MigrationRule) o; return Objects.equals(key, that.key) && step == that.step && Objects.equals(threshold, that.threshold) && Objects.equals(proportion, that.proportion) && Objects.equals(delay, that.delay) && Objects.equals(force, that.force) && Objects.equals(interfaces, that.interfaces) && Objects.equals(applications, that.applications) && Objects.equals(interfaceRules, that.interfaceRules) && Objects.equals(applicationRules, that.applicationRules); } @Override public int hashCode() { return Objects.hash( key, step, threshold, proportion, delay, force, interfaces, applications, interfaceRules, applicationRules); } }
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/migration/model/MigrationStep.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/MigrationStep.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; public enum MigrationStep { FORCE_INTERFACE, APPLICATION_FIRST, FORCE_APPLICATION }
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/status/RegistryStatusChecker.java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/status/RegistryStatusChecker.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.status; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.support.RegistryManager; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collection; /** * RegistryStatusChecker * */ @Activate public class RegistryStatusChecker implements StatusChecker { private ApplicationModel applicationModel; public RegistryStatusChecker(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } @Override public Status check() { RegistryManager registryManager = applicationModel.getBeanFactory().getBean(RegistryManager.class); Collection<Registry> registries = registryManager.getRegistries(); if (registries.isEmpty()) { return new Status(Status.Level.UNKNOWN); } Status.Level level = Status.Level.OK; StringBuilder buf = new StringBuilder(); for (Registry registry : registries) { if (buf.length() > 0) { buf.append(','); } buf.append(registry.getUrl().getAddress()); if (!registry.isAvailable()) { level = Status.Level.ERROR; buf.append("(disconnected)"); } else { buf.append("(connected)"); } } return new Status(level, buf.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-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactoryTest.java
dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactoryTest.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.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.rpc.model.ApplicationModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Test for NacosServiceDiscoveryFactory */ class NacosServiceDiscoveryFactoryTest { private NacosServiceDiscoveryFactory nacosServiceDiscoveryFactory; @BeforeEach public void setup() { nacosServiceDiscoveryFactory = new NacosServiceDiscoveryFactory(); ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel .getApplicationConfigManager() .setApplication(new ApplicationConfig("NacosServiceDiscoveryFactoryTest")); nacosServiceDiscoveryFactory.setApplicationModel(applicationModel); } @Test void testGetServiceDiscoveryWithCache() { URL url = URL.valueOf("dubbo://test:8080?nacos.check=false"); ServiceDiscovery discovery = nacosServiceDiscoveryFactory.createDiscovery(url); Assertions.assertTrue(discovery instanceof NacosServiceDiscovery); } @AfterEach public void tearDown() { 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-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosConnectionsManagerTest.java
dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosConnectionsManagerTest.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.nacos; import org.apache.dubbo.common.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.DOWN; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP; import static org.mockito.ArgumentMatchers.any; public class NacosConnectionsManagerTest { @Test public void testGet() { NamingService namingService = Mockito.mock(NamingService.class); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(namingService); Assertions.assertEquals(namingService, nacosConnectionManager.getNamingService()); Assertions.assertEquals(namingService, nacosConnectionManager.getNamingService()); Assertions.assertEquals(namingService, nacosConnectionManager.getNamingService()); } @Test public void testCreate() { List<NamingService> namingServiceList = new ArrayList<>(); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(URL.valueOf(""), false, 0, 0) { @Override protected NamingService createNamingService() { NamingService namingService = Mockito.mock(NamingService.class); namingServiceList.add(namingService); return namingService; } }; Assertions.assertEquals(1, namingServiceList.size()); Assertions.assertEquals(namingServiceList.get(0), nacosConnectionManager.getNamingService()); Assertions.assertEquals(namingServiceList.get(0), nacosConnectionManager.getNamingService()); Assertions.assertEquals(namingServiceList.get(0), nacosConnectionManager.getNamingService()); Assertions.assertEquals(namingServiceList.get(0), nacosConnectionManager.getNamingService()); LinkedList<NamingService> copy = new LinkedList<>(namingServiceList); Assertions.assertFalse(copy.contains(nacosConnectionManager.getNamingService(new HashSet<>(copy)))); copy = new LinkedList<>(namingServiceList); Assertions.assertFalse(copy.contains(nacosConnectionManager.getNamingService(new HashSet<>(copy)))); copy = new LinkedList<>(namingServiceList); Assertions.assertFalse(copy.contains(nacosConnectionManager.getNamingService(new HashSet<>(copy)))); copy = new LinkedList<>(namingServiceList); Assertions.assertFalse(copy.contains(nacosConnectionManager.getNamingService(new HashSet<>(copy)))); Assertions.assertEquals(5, namingServiceList.size()); copy = new LinkedList<>(namingServiceList); for (int i = 0; i < 1000; i++) { if (copy.size() == 0) { break; } copy.remove(nacosConnectionManager.getNamingService()); } Assertions.assertTrue(copy.isEmpty()); nacosConnectionManager.shutdownAll(); copy = new LinkedList<>(namingServiceList); Assertions.assertFalse(copy.contains(nacosConnectionManager.getNamingService())); } @Test void testRetryCreate() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { AtomicInteger atomicInteger = new AtomicInteger(0); NamingService mock = new MockNamingService() { @Override public String getServerStatus() { return atomicInteger.incrementAndGet() > 10 ? UP : DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848"); Assertions.assertThrows(IllegalStateException.class, () -> new NacosConnectionManager(url, true, 5, 10)); try { new NacosConnectionManager(url, true, 5, 10); } catch (Throwable t) { Assertions.fail(t); } } } @Test void testNoCheck() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { NamingService mock = new MockNamingService() { @Override public String getServerStatus() { return DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848"); try { new NacosConnectionManager(url, false, 5, 10); } catch (Throwable t) { Assertions.fail(t); } } } @Test void testDisable() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { NamingService mock = new MockNamingService() { @Override public String getServerStatus() { return DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") .addParameter("nacos.retry", 5) .addParameter("nacos.retry-wait", 10) .addParameter("nacos.check", "false"); try { new NacosConnectionManager(url, false, 5, 10); } catch (Throwable t) { Assertions.fail(t); } } } @Test void testRequest() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { AtomicInteger atomicInteger = new AtomicInteger(0); NamingService mock = new MockNamingService() { @Override public List<Instance> getAllInstances(String serviceName, boolean subscribe) throws NacosException { if (atomicInteger.incrementAndGet() > 10) { return null; } else { throw new NacosException(); } } @Override public String getServerStatus() { return UP; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") .addParameter("nacos.retry", 5) .addParameter("nacos.retry-wait", 10); Assertions.assertThrows(IllegalStateException.class, () -> new NacosConnectionManager(url, true, 5, 10)); try { new NacosConnectionManager(url, true, 5, 10); } catch (Throwable t) { Assertions.fail(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-nacos/src/test/java/org/apache/dubbo/registry/nacos/MockNamingService.java
dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/MockNamingService.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.nacos; import java.util.List; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.api.naming.selector.NamingSelector; import com.alibaba.nacos.api.selector.AbstractSelector; public class MockNamingService implements NamingService { @Override public void registerInstance(String serviceName, String ip, int port) {} @Override public void registerInstance(String serviceName, String groupName, String ip, int port) {} @Override public void registerInstance(String serviceName, String ip, int port, String clusterName) {} @Override public void registerInstance(String serviceName, String groupName, String ip, int port, String clusterName) {} @Override public void registerInstance(String serviceName, Instance instance) {} @Override public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException {} @Override public void batchRegisterInstance(String serviceName, String groupName, List<Instance> instances) {} @Override public void deregisterInstance(String serviceName, String ip, int port) {} @Override public void deregisterInstance(String serviceName, String groupName, String ip, int port) {} @Override public void deregisterInstance(String serviceName, String ip, int port, String clusterName) {} @Override public void deregisterInstance(String serviceName, String groupName, String ip, int port, String clusterName) {} @Override public void deregisterInstance(String serviceName, Instance instance) {} @Override public void deregisterInstance(String serviceName, String groupName, Instance instance) {} @Override public void batchDeregisterInstance(String s, String s1, List<Instance> list) throws NacosException {} @Override public List<Instance> getAllInstances(String serviceName) { return null; } @Override public List<Instance> getAllInstances(String serviceName, String groupName) throws NacosException { return null; } @Override public List<Instance> getAllInstances(String serviceName, boolean subscribe) throws NacosException { return null; } @Override public List<Instance> getAllInstances(String serviceName, String groupName, boolean subscribe) throws NacosException { return null; } @Override public List<Instance> getAllInstances(String serviceName, List<String> clusters) { return null; } @Override public List<Instance> getAllInstances(String serviceName, String groupName, List<String> clusters) { return null; } @Override public List<Instance> getAllInstances(String serviceName, List<String> clusters, boolean subscribe) { return null; } @Override public List<Instance> getAllInstances( String serviceName, String groupName, List<String> clusters, boolean subscribe) { return null; } @Override public List<Instance> selectInstances(String serviceName, boolean healthy) { return null; } @Override public List<Instance> selectInstances(String serviceName, String groupName, boolean healthy) { return null; } @Override public List<Instance> selectInstances(String serviceName, boolean healthy, boolean subscribe) { return null; } @Override public List<Instance> selectInstances(String serviceName, String groupName, boolean healthy, boolean subscribe) { return null; } @Override public List<Instance> selectInstances(String serviceName, List<String> clusters, boolean healthy) { return null; } @Override public List<Instance> selectInstances( String serviceName, String groupName, List<String> clusters, boolean healthy) { return null; } @Override public List<Instance> selectInstances( String serviceName, List<String> clusters, boolean healthy, boolean subscribe) { return null; } @Override public List<Instance> selectInstances( String serviceName, String groupName, List<String> clusters, boolean healthy, boolean subscribe) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName, String groupName) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName, boolean subscribe) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName, String groupName, boolean subscribe) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName, List<String> clusters) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName, String groupName, List<String> clusters) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName, List<String> clusters, boolean subscribe) { return null; } @Override public Instance selectOneHealthyInstance( String serviceName, String groupName, List<String> clusters, boolean subscribe) { return null; } @Override public void subscribe(String serviceName, EventListener listener) throws NacosException {} @Override public void subscribe(String serviceName, String groupName, EventListener listener) throws NacosException {} @Override public void subscribe(String serviceName, List<String> clusters, EventListener listener) throws NacosException {} @Override public void subscribe(String serviceName, String groupName, List<String> clusters, EventListener listener) throws NacosException {} @Override public void unsubscribe(String serviceName, EventListener listener) {} @Override public void unsubscribe(String serviceName, String groupName, EventListener listener) {} @Override public void unsubscribe(String serviceName, List<String> clusters, EventListener listener) {} @Override public void unsubscribe(String serviceName, String groupName, List<String> clusters, EventListener listener) {} @Override public ListView<String> getServicesOfServer(int pageNo, int pageSize) { return null; } @Override public ListView<String> getServicesOfServer(int pageNo, int pageSize, String groupName) { return null; } @Override public ListView<String> getServicesOfServer(int pageNo, int pageSize, AbstractSelector selector) { return null; } @Override public ListView<String> getServicesOfServer(int pageNo, int pageSize, String groupName, AbstractSelector selector) { return null; } @Override public List<ServiceInfo> getSubscribeServices() { return null; } @Override public String getServerStatus() { return null; } @Override public void shutDown() {} @Override public void subscribe(String s, NamingSelector namingSelector, EventListener eventListener) throws NacosException {} @Override public void subscribe(String s, String s1, NamingSelector namingSelector, EventListener eventListener) throws NacosException {} @Override public void unsubscribe(String s, NamingSelector namingSelector, EventListener eventListener) throws NacosException {} @Override public void unsubscribe(String s, String s1, NamingSelector namingSelector, EventListener eventListener) throws NacosException {} }
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-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryTest.java
dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryTest.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.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.registry.NotifyListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.client.naming.NacosNamingService; 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 static org.apache.dubbo.common.constants.CommonConstants.GROUP_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.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Test for NacosRegistry */ class NacosRegistryTest { private static final String serviceInterface = "org.apache.dubbo.registry.nacos.NacosService"; private final URL serviceUrl = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface=" + serviceInterface + "&notify=false&methods=test1,test2&category=providers&version=1.0.0&group=default&side=provider"); private NacosRegistryFactory nacosRegistryFactory; private NacosRegistry nacosRegistry; private URL registryUrl; @BeforeEach public void setUp() throws Exception { int nacosServerPort = NetUtils.getAvailablePort(); this.registryUrl = URL.valueOf("nacos://localhost:" + nacosServerPort + "?nacos.check=false"); this.nacosRegistryFactory = new NacosRegistryFactory(); this.nacosRegistry = (NacosRegistry) nacosRegistryFactory.createRegistry(registryUrl); } @AfterEach public void tearDown() throws Exception {} @Test void testRegister() { NamingService namingService = mock(NacosNamingService.class); try { String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; String category = this.serviceUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); URL newUrl = this.serviceUrl.addParameter(CATEGORY_KEY, category); newUrl = newUrl.addParameter(PROTOCOL_KEY, this.serviceUrl.getProtocol()); newUrl = newUrl.addParameter(PATH_KEY, this.serviceUrl.getPath()); String ip = newUrl.getHost(); int port = newUrl.getPort(); Instance instance = new Instance(); instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newUrl.getParameters())); doNothing().when(namingService).registerInstance(serviceName, Constants.DEFAULT_GROUP, instance); } catch (NacosException e) { // ignore } NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); Set<URL> registered; for (int i = 0; i < 2; i++) { nacosRegistry.register(serviceUrl); registered = nacosRegistry.getRegistered(); assertThat(registered.contains(serviceUrl), is(true)); } registered = nacosRegistry.getRegistered(); Assertions.assertEquals(1, registered.size()); } @Test void testUnRegister() { NamingService namingService = mock(NacosNamingService.class); try { String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; String category = this.serviceUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); URL newUrl = this.serviceUrl.addParameter(CATEGORY_KEY, category); newUrl = newUrl.addParameter(PROTOCOL_KEY, this.serviceUrl.getProtocol()); newUrl = newUrl.addParameter(PATH_KEY, this.serviceUrl.getPath()); String ip = newUrl.getHost(); int port = newUrl.getPort(); Instance instance = new Instance(); instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newUrl.getParameters())); doNothing().when(namingService).registerInstance(serviceName, Constants.DEFAULT_GROUP, instance); doNothing().when(namingService).deregisterInstance(serviceName, Constants.DEFAULT_GROUP, ip, port); } catch (NacosException e) { // ignore } NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); nacosRegistry.register(serviceUrl); Set<URL> registered = nacosRegistry.getRegistered(); assertThat(registered.contains(serviceUrl), is(true)); Assertions.assertEquals(1, registered.size()); nacosRegistry.unregister(serviceUrl); Assertions.assertFalse(registered.contains(serviceUrl)); Assertions.assertEquals(0, registered.size()); } @Test void testSubscribe() { NamingService namingService = mock(NacosNamingService.class); try { String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; String category = this.serviceUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); URL newUrl = this.serviceUrl.addParameter(CATEGORY_KEY, category); newUrl = newUrl.addParameter(PROTOCOL_KEY, this.serviceUrl.getProtocol()); newUrl = newUrl.addParameter(PATH_KEY, this.serviceUrl.getPath()); String ip = newUrl.getHost(); int port = newUrl.getPort(); Instance instance = new Instance(); instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newUrl.getParameters())); List<Instance> instances = new ArrayList<>(); instances.add(instance); when(namingService.getAllInstances( serviceName, this.registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))) .thenReturn(instances); } catch (NacosException e) { // ignore } NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); NotifyListener listener = mock(NotifyListener.class); nacosRegistry.subscribe(serviceUrl, listener); Map<URL, Set<NotifyListener>> subscribed = nacosRegistry.getSubscribed(); Assertions.assertEquals(1, subscribed.size()); Assertions.assertEquals(1, subscribed.get(serviceUrl).size()); } @Test void testUnSubscribe() { NamingService namingService = mock(NacosNamingService.class); try { String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; String category = this.serviceUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); URL newUrl = this.serviceUrl.addParameter(CATEGORY_KEY, category); newUrl = newUrl.addParameter(PROTOCOL_KEY, this.serviceUrl.getProtocol()); newUrl = newUrl.addParameter(PATH_KEY, this.serviceUrl.getPath()); String ip = newUrl.getHost(); int port = newUrl.getPort(); Instance instance = new Instance(); instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newUrl.getParameters())); List<Instance> instances = new ArrayList<>(); instances.add(instance); when(namingService.getAllInstances( serviceName, this.registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))) .thenReturn(instances); } catch (NacosException e) { // ignore } NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); NotifyListener listener = mock(NotifyListener.class); nacosRegistry.subscribe(serviceUrl, listener); Map<URL, Set<NotifyListener>> subscribed = nacosRegistry.getSubscribed(); Assertions.assertEquals(1, subscribed.size()); Assertions.assertEquals(1, subscribed.get(serviceUrl).size()); nacosRegistry.unsubscribe(serviceUrl, listener); subscribed = nacosRegistry.getSubscribed(); Assertions.assertEquals(1, subscribed.size()); Assertions.assertEquals(0, subscribed.get(serviceUrl).size()); } @Test void testIsConformRules() { NamingService namingService = mock(NacosNamingService.class); URL serviceUrlWithoutCategory = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface=" + serviceInterface + "&notify=false&methods=test1,test2&version=1.0.0&group=default"); try { String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; String category = this.serviceUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); URL newUrl = this.serviceUrl.addParameter(CATEGORY_KEY, category); newUrl = newUrl.addParameter(PROTOCOL_KEY, this.serviceUrl.getProtocol()); newUrl = newUrl.addParameter(PATH_KEY, this.serviceUrl.getPath()); String ip = newUrl.getHost(); int port = newUrl.getPort(); Instance instance = new Instance(); instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newUrl.getParameters())); List<Instance> instances = new ArrayList<>(); instances.add(instance); when(namingService.getAllInstances( serviceName, this.registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))) .thenReturn(instances); String serviceNameWithoutVersion = "providers:org.apache.dubbo.registry.nacos.NacosService:default"; String serviceName1 = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; List<String> serviceNames = new ArrayList<>(); serviceNames.add(serviceNameWithoutVersion); serviceNames.add(serviceName1); ListView<String> result = new ListView<>(); result.setData(serviceNames); when(namingService.getServicesOfServer( 1, Integer.MAX_VALUE, registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))) .thenReturn(result); } catch (NacosException e) { // ignore } NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); Set<URL> registered; nacosRegistry.register(this.serviceUrl); nacosRegistry.register(serviceUrlWithoutCategory); registered = nacosRegistry.getRegistered(); Assertions.assertTrue(registered.contains(serviceUrl)); Assertions.assertTrue(registered.contains(serviceUrlWithoutCategory)); Assertions.assertEquals(2, registered.size()); URL serviceUrlWithWildcard = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface=org.apache.dubbo.registry.nacos.NacosService" + "&notify=false&methods=test1,test2&category=providers&version=*&group=default"); URL serviceUrlWithOutWildcard = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface=org.apache.dubbo.registry.nacos.NacosService" + "&notify=false&methods=test1,test2&category=providers&version=1.0.0&group=default"); NotifyListener listener = mock(NotifyListener.class); nacosRegistry.subscribe(serviceUrlWithWildcard, listener); nacosRegistry.subscribe(serviceUrlWithOutWildcard, listener); Map<URL, Set<NotifyListener>> subscribed = nacosRegistry.getSubscribed(); Assertions.assertEquals(2, registered.size()); Assertions.assertEquals(1, subscribed.get(serviceUrlWithOutWildcard).size()); Assertions.assertEquals(2, registered.size()); Assertions.assertEquals(1, subscribed.get(serviceUrlWithWildcard).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-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryFactoryTest.java
dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryFactoryTest.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.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Test for NacosRegistryFactory */ class NacosRegistryFactoryTest { private NacosRegistryFactory nacosRegistryFactory; @BeforeEach public void setup() { nacosRegistryFactory = new NacosRegistryFactory(); } @AfterEach public void teardown() {} @Test void testCreateRegistryCacheKey() { URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":8080?nacos.check=false"); String registryCacheKey1 = nacosRegistryFactory.createRegistryCacheKey(url); String registryCacheKey2 = nacosRegistryFactory.createRegistryCacheKey(url); Assertions.assertEquals(registryCacheKey1, registryCacheKey2); } @Test void testCreateRegistryCacheKeyWithNamespace() { URL url = URL.valueOf( "dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":8080?namespace=test&nacos.check=false"); String registryCacheKey1 = nacosRegistryFactory.createRegistryCacheKey(url); String registryCacheKey2 = nacosRegistryFactory.createRegistryCacheKey(url); Assertions.assertEquals(registryCacheKey1, registryCacheKey2); } }
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-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryTest.java
dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryTest.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.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import org.junit.jupiter.api.AfterAll; 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 org.mockito.internal.util.collections.Sets; import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Test for NacosServiceDiscovery */ class NacosServiceDiscoveryTest { private static final String SERVICE_NAME = "NACOS_SERVICE"; private static final String LOCALHOST = "127.0.0.1"; protected URL registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false"); private NacosServiceDiscovery nacosServiceDiscovery; private NacosNamingServiceWrapper namingServiceWrapper; protected String group = DEFAULT_GROUP; private DefaultServiceInstance createServiceInstance(String serviceName, String host, int port) { return new DefaultServiceInstance( serviceName, host, port, ScopeModelUtil.getApplicationModel(registryUrl.getScopeModel())); } public static class NacosServiceDiscoveryGroupTest1 extends NacosServiceDiscoveryTest { public NacosServiceDiscoveryGroupTest1() { super(); group = "test-group1"; registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false") .addParameter("group", group); } } public static class NacosServiceDiscoveryGroupTest2 extends NacosServiceDiscoveryTest { public NacosServiceDiscoveryGroupTest2() { super(); group = "test-group2"; registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false") .addParameter("group", group); } } public static class NacosServiceDiscoveryGroupTest3 extends NacosServiceDiscoveryTest { public NacosServiceDiscoveryGroupTest3() { super(); group = DEFAULT_GROUP; registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false") .addParameter("group", "test-group3"); } @BeforeAll public static void beforeClass() { System.setProperty("dubbo.nacos-service-discovery.use-default-group", "true"); } @AfterAll public static void afterClass() { System.clearProperty("dubbo.nacos-service-discovery.use-default-group"); } } @BeforeEach public void init() throws Exception { ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig(SERVICE_NAME)); registryUrl.setScopeModel(applicationModel); // this.nacosServiceDiscovery = new NacosServiceDiscovery(SERVICE_NAME, registryUrl); this.nacosServiceDiscovery = new NacosServiceDiscovery(applicationModel, registryUrl); Field namingService = nacosServiceDiscovery.getClass().getDeclaredField("namingService"); namingService.setAccessible(true); namingServiceWrapper = mock(NacosNamingServiceWrapper.class); namingService.set(nacosServiceDiscovery, namingServiceWrapper); } @AfterEach public void destroy() throws Exception { ApplicationModel.defaultModel().destroy(); nacosServiceDiscovery.destroy(); } @Test void testDoRegister() throws NacosException { DefaultServiceInstance serviceInstance = createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); // register nacosServiceDiscovery.doRegister(serviceInstance); ArgumentCaptor<Instance> instanceCaptor = ArgumentCaptor.forClass(Instance.class); verify(namingServiceWrapper, times(1)).registerInstance(any(), eq(group), instanceCaptor.capture()); Instance capture = instanceCaptor.getValue(); assertEquals(SERVICE_NAME, capture.getServiceName()); assertEquals(LOCALHOST, capture.getIp()); assertEquals(serviceInstance.getPort(), capture.getPort()); } @Test void testDoUnRegister() throws NacosException { // register DefaultServiceInstance serviceInstance = createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); // register nacosServiceDiscovery.doRegister(serviceInstance); // unRegister nacosServiceDiscovery.doUnregister(serviceInstance); ArgumentCaptor<Instance> instanceCaptor = ArgumentCaptor.forClass(Instance.class); verify(namingServiceWrapper, times(1)).deregisterInstance(any(), eq(group), instanceCaptor.capture()); Instance capture = instanceCaptor.getValue(); assertEquals(SERVICE_NAME, capture.getServiceName()); assertEquals(LOCALHOST, capture.getIp()); assertEquals(serviceInstance.getPort(), capture.getPort()); } @Test void testGetServices() throws NacosException { DefaultServiceInstance serviceInstance = createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); // register nacosServiceDiscovery.doRegister(serviceInstance); ArgumentCaptor<Instance> instance = ArgumentCaptor.forClass(Instance.class); verify(namingServiceWrapper, times(1)).registerInstance(any(), eq(group), instance.capture()); String serviceNameWithoutVersion = "providers:org.apache.dubbo.registry.nacos.NacosService:default"; String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; List<String> serviceNames = new ArrayList<>(); serviceNames.add(serviceNameWithoutVersion); serviceNames.add(serviceName); ListView<String> result = new ListView<>(); result.setData(serviceNames); when(namingServiceWrapper.getServicesOfServer(anyInt(), anyInt(), eq(group))) .thenReturn(result); Set<String> services = nacosServiceDiscovery.getServices(); assertEquals(2, services.size()); } @Test void testAddServiceInstancesChangedListener() { List<ServiceInstance> serviceInstances = new LinkedList<>(); // Add Listener nacosServiceDiscovery.addServiceInstancesChangedListener( new ServiceInstancesChangedListener(Sets.newSet(SERVICE_NAME), nacosServiceDiscovery) { @Override public void onEvent(ServiceInstancesChangedEvent event) { serviceInstances.addAll(event.getServiceInstances()); } }); nacosServiceDiscovery.register(); nacosServiceDiscovery.update(); nacosServiceDiscovery.unregister(); assertTrue(serviceInstances.isEmpty()); } }
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-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapperTest.java
dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapperTest.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.nacos; import org.apache.dubbo.common.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.pojo.Instance; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class NacosNamingServiceWrapperTest { @Test void testSubscribe() throws NacosException { NacosConnectionManager connectionManager = Mockito.mock(NacosConnectionManager.class); NamingService namingService = Mockito.mock(NamingService.class); Mockito.when(connectionManager.getNamingService()).thenReturn(namingService); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(connectionManager, 0, 0); EventListener eventListener = Mockito.mock(EventListener.class); nacosNamingServiceWrapper.subscribe("service_name", "test", eventListener); Mockito.verify(namingService, Mockito.times(1)).subscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.subscribe("service_name", "test", eventListener); Mockito.verify(namingService, Mockito.times(2)).subscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.unsubscribe("service_name", "test", eventListener); Mockito.verify(namingService, Mockito.times(1)).unsubscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.unsubscribe("service_name", "test", eventListener); Mockito.verify(namingService, Mockito.times(1)).unsubscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.unsubscribe("service_name", "mock", eventListener); Mockito.verify(namingService, Mockito.times(0)).unsubscribe("service_name", "mock", eventListener); } @Test void testSubscribeMultiManager() throws NacosException { NacosConnectionManager connectionManager = Mockito.mock(NacosConnectionManager.class); NamingService namingService1 = Mockito.mock(NamingService.class); NamingService namingService2 = Mockito.mock(NamingService.class); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(connectionManager, 0, 0); EventListener eventListener = Mockito.mock(EventListener.class); Mockito.when(connectionManager.getNamingService()).thenReturn(namingService1); nacosNamingServiceWrapper.subscribe("service_name", "test", eventListener); Mockito.verify(namingService1, Mockito.times(1)).subscribe("service_name", "test", eventListener); Mockito.when(connectionManager.getNamingService()).thenReturn(namingService2); nacosNamingServiceWrapper.subscribe("service_name", "test", eventListener); Mockito.verify(namingService1, Mockito.times(2)).subscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.unsubscribe("service_name", "test", eventListener); Mockito.verify(namingService1, Mockito.times(1)).unsubscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.unsubscribe("service_name", "test", eventListener); Mockito.verify(namingService1, Mockito.times(1)).unsubscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.unsubscribe("service_name", "mock", eventListener); Mockito.verify(namingService1, Mockito.times(0)).unsubscribe("service_name", "mock", eventListener); Mockito.verify(namingService2, Mockito.times(0)).unsubscribe("service_name", "mock", eventListener); } @Test void testRegisterNacos2_0_x() throws NacosException { List<NamingService> namingServiceList = new LinkedList<>(); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(URL.valueOf(""), false, 0, 0) { @Override protected NamingService createNamingService() { NamingService namingService = Mockito.mock(NamingService.class); namingServiceList.add(namingService); return namingService; } }; Assertions.assertEquals(1, namingServiceList.size()); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(nacosConnectionManager, false, 0, 0); Instance instance1 = new Instance(); instance1.setIp("ip1"); instance1.setPort(1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Instance instance2 = new Instance(); instance2.setIp("ip2"); instance2.setPort(2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(2, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(1), Mockito.times(1)).registerInstance("service_name", "test", instance2); Instance instance3 = new Instance(); instance3.setIp("ip3"); instance3.setPort(3); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(3, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(1), Mockito.times(1)).registerInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(2), Mockito.times(1)).registerInstance("service_name", "test", instance3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .deregisterInstance("service_name", "test", instance1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(1), Mockito.times(1)) .deregisterInstance("service_name", "test", instance2); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); Mockito.verify(namingServiceList.get(2), Mockito.times(1)) .deregisterInstance("service_name", "test", instance3); } @Test void testRegisterNacos2_1_xClient2_0_xServer() throws NacosException { List<NamingService> namingServiceList = new LinkedList<>(); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(URL.valueOf(""), false, 0, 0) { @Override protected NamingService createNamingService() { NamingService namingService = Mockito.mock(NamingService.class); try { Mockito.doThrow(new NacosException()) .when(namingService) .batchRegisterInstance(Mockito.anyString(), Mockito.anyString(), Mockito.any(List.class)); } catch (NacosException e) { throw new RuntimeException(e); } namingServiceList.add(namingService); return namingService; } }; Assertions.assertEquals(1, namingServiceList.size()); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(nacosConnectionManager, true, 0, 0); Instance instance1 = new Instance(); instance1.setIp("ip1"); instance1.setPort(1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Instance instance2 = new Instance(); instance2.setIp("ip2"); instance2.setPort(2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(2, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(1), Mockito.times(1)).registerInstance("service_name", "test", instance2); Instance instance3 = new Instance(); instance3.setIp("ip3"); instance3.setPort(3); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(3, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(1), Mockito.times(1)).registerInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(2), Mockito.times(1)).registerInstance("service_name", "test", instance3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .deregisterInstance("service_name", "test", instance1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(1), Mockito.times(1)) .deregisterInstance("service_name", "test", instance2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .registerInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); Mockito.verify(namingServiceList.get(1), Mockito.times(2)) .registerInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .deregisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); Mockito.verify(namingServiceList.get(1), Mockito.times(2)) .deregisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); Mockito.verify(namingServiceList.get(2), Mockito.times(1)) .deregisterInstance("service_name", "test", instance3); } @Test void testRegisterNacos2_1_xClient2_1_xServer() throws NacosException { List<NamingService> namingServiceList = new LinkedList<>(); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(URL.valueOf(""), false, 0, 0) { @Override protected NamingService createNamingService() { NamingService namingService = Mockito.mock(NamingService.class); namingServiceList.add(namingService); return namingService; } }; Assertions.assertEquals(1, namingServiceList.size()); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(nacosConnectionManager, true, 0, 0); Instance instance1 = new Instance(); instance1.setIp("ip1"); instance1.setPort(1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Instance instance2 = new Instance(); instance2.setIp("ip2"); instance2.setPort(2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); Instance instance3 = new Instance(); instance3.setIp("ip3"); instance3.setPort(3); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .deregisterInstance("service_name", "test", instance3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .deregisterInstance("service_name", "test", instance3); // rerun nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(2)).registerInstance("service_name", "test", instance1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(3)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(4)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .deregisterInstance("service_name", "test", instance3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .deregisterInstance("service_name", "test", instance3); } @Test void testUnregister() throws NacosException { List<NamingService> namingServiceList = new LinkedList<>(); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(URL.valueOf(""), false, 0, 0) { @Override protected NamingService createNamingService() { NamingService namingService = Mockito.mock(NamingService.class); namingServiceList.add(namingService); return namingService; } }; Assertions.assertEquals(1, namingServiceList.size()); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(nacosConnectionManager, true, 0, 0); Instance instance1 = new Instance(); instance1.setIp("ip1"); instance1.setPort(1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Instance instance2 = new Instance(); instance2.setIp("ip2"); instance2.setPort(2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); Instance instance3 = new Instance(); instance3.setIp("ip3"); instance3.setPort(3); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip1", 2); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip1", 1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 2); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 2); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip3", 3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip3", 3); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .deregisterInstance("service_name", "test", instance3); // rerun nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(2)).registerInstance("service_name", "test", instance1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip1", 1); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 2); Mockito.verify(namingServiceList.get(0), Mockito.times(3)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip1", 1); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 2); Mockito.verify(namingServiceList.get(0), Mockito.times(4)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip3", 3); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .deregisterInstance("service_name", "test", instance3); } @Test void testConcurrency() throws NacosException, InterruptedException { NacosConnectionManager connectionManager = Mockito.mock(NacosConnectionManager.class); CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch stopLatch = new CountDownLatch(1); NamingService namingService = Mockito.mock(NamingService.class); Mockito.when(connectionManager.getNamingService()).thenReturn(namingService); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(connectionManager, false, 0, 0); Instance instance = new Instance(); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance); NacosNamingServiceWrapper.InstancesInfo instancesInfo = nacosNamingServiceWrapper .getRegisterStatus() .get(new NacosNamingServiceWrapper.InstanceId("service_name", "test")); Assertions.assertEquals(1, instancesInfo.getInstances().size()); nacosNamingServiceWrapper .getRegisterStatus() .put( new NacosNamingServiceWrapper.InstanceId("service_name", "test"), new NacosNamingServiceWrapper.InstancesInfo() { private final NacosNamingServiceWrapper.InstancesInfo delegate = instancesInfo; @Override public void lock() { delegate.lock(); } @Override public void unlock() { delegate.unlock(); } @Override public List<NacosNamingServiceWrapper.InstanceInfo> getInstances() { try { if (startLatch.getCount() > 0) { Thread.sleep(1000); startLatch.countDown(); Thread.sleep(1000); } } catch (InterruptedException e) { throw new RuntimeException(e); } return delegate.getInstances(); } @Override public boolean isBatchRegistered() { return delegate.isBatchRegistered(); } @Override public void setBatchRegistered(boolean batchRegistered) {
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-nacos/src/test/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtilsTest.java
dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtilsTest.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.nacos.util; import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.nacos.MockNamingService; import org.apache.dubbo.registry.nacos.NacosNamingServiceWrapper; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.DOWN; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; /** * Test for NacosNamingServiceUtils */ class NacosNamingServiceUtilsTest { private static MetadataReport metadataReport = Mockito.mock(MetadataReport.class); @Test void testToInstance() { ServiceInstance serviceInstance = mock(ServiceInstance.class); Instance instance = NacosNamingServiceUtils.toInstance(serviceInstance); Assertions.assertNotNull(instance); } @Test void testToServiceInstance() { URL registryUrl = URL.valueOf("nacos://127.0.0.1:8080/test"); Instance instance = new Instance(); instance.setServiceName("serviceName"); instance.setIp("1.1.1.1"); instance.setPort(800); instance.setWeight(2); instance.setHealthy(Boolean.TRUE); instance.setEnabled(Boolean.TRUE); Map<String, String> map = new HashMap<String, String>(); map.put("netType", "external"); map.put("version", "2.0"); instance.setMetadata(map); ServiceInstance serviceInstance = NacosNamingServiceUtils.toServiceInstance(registryUrl, instance); Assertions.assertNotNull(serviceInstance); Assertions.assertEquals(serviceInstance.isEnabled(), Boolean.TRUE); Assertions.assertEquals(serviceInstance.getServiceName(), "serviceName"); } @Test void testCreateNamingService() { URL url = URL.valueOf("nacos://127.0.0.1:8080/test?backup=127.0.0.1&nacos.check=false"); NacosNamingServiceWrapper namingService = NacosNamingServiceUtils.createNamingService(url); Assertions.assertNotNull(namingService); } @Test void testRetryCreate() throws NacosException { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { AtomicInteger atomicInteger = new AtomicInteger(0); NamingService mock = new MockNamingService() { @Override public String getServerStatus() { return atomicInteger.incrementAndGet() > 10 ? UP : DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") .addParameter("nacos.retry", 5) .addParameter("nacos.retry-wait", 10); Assertions.assertThrows( IllegalStateException.class, () -> NacosNamingServiceUtils.createNamingService(url)); try { NacosNamingServiceUtils.createNamingService(url); } catch (Throwable t) { Assertions.fail(t); } } } @Test void testDisable() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { NamingService mock = new MockNamingService() { @Override public String getServerStatus() { return DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") .addParameter("nacos.retry", 5) .addParameter("nacos.retry-wait", 10) .addParameter("nacos.check", "false"); try { NacosNamingServiceUtils.createNamingService(url); } catch (Throwable t) { Assertions.fail(t); } } } @Test void testRequest() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { AtomicInteger atomicInteger = new AtomicInteger(0); NamingService mock = new MockNamingService() { @Override public List<Instance> getAllInstances(String serviceName, boolean subscribe) throws NacosException { if (atomicInteger.incrementAndGet() > 10) { return null; } else { throw new NacosException(); } } @Override public String getServerStatus() { return UP; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") .addParameter("nacos.retry", 5) .addParameter("nacos.retry-wait", 10); Assertions.assertThrows( IllegalStateException.class, () -> NacosNamingServiceUtils.createNamingService(url)); try { NacosNamingServiceUtils.createNamingService(url); } catch (Throwable t) { Assertions.fail(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-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.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.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; 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.url.component.DubboServiceAddressURL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; 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.registry.RegistryNotifier; import org.apache.dubbo.registry.support.FailbackRegistry; import org.apache.dubbo.registry.support.SkipFailbackWrapperException; import org.apache.dubbo.rpc.RpcException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; 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.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.listener.Event; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_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.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION; 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.CONSUMERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; 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.NACOS_REGISTER_COMPATIBLE; import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_CONSUMER_URL_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; import static org.apache.dubbo.registry.Constants.ADMIN_PROTOCOL; import static org.apache.dubbo.registry.nacos.NacosServiceName.NAME_SEPARATOR; import static org.apache.dubbo.registry.nacos.NacosServiceName.valueOf; /** * Nacos {@link Registry} * * @see #SERVICE_NAME_SEPARATOR * @see #PAGINATION_SIZE * @see #LOOKUP_INTERVAL * @since 2.6.5 */ public class NacosRegistry extends FailbackRegistry { /** * All supported categories */ private static final List<String> ALL_SUPPORTED_CATEGORIES = Arrays.asList(PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, CONFIGURATORS_CATEGORY); private static final int CATEGORY_INDEX = 0; private static final int SERVICE_INTERFACE_INDEX = 1; private static final int SERVICE_VERSION_INDEX = 2; private static final int SERVICE_GROUP_INDEX = 3; private static final String WILDCARD = "*"; private static final String UP = "UP"; /** * The separator for service name Change a constant to be configurable, it's designed for Windows file name that is * compatible with old Nacos binary release(< 0.6.1) */ private static final String SERVICE_NAME_SEPARATOR = SystemPropertyConfigUtils.getSystemProperty( CommonConstants.ThirdPartyProperty.NACOS_SERVICE_NAME_SEPARATOR, ":"); /** * The pagination size of query for Nacos service names(only for Dubbo-OPS) */ private static final int PAGINATION_SIZE = Integer.getInteger("nacos.service.names.pagination.size", 100); /** * The interval in second of lookup Nacos service names(only for Dubbo-OPS) */ private static final long LOOKUP_INTERVAL = Long.getLong("nacos.service.names.lookup.interval", 30); private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosRegistry.class); private final NacosNamingServiceWrapper namingService; /** * {@link ScheduledExecutorService} lookup Nacos service names(only for Dubbo-OPS) */ private volatile ScheduledExecutorService scheduledExecutorService; private final Map<URL, Map<NotifyListener, NacosAggregateListener>> originToAggregateListener = new ConcurrentHashMap<>(); private final ConcurrentHashMap< URL, ConcurrentHashMap<NacosAggregateListener, ConcurrentHashMap<String, EventListener>>> nacosListeners = new ConcurrentHashMap<>(); private final boolean supportLegacyServiceName; public NacosRegistry(URL url, NacosNamingServiceWrapper namingService) { super(url); this.namingService = namingService; this.supportLegacyServiceName = url.getParameter("nacos.subscribe.legacy-name", false); } @Override public boolean isAvailable() { return UP.equals(namingService.getServerStatus()); } @Override public List<URL> lookup(final URL url) { if (url == null) { throw new IllegalArgumentException("lookup url == null"); } try { List<URL> urls = new LinkedList<>(); Set<String> serviceNames = getServiceNames(url, null); for (String serviceName : serviceNames) { List<Instance> instances = namingService.getAllInstancesWithoutSubscription( serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP)); urls.addAll(buildURLs(url, instances)); } return urls; } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Exception cause) { throw new RpcException( "Failed to lookup " + url + " from nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); } } @Override public void doRegister(URL url) { try { if (PROVIDER_SIDE.equals(url.getSide()) || getUrl().getParameter(REGISTER_CONSUMER_URL_KEY, false)) { Instance instance = createInstance(url); Set<String> serviceNames = new HashSet<>(); // by default servicename is "org.apache.dubbo.xxService:1.0.0:" String serviceName = getServiceName(url, false); serviceNames.add(serviceName); // in https://github.com/apache/dubbo/issues/14075 if (getUrl().getParameter(NACOS_REGISTER_COMPATIBLE, false)) { // servicename is "org.apache.dubbo.xxService:1.0.0" String compatibleServiceName = getServiceName(url, true); serviceNames.add(compatibleServiceName); } /** * namingService.registerInstance with * {@link org.apache.dubbo.registry.support.AbstractRegistry#registryUrl} * default {@link DEFAULT_GROUP} * * in https://github.com/apache/dubbo/issues/5978 */ for (String service : serviceNames) { namingService.registerInstance(service, getUrl().getGroup(Constants.DEFAULT_GROUP), instance); } } else { logger.info("Please set 'dubbo.registry.parameters.register-consumer-url=true' to turn on consumer " + "url registration."); } } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Exception cause) { throw new RpcException( "Failed to register " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); } } @Override public void doUnregister(final URL url) { try { Instance instance = createInstance(url); Set<String> serviceNames = new HashSet<>(); // by default servicename is "org.apache.dubbo.xxService:1.0.0:" String serviceName = getServiceName(url, false); serviceNames.add(serviceName); // in https://github.com/apache/dubbo/issues/14075 if (getUrl().getParameter(NACOS_REGISTER_COMPATIBLE, false)) { // servicename is "org.apache.dubbo.xxService:1.0.0" String serviceName1 = getServiceName(url, true); serviceNames.add(serviceName1); } for (String service : serviceNames) { namingService.deregisterInstance( service, getUrl().getGroup(Constants.DEFAULT_GROUP), instance.getIp(), instance.getPort()); } } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Exception cause) { throw new RpcException( "Failed to unregister " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); } } @Override public void doSubscribe(final URL url, final NotifyListener listener) { NacosAggregateListener nacosAggregateListener = new NacosAggregateListener(listener); originToAggregateListener .computeIfAbsent(url, k -> new ConcurrentHashMap<>()) .put(listener, nacosAggregateListener); Set<String> serviceNames = getServiceNames(url, nacosAggregateListener); doSubscribe(url, nacosAggregateListener, serviceNames); } private void doSubscribe(final URL url, final NacosAggregateListener listener, final Set<String> serviceNames) { try { if (isServiceNamesWithCompatibleMode(url)) { /** * Get all instances with serviceNames to avoid instance overwrite and but with empty instance mentioned * in https://github.com/apache/dubbo/issues/5885 and https://github.com/apache/dubbo/issues/5899 * * namingService.getAllInstances with * {@link org.apache.dubbo.registry.support.AbstractRegistry#registryUrl} * default {@link DEFAULT_GROUP} * * in https://github.com/apache/dubbo/issues/5978 */ for (String serviceName : serviceNames) { List<Instance> instances = namingService.getAllInstancesWithoutSubscription( serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP)); notifySubscriber(url, serviceName, listener, instances); } for (String serviceName : serviceNames) { subscribeEventListener(serviceName, url, listener); } } else { for (String serviceName : serviceNames) { List<Instance> instances = new LinkedList<>(); instances.addAll(namingService.getAllInstancesWithoutSubscription( serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP))); String serviceInterface = serviceName; String[] segments = serviceName.split(SERVICE_NAME_SEPARATOR, -1); if (segments.length == 4) { serviceInterface = segments[SERVICE_INTERFACE_INDEX]; } URL subscriberURL = url.setPath(serviceInterface) .addParameters( INTERFACE_KEY, serviceInterface, CommonConstants.APPLICATION_KEY, url.getApplication(), CHECK_KEY, String.valueOf(false)); notifySubscriber(subscriberURL, serviceName, listener, instances); subscribeEventListener(serviceName, subscriberURL, listener); } } } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Throwable cause) { throw new RpcException( "Failed to subscribe " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); } } /** * Since 2.7.6 the legacy service name will be added to serviceNames to fix bug with * https://github.com/apache/dubbo/issues/5442 * * @param url * @return */ private boolean isServiceNamesWithCompatibleMode(final URL url) { return !isAdminProtocol(url) && createServiceName(url).isConcrete(); } @Override public void doUnsubscribe(URL url, NotifyListener listener) { if (isAdminProtocol(url)) { shutdownServiceNamesLookup(); } else { Map<NotifyListener, NacosAggregateListener> listenerMap = originToAggregateListener.get(url); if (listenerMap == null) { logger.warn( REGISTRY_NACOS_EXCEPTION, "", "", String.format( "No aggregate listener found for url %s, " + "this service might have already been unsubscribed.", url)); return; } NacosAggregateListener nacosAggregateListener = listenerMap.remove(listener); if (nacosAggregateListener != null) { Set<String> serviceNames = nacosAggregateListener.getServiceNames(); try { doUnsubscribe(url, nacosAggregateListener, serviceNames); } catch (NacosException e) { logger.error( REGISTRY_NACOS_EXCEPTION, "", "", "Failed to unsubscribe " + url + " to nacos " + getUrl() + ", cause: " + e.getMessage(), e); } } if (listenerMap.isEmpty()) { originToAggregateListener.remove(url); } } } private void doUnsubscribe( final URL url, final NacosAggregateListener nacosAggregateListener, final Set<String> serviceNames) throws NacosException { for (String serviceName : serviceNames) { unsubscribeEventListener(serviceName, url, nacosAggregateListener); } } private void shutdownServiceNamesLookup() { if (scheduledExecutorService != null) { scheduledExecutorService.shutdown(); } } /** * Get the service names from the specified {@link URL url} * * @param url {@link URL} * @param listener {@link NotifyListener} * @return non-null */ private Set<String> getServiceNames(URL url, NacosAggregateListener listener) { if (isAdminProtocol(url)) { scheduleServiceNamesLookup(url, listener); return getServiceNamesForOps(url); } else { return getServiceNames0(url); } } private Set<String> getServiceNames0(URL url) { NacosServiceName serviceName = createServiceName(url); final Set<String> serviceNames; if (serviceName.isConcrete()) { // is the concrete service name serviceNames = new LinkedHashSet<>(); serviceNames.add(serviceName.toString()); if (supportLegacyServiceName) { // Add the legacy service name since 2.7.6 String legacySubscribedServiceName = getLegacySubscribedServiceName(url); if (!serviceName.toString().equals(legacySubscribedServiceName)) { // avoid duplicated service names serviceNames.add(legacySubscribedServiceName); } } } else { serviceNames = filterServiceNames(serviceName); } return serviceNames; } private Set<String> filterServiceNames(NacosServiceName serviceName) { try { Set<String> serviceNames = new LinkedHashSet<>(); serviceNames.addAll( namingService .getServicesOfServer(1, Integer.MAX_VALUE, getUrl().getGroup(Constants.DEFAULT_GROUP)) .getData() .stream() .filter(this::isConformRules) .map(NacosServiceName::new) .filter(serviceName::isCompatible) .map(NacosServiceName::toString) .collect(Collectors.toList())); return serviceNames; } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Throwable cause) { throw new RpcException( "Failed to filter serviceName from nacos, url: " + getUrl() + ", serviceName: " + serviceName + ", cause: " + cause.getMessage(), cause); } } /** * Verify whether it is a dubbo service * * @param serviceName * @return * @since 2.7.12 */ private boolean isConformRules(String serviceName) { return serviceName.split(NAME_SEPARATOR, -1).length == 4; } /** * Get the legacy subscribed service name for compatible with Dubbo 2.7.3 and below * * @param url {@link URL} * @return non-null * @since 2.7.6 */ private String getLegacySubscribedServiceName(URL url) { StringBuilder serviceNameBuilder = new StringBuilder(DEFAULT_CATEGORY); appendIfPresent(serviceNameBuilder, url, INTERFACE_KEY); appendIfPresent(serviceNameBuilder, url, VERSION_KEY); appendIfPresent(serviceNameBuilder, url, GROUP_KEY); return serviceNameBuilder.toString(); } private void appendIfPresent(StringBuilder target, URL url, String parameterName) { String parameterValue = url.getParameter(parameterName); if (!StringUtils.isBlank(parameterValue)) { target.append(SERVICE_NAME_SEPARATOR).append(parameterValue); } } private boolean isAdminProtocol(URL url) { return ADMIN_PROTOCOL.equals(url.getProtocol()); } private void scheduleServiceNamesLookup(final URL url, final NacosAggregateListener listener) { if (scheduledExecutorService == null) { scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.scheduleAtFixedRate( () -> { Set<String> serviceNames = getAllServiceNames(); filterData(serviceNames, serviceName -> { boolean accepted = false; for (String category : ALL_SUPPORTED_CATEGORIES) { String prefix = category + SERVICE_NAME_SEPARATOR; if (serviceName != null && serviceName.startsWith(prefix)) { accepted = true; break; } } return accepted; }); doSubscribe(url, listener, serviceNames); }, LOOKUP_INTERVAL, LOOKUP_INTERVAL, TimeUnit.SECONDS); } } /** * Get the service names for Dubbo OPS * * @param url {@link URL} * @return non-null */ private Set<String> getServiceNamesForOps(URL url) { Set<String> serviceNames = getAllServiceNames(); filterServiceNames(serviceNames, url); return serviceNames; } private Set<String> getAllServiceNames() { try { final Set<String> serviceNames = new LinkedHashSet<>(); int pageIndex = 1; ListView<String> listView = namingService.getServicesOfServer( pageIndex, PAGINATION_SIZE, getUrl().getGroup(Constants.DEFAULT_GROUP)); // First page data List<String> firstPageData = listView.getData(); // Append first page into list serviceNames.addAll(firstPageData); // the total count int count = listView.getCount(); // the number of pages int pageNumbers = count / PAGINATION_SIZE; int remainder = count % PAGINATION_SIZE; // remain if (remainder > 0) { pageNumbers += 1; } // If more than 1 page while (pageIndex < pageNumbers) { listView = namingService.getServicesOfServer( ++pageIndex, PAGINATION_SIZE, getUrl().getGroup(Constants.DEFAULT_GROUP)); serviceNames.addAll(listView.getData()); } return serviceNames; } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Throwable cause) { throw new RpcException( "Failed to get all serviceName from nacos, url: " + getUrl() + ", cause: " + cause.getMessage(), cause); } } private void filterServiceNames(Set<String> serviceNames, URL url) { final List<String> categories = getCategories(url); final String targetServiceInterface = url.getServiceInterface(); final String targetVersion = url.getVersion(""); final String targetGroup = url.getGroup(""); filterData(serviceNames, serviceName -> { // split service name to segments // (required) segments[0] = category // (required) segments[1] = serviceInterface // (optional) segments[2] = version // (optional) segments[3] = group String[] segments = serviceName.split(SERVICE_NAME_SEPARATOR, -1); int length = segments.length; if (length != 4) { // must present 4 segments return false; } String category = segments[CATEGORY_INDEX]; if (!categories.contains(category)) { // no match category return false; } String serviceInterface = segments[SERVICE_INTERFACE_INDEX]; // no match service interface if (!WILDCARD.equals(targetServiceInterface) && !StringUtils.isEquals(targetServiceInterface, serviceInterface)) { return false; } // no match service version String version = segments[SERVICE_VERSION_INDEX]; if (!WILDCARD.equals(targetVersion) && !StringUtils.isEquals(targetVersion, version)) { return false; } String group = segments[SERVICE_GROUP_INDEX]; return group == null || WILDCARD.equals(targetGroup) || StringUtils.isEquals(targetGroup, group); }); } private <T> void filterData(Collection<T> collection, NacosDataFilter<T> filter) { // remove if not accept collection.removeIf(data -> !filter.accept(data)); } @Deprecated private List<String> doGetServiceNames(URL url) { List<String> categories = getCategories(url); List<String> serviceNames = new ArrayList<>(categories.size()); for (String category : categories) { final String serviceName = getServiceName(url, category); serviceNames.add(serviceName); } return serviceNames; } @Override public void destroy() { super.destroy(); try { this.namingService.shutdown(); } catch (NacosException e) { logger.warn(REGISTRY_NACOS_EXCEPTION, "", "", "Unable to shutdown nacos naming service", e); } this.nacosListeners.clear(); } private List<URL> toUrlWithEmpty(URL consumerURL, Collection<Instance> instances) { consumerURL = removeParamsFromConsumer(consumerURL); List<URL> urls = buildURLs(consumerURL, instances); // Nacos does not support configurators and routers from registry, so all notifications are of providers type. if (urls.size() == 0 && !getUrl().getParameter(ENABLE_EMPTY_PROTECTION_KEY, DEFAULT_ENABLE_EMPTY_PROTECTION)) { logger.warn( REGISTRY_NACOS_EXCEPTION, "", "", "Received empty url address list and empty protection is " + "disabled, will clear current available addresses"); URL empty = URLBuilder.from(consumerURL) .setProtocol(EMPTY_PROTOCOL) .addParameter(CATEGORY_KEY, DEFAULT_CATEGORY) .build(); urls.add(empty); } return urls; } private List<URL> buildURLs(URL consumerURL, Collection<Instance> instances) { List<URL> urls = new LinkedList<>(); if (instances != null && !instances.isEmpty()) { for (Instance instance : instances) { URL url = buildURL(consumerURL, instance); if (UrlUtils.isMatch(consumerURL, url)) { urls.add(url); } } } return urls; } private void subscribeEventListener(String serviceName, final URL url, final NacosAggregateListener listener) throws NacosException { ConcurrentHashMap<NacosAggregateListener, ConcurrentHashMap<String, EventListener>> listeners = ConcurrentHashMapUtils.computeIfAbsent(nacosListeners, url, k -> new ConcurrentHashMap<>()); ConcurrentHashMap<String, EventListener> eventListeners = ConcurrentHashMapUtils.computeIfAbsent(listeners, listener, k -> new ConcurrentHashMap<>()); EventListener eventListener = ConcurrentHashMapUtils.computeIfAbsent( eventListeners, serviceName, k -> new RegistryChildListenerImpl(serviceName, url, listener)); namingService.subscribe(serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP), eventListener); } private void unsubscribeEventListener(String serviceName, final URL url, final NacosAggregateListener listener) throws NacosException { ConcurrentHashMap<NacosAggregateListener, ConcurrentHashMap<String, EventListener>> listenerToServiceEvent = nacosListeners.get(url); if (listenerToServiceEvent == null) { return; } Map<String, EventListener> serviceToEventMap = listenerToServiceEvent.get(listener); if (serviceToEventMap == null) { return; } EventListener eventListener = serviceToEventMap.remove(serviceName); if (eventListener == null) { return; } namingService.unsubscribe( serviceName, getUrl().getParameter(GROUP_KEY, Constants.DEFAULT_GROUP), eventListener); if (serviceToEventMap.isEmpty()) { listenerToServiceEvent.remove(listener); } if (listenerToServiceEvent.isEmpty()) { nacosListeners.remove(url); } } /** * Notify the Enabled {@link Instance instances} to subscriber. * * @param url {@link URL} * @param listener {@link NotifyListener} * @param instances all {@link Instance instances} */ private void notifySubscriber( URL url, String serviceName, NacosAggregateListener listener, Collection<Instance> instances) { List<Instance> enabledInstances = new LinkedList<>(instances); if (enabledInstances.size() > 0) { // Instances filterEnabledInstances(enabledInstances); } List<URL> aggregatedUrls = toUrlWithEmpty(url, listener.saveAndAggregateAllInstances(serviceName, enabledInstances)); NacosRegistry.this.notify(url, listener.getNotifyListener(), aggregatedUrls); } /** * Get the categories from {@link URL} * * @param url {@link URL} * @return non-null array */ private List<String> getCategories(URL url) { return ANY_VALUE.equals(url.getServiceInterface()) ? ALL_SUPPORTED_CATEGORIES : Arrays.asList(DEFAULT_CATEGORY); } private URL buildURL(URL consumerURL, Instance instance) { Map<String, String> metadata = instance.getMetadata(); String protocol = metadata.get(PROTOCOL_KEY); String path = metadata.get(PATH_KEY); URL url = new ServiceConfigURL(protocol, instance.getIp(), instance.getPort(), path, instance.getMetadata()); return new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), consumerURL, null); } private Instance createInstance(URL url) { // Append default category if absent String category = url.getCategory(DEFAULT_CATEGORY); URL newURL = url.addParameter(CATEGORY_KEY, category); newURL = newURL.addParameter(PROTOCOL_KEY, url.getProtocol()); newURL = newURL.addParameter(PATH_KEY, url.getPath()); String ip = url.getHost(); int port = url.getPort(); Instance instance = new Instance(); instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newURL.getParameters())); return instance; } private NacosServiceName createServiceName(URL url) { return valueOf(url); } private String getServiceName(URL url, boolean needCompatible) { if (needCompatible) { return getCompatibleServiceName(url, url.getCategory(DEFAULT_CATEGORY)); } return getServiceName(url, url.getCategory(DEFAULT_CATEGORY)); } private String getServiceName(URL url, String category) { return category + SERVICE_NAME_SEPARATOR + url.getColonSeparatedKey(); } private String getCompatibleServiceName(URL url, String category) { return category + SERVICE_NAME_SEPARATOR + url.getCompatibleColonSeparatedKey(); } private void filterEnabledInstances(Collection<Instance> instances) { filterData(instances, Instance::isEnabled); } /** * A filter for Nacos data * * @since 2.6.5 */
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-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.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.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.client.AbstractServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceDiscovery; import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_NAMESPACE_KEY; public class NacosServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory { @Override protected String createRegistryCacheKey(URL url) { String namespace = url.getParameter(CONFIG_NAMESPACE_KEY); url = URL.valueOf(url.toServiceStringWithoutResolving()); if (StringUtils.isNotEmpty(namespace)) { url = url.addParameter(CONFIG_NAMESPACE_KEY, namespace); } return url.toFullString(); } @Override protected ServiceDiscovery createDiscovery(URL registryURL) { return new NacosServiceDiscovery(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-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.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.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.function.ThrowableFunction; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.registry.client.AbstractServiceDiscovery; 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.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.listener.Event; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION; import static org.apache.dubbo.common.function.ThrowableConsumer.execute; 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.nacos.util.NacosNamingServiceUtils.createNamingService; import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.getGroup; import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.toInstance; import static org.apache.dubbo.rpc.RpcException.REGISTRY_EXCEPTION; /** * Nacos {@link ServiceDiscovery} implementation * * @see ServiceDiscovery * @since 2.7.5 */ public class NacosServiceDiscovery extends AbstractServiceDiscovery { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final String group; private final NacosNamingServiceWrapper namingService; private static final String NACOS_SD_USE_DEFAULT_GROUP_KEY = "dubbo.nacos-service-discovery.use-default-group"; private final ConcurrentHashMap<String, NacosEventListener> eventListeners = new ConcurrentHashMap<>(); public NacosServiceDiscovery(ApplicationModel applicationModel, URL registryURL) { super(applicationModel, registryURL); this.namingService = createNamingService(registryURL); // backward compatibility for 3.0.x this.group = Boolean.parseBoolean( ConfigurationUtils.getProperty(applicationModel, NACOS_SD_USE_DEFAULT_GROUP_KEY, "false")) ? DEFAULT_GROUP : getGroup(registryURL); } @Override public void doDestroy() throws Exception { this.namingService.shutdown(); this.eventListeners.clear(); } @Override public void doRegister(ServiceInstance serviceInstance) { execute(namingService, service -> { Instance instance = toInstance(serviceInstance); service.registerInstance(instance.getServiceName(), group, instance); }); } @Override public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException { execute(namingService, service -> { Instance instance = toInstance(serviceInstance); service.deregisterInstance(instance.getServiceName(), group, instance); }); } @Override protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) throws RuntimeException { if (EMPTY_REVISION.equals(getExportedServicesRevision(newServiceInstance)) || EMPTY_REVISION.equals( oldServiceInstance.getMetadata().get(EXPORTED_SERVICES_REVISION_PROPERTY_NAME))) { super.doUpdate(oldServiceInstance, newServiceInstance); return; } if (!Objects.equals(newServiceInstance.getHost(), oldServiceInstance.getHost()) || !Objects.equals(newServiceInstance.getPort(), oldServiceInstance.getPort())) { // Ignore if id changed. Should unregister first. super.doUpdate(oldServiceInstance, newServiceInstance); return; } Instance oldInstance = toInstance(oldServiceInstance); Instance newInstance = toInstance(newServiceInstance); try { this.serviceInstance = newServiceInstance; reportMetadata(newServiceInstance.getServiceMetadata()); execute(namingService, service -> { Instance instance = toInstance(serviceInstance); service.updateInstance(instance.getServiceName(), group, oldInstance, newInstance); }); } catch (Exception e) { throw new RpcException(REGISTRY_EXCEPTION, "Failed register instance " + newServiceInstance.toString(), e); } } @Override public Set<String> getServices() { return ThrowableFunction.execute(namingService, service -> { ListView<String> view = service.getServicesOfServer(0, Integer.MAX_VALUE, group); return new LinkedHashSet<>(view.getData()); }); } @Override public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException { return ThrowableFunction.execute( namingService, service -> service.selectInstances(serviceName, group, true).stream() .map((i) -> NacosNamingServiceUtils.toServiceInstance(registryURL, i)) .collect(Collectors.toList())); } @Override public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { // check if listener has already been added through another interface/service if (!instanceListeners.add(listener)) { return; } for (String serviceName : listener.getServiceNames()) { NacosEventListener nacosEventListener = eventListeners.get(serviceName); if (nacosEventListener != null) { nacosEventListener.addListener(listener); } else { try { nacosEventListener = new NacosEventListener(); nacosEventListener.addListener(listener); namingService.subscribe(serviceName, group, nacosEventListener); eventListeners.put(serviceName, nacosEventListener); } catch (NacosException e) { logger.error( REGISTRY_NACOS_EXCEPTION, "", "", "add nacos service instances changed listener fail ", e); } } } } @Override public void removeServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws IllegalArgumentException { if (!instanceListeners.remove(listener)) { return; } for (String serviceName : listener.getServiceNames()) { NacosEventListener nacosEventListener = eventListeners.get(serviceName); if (nacosEventListener != null) { nacosEventListener.removeListener(listener); if (nacosEventListener.isEmpty()) { eventListeners.remove(serviceName); try { namingService.unsubscribe(serviceName, group, nacosEventListener); } catch (NacosException e) { logger.error( REGISTRY_NACOS_EXCEPTION, "", "", "remove nacos service instances changed listener fail ", e); } } } } } public class NacosEventListener implements EventListener { private final Set<ServiceInstancesChangedListener> listeners = new ConcurrentHashSet<>(); @Override public void onEvent(Event e) { if (e instanceof NamingEvent) { for (ServiceInstancesChangedListener listener : listeners) { NamingEvent event = (NamingEvent) e; handleEvent(event, listener); } } } public void addListener(ServiceInstancesChangedListener listener) { listeners.add(listener); } public void removeListener(ServiceInstancesChangedListener listener) { listeners.remove(listener); } public boolean isEmpty() { return listeners.isEmpty(); } } @Override public URL getUrl() { return registryURL; } private void handleEvent(NamingEvent event, ServiceInstancesChangedListener listener) { String serviceName = event.getServiceName(); List<ServiceInstance> serviceInstances = event.getInstances().stream() .map((i) -> NacosNamingServiceUtils.toServiceInstance(registryURL, i)) .collect(Collectors.toList()); listener.onEvent(new ServiceInstancesChangedEvent(serviceName, serviceInstances)); } }
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-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.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.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.support.AbstractRegistryFactory; import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.createNamingService; /** * Nacos {@link RegistryFactory} * * @since 2.6.5 */ public class NacosRegistryFactory extends AbstractRegistryFactory { @Override protected String createRegistryCacheKey(URL url) { String namespace = url.getParameter(CONFIG_NAMESPACE_KEY); url = URL.valueOf(url.toServiceStringWithoutResolving()); if (StringUtils.isNotEmpty(namespace)) { url = url.addParameter(CONFIG_NAMESPACE_KEY, namespace); } return url.toFullString(); } @Override protected Registry createRegistry(URL url) { return new NacosRegistry(url, createNamingService(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-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosConnectionManager.java
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosConnectionManager.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.nacos; 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.StringUtils; import org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import static com.alibaba.nacos.api.PropertyKeyConst.PASSWORD; import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static com.alibaba.nacos.api.PropertyKeyConst.USERNAME; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP; import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_INTERRUPTED; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of; public class NacosConnectionManager { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosNamingServiceUtils.class); private final URL connectionURL; private final List<NamingService> namingServiceList = new LinkedList<>(); private final int retryTimes; private final int sleepMsBetweenRetries; private final boolean check; private final Properties nacosProperties; public NacosConnectionManager(URL connectionURL, boolean check, int retryTimes, int sleepMsBetweenRetries) { this.connectionURL = connectionURL; this.check = check; this.retryTimes = retryTimes; this.sleepMsBetweenRetries = sleepMsBetweenRetries; this.nacosProperties = buildNacosProperties(this.connectionURL); // create default one this.namingServiceList.add(createNamingService()); } /** * @deprecated for ut only */ @Deprecated protected NacosConnectionManager(NamingService namingService) { this.connectionURL = null; this.retryTimes = 0; this.sleepMsBetweenRetries = 0; this.check = false; this.nacosProperties = null; // create default one this.namingServiceList.add(namingService); } public synchronized NamingService getNamingService() { if (namingServiceList.isEmpty()) { this.namingServiceList.add(createNamingService()); } return namingServiceList.get(ThreadLocalRandom.current().nextInt(namingServiceList.size())); } public synchronized NamingService getNamingService(Set<NamingService> selected) { List<NamingService> copyOfNamingService = new LinkedList<>(namingServiceList); copyOfNamingService.removeAll(selected); if (copyOfNamingService.isEmpty()) { this.namingServiceList.add(createNamingService()); return getNamingService(selected); } return copyOfNamingService.get(ThreadLocalRandom.current().nextInt(copyOfNamingService.size())); } public synchronized void shutdownAll() { for (NamingService namingService : namingServiceList) { try { namingService.shutDown(); } catch (Exception e) { logger.warn(REGISTRY_NACOS_EXCEPTION, "", "", "Unable to shutdown nacos naming service", e); } } this.namingServiceList.clear(); } /** * Create an instance of {@link NamingService} from specified {@link URL connection url} * * @return {@link NamingService} */ protected NamingService createNamingService() { NamingService namingService = null; try { for (int i = 0; i < retryTimes + 1; i++) { namingService = NacosFactory.createNamingService(nacosProperties); String serverStatus = namingService.getServerStatus(); boolean namingServiceAvailable = testNamingService(namingService); if (!check || (UP.equals(serverStatus) && namingServiceAvailable)) { break; } else { logger.warn( LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, "", "", "Failed to connect to nacos naming server. " + "Server status: " + serverStatus + ". " + "Naming Service Available: " + namingServiceAvailable + ". " + (i < retryTimes ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " : "Exceed retry max times.") + "Try times: " + (i + 1)); } namingService.shutDown(); namingService = null; Thread.sleep(sleepMsBetweenRetries); } } catch (NacosException e) { if (logger.isErrorEnabled()) { logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getErrMsg(), e); } } catch (InterruptedException e) { logger.error(INTERNAL_INTERRUPTED, "", "", "Interrupted when creating nacos naming service client.", e); Thread.currentThread().interrupt(); throw new IllegalStateException(e); } if (namingService == null) { logger.error( REGISTRY_NACOS_EXCEPTION, "", "", "Failed to create nacos naming service client. Reason: server status check failed."); throw new IllegalStateException( "Failed to create nacos naming service client. Reason: server status check failed."); } return namingService; } private boolean testNamingService(NamingService namingService) { try { namingService.getAllInstances("Dubbo-Nacos-Test", false); return true; } catch (NacosException e) { return false; } } private Properties buildNacosProperties(URL url) { Properties properties = new Properties(); if (StringUtils.isEmpty(url.getHost())) { return properties; } setServerAddr(url, properties); setProperties(url, properties); return properties; } private void setServerAddr(URL url, Properties properties) { StringBuilder serverAddrBuilder = new StringBuilder(url.getHost()) // Host .append(':') .append(url.getPort()); // Port // Append backup parameter as other servers String backup = url.getParameter(BACKUP_KEY); if (StringUtils.isNotEmpty(backup)) { serverAddrBuilder.append(',').append(backup); } String serverAddr = serverAddrBuilder.toString(); properties.put(SERVER_ADDR, serverAddr); } private void setProperties(URL url, Properties properties) { putPropertyIfAbsent(url, properties, NACOS_NAMING_LOG_NAME, null); // @since 2.7.8 : Refactoring // Get the parameters from constants Map<String, String> parameters = url.getParameters(of(PropertyKeyConst.class)); // Put all parameters properties.putAll(parameters); if (StringUtils.isNotEmpty(url.getUsername())) { properties.put(USERNAME, url.getUsername()); } if (StringUtils.isNotEmpty(url.getPassword())) { properties.put(PASSWORD, url.getPassword()); } } private void putPropertyIfAbsent(URL url, Properties properties, String propertyName, String defaultValue) { String propertyValue = url.getParameter(propertyName); if (StringUtils.isNotEmpty(propertyValue)) { properties.setProperty(propertyName, propertyValue); } else { // when defaultValue is empty, we should not set empty value if (StringUtils.isNotEmpty(defaultValue)) { properties.setProperty(propertyName, defaultValue); } } } }
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-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosAggregateListener.java
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosAggregateListener.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.nacos; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.registry.NotifyListener; 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.atomic.AtomicBoolean; import java.util.regex.Pattern; import java.util.stream.Collectors; import com.alibaba.nacos.api.naming.pojo.Instance; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_SUB_LEGACY; public class NacosAggregateListener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosAggregateListener.class); private final NotifyListener notifyListener; private final Set<String> serviceNames = new ConcurrentHashSet<>(); private final Map<String, List<Instance>> serviceInstances = new ConcurrentHashMap<>(); private final AtomicBoolean warned = new AtomicBoolean(false); private static final Pattern SPLITTED_PATTERN = Pattern.compile(".*:.*:.*:.*"); public NacosAggregateListener(NotifyListener notifyListener) { this.notifyListener = notifyListener; } public List<Instance> saveAndAggregateAllInstances(String serviceName, List<Instance> instances) { serviceNames.add(serviceName); if (instances == null) { serviceInstances.remove(serviceName); } else { serviceInstances.put(serviceName, instances); } if (isLegacyName(serviceName) && instances != null && !instances.isEmpty() && warned.compareAndSet(false, true)) { logger.error( REGISTRY_NACOS_SUB_LEGACY, "", "", "Received not empty notification for legacy service name: " + serviceName + ", " + "instances: [" + instances.stream().map(Instance::getIp).collect(Collectors.joining(" ,")) + "]. " + "Please upgrade these Dubbo client(lower than 2.7.3) to the latest version. " + "Dubbo will remove the support for legacy service name in the future."); } return serviceInstances.values().stream().flatMap(List::stream).collect(Collectors.toList()); } private static boolean isLegacyName(String serviceName) { return !SPLITTED_PATTERN.matcher(serviceName).matches(); } public NotifyListener getNotifyListener() { return notifyListener; } public Set<String> getServiceNames() { return serviceNames; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NacosAggregateListener that = (NacosAggregateListener) o; return Objects.equals(notifyListener, that.notifyListener) && Objects.equals(serviceNames, that.serviceNames) && Objects.equals(serviceInstances, that.serviceInstances); } @Override public int hashCode() { return Objects.hash(notifyListener); } }
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-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceName.java
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceName.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.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import java.util.Arrays; import java.util.Objects; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.apache.dubbo.common.utils.StringUtils.isBlank; /** * The service name of Nacos * * @since 2.7.3 */ public class NacosServiceName { public static final String NAME_SEPARATOR = ":"; public static final String VALUE_SEPARATOR = ","; public static final String WILDCARD = "*"; public static final String DEFAULT_PARAM_VALUE = ""; private static final int CATEGORY_INDEX = 0; private static final int SERVICE_INTERFACE_INDEX = 1; private static final int SERVICE_VERSION_INDEX = 2; private static final int SERVICE_GROUP_INDEX = 3; private String category; private String serviceInterface; private String version; private String group; private String value; public NacosServiceName() {} public NacosServiceName(URL url) { serviceInterface = url.getParameter(INTERFACE_KEY); category = isConcrete(serviceInterface) ? DEFAULT_CATEGORY : url.getCategory(); version = url.getVersion(DEFAULT_PARAM_VALUE); group = url.getGroup(DEFAULT_PARAM_VALUE); value = toValue(); } public NacosServiceName(String value) { this.value = value; String[] segments = value.split(NAME_SEPARATOR, -1); this.category = segments[CATEGORY_INDEX]; this.serviceInterface = segments[SERVICE_INTERFACE_INDEX]; this.version = segments[SERVICE_VERSION_INDEX]; this.group = segments[SERVICE_GROUP_INDEX]; } /** * Build an instance of {@link NacosServiceName} * * @param url * @return */ public static NacosServiceName valueOf(URL url) { return new NacosServiceName(url); } /** * Is the concrete service name or not * * @return if concrete , return <code>true</code>, or <code>false</code> */ public boolean isConcrete() { return isConcrete(serviceInterface) && isConcrete(version) && isConcrete(group); } public boolean isCompatible(NacosServiceName concreteServiceName) { if (!concreteServiceName.isConcrete()) { // The argument must be the concrete NacosServiceName return false; } // Not match comparison if (!StringUtils.isEquals(this.category, concreteServiceName.category) && !matchRange(this.category, concreteServiceName.category)) { return false; } if (!StringUtils.isEquals(this.serviceInterface, concreteServiceName.serviceInterface)) { return false; } // wildcard condition if (isWildcard(this.version)) { return true; } if (isWildcard(this.group)) { return true; } // range condition if (!StringUtils.isEquals(this.version, concreteServiceName.version) && !matchRange(this.version, concreteServiceName.version)) { return false; } if (!StringUtils.isEquals(this.group, concreteServiceName.group) && !matchRange(this.group, concreteServiceName.group)) { return false; } return true; } private boolean matchRange(String range, String value) { if (isBlank(range)) { return true; } if (!isRange(range)) { return false; } String[] values = range.split(VALUE_SEPARATOR); return Arrays.asList(values).contains(value); } private boolean isConcrete(String value) { return !isWildcard(value) && !isRange(value); } private boolean isWildcard(String value) { return WILDCARD.equals(value); } private boolean isRange(String value) { return value != null && value.indexOf(VALUE_SEPARATOR) > -1 && value.split(VALUE_SEPARATOR).length > 1; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getServiceInterface() { return serviceInterface; } public void setServiceInterface(String serviceInterface) { this.serviceInterface = serviceInterface; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getValue() { if (value == null) { value = toValue(); } return value; } private String toValue() { return new StringBuilder(category) .append(NAME_SEPARATOR) .append(serviceInterface) .append(NAME_SEPARATOR) .append(version) .append(NAME_SEPARATOR) .append(group) .toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof NacosServiceName)) { return false; } NacosServiceName that = (NacosServiceName) o; return Objects.equals(getValue(), that.getValue()); } @Override public int hashCode() { return Objects.hash(getValue()); } @Override public String toString() { return getValue(); } }
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-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapper.java
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapper.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.nacos; 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.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.MethodUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.nacos.function.NacosConsumer; import org.apache.dubbo.registry.nacos.function.NacosFunction; import java.util.ArrayList; 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.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; public class NacosNamingServiceWrapper { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosNamingServiceWrapper.class); private static final String INNERCLASS_SYMBOL = "$"; private static final String INNERCLASS_COMPATIBLE_SYMBOL = "___"; private final NacosConnectionManager nacosConnectionManager; private final int retryTimes; private final int sleepMsBetweenRetries; private final boolean isSupportBatchRegister; private final ConcurrentMap<InstanceId, InstancesInfo> registerStatus = new ConcurrentHashMap<>(); private final ConcurrentMap<SubscribeInfo, NamingService> subscribeStatus = new ConcurrentHashMap<>(); public NacosNamingServiceWrapper( NacosConnectionManager nacosConnectionManager, int retryTimes, int sleepMsBetweenRetries) { this.nacosConnectionManager = nacosConnectionManager; this.isSupportBatchRegister = MethodUtils.findMethod( NamingService.class, "batchRegisterInstance", String.class, String.class, List.class) != null; logger.info("Nacos batch register enable: " + isSupportBatchRegister); this.retryTimes = Math.max(retryTimes, 0); this.sleepMsBetweenRetries = sleepMsBetweenRetries; } /** * @deprecated for uts only */ @Deprecated protected NacosNamingServiceWrapper( NacosConnectionManager nacosConnectionManager, boolean isSupportBatchRegister, int retryTimes, int sleepMsBetweenRetries) { this.nacosConnectionManager = nacosConnectionManager; this.isSupportBatchRegister = isSupportBatchRegister; this.retryTimes = Math.max(retryTimes, 0); this.sleepMsBetweenRetries = sleepMsBetweenRetries; } public String getServerStatus() { return nacosConnectionManager.getNamingService().getServerStatus(); } public void subscribe(String serviceName, String group, EventListener eventListener) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); SubscribeInfo subscribeInfo = new SubscribeInfo(nacosServiceName, group, eventListener); NamingService namingService = ConcurrentHashMapUtils.computeIfAbsent( subscribeStatus, subscribeInfo, info -> nacosConnectionManager.getNamingService()); accept(() -> namingService.subscribe(nacosServiceName, group, eventListener)); } public void unsubscribe(String serviceName, String group, EventListener eventListener) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); SubscribeInfo subscribeInfo = new SubscribeInfo(nacosServiceName, group, eventListener); NamingService namingService = subscribeStatus.get(subscribeInfo); if (namingService != null) { accept(() -> namingService.unsubscribe(nacosServiceName, group, eventListener)); subscribeStatus.remove(subscribeInfo); } } public List<Instance> getAllInstancesWithoutSubscription(String serviceName, String group) throws NacosException { return apply(() -> nacosConnectionManager .getNamingService() .getAllInstances(handleInnerSymbol(serviceName), group, false)); } public void registerInstance(String serviceName, String group, Instance instance) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent( registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); try { instancesInfo.lock(); if (!instancesInfo.isValid()) { registerInstance(serviceName, group, instance); return; } if (instancesInfo.getInstances().isEmpty()) { // directly register NamingService namingService = nacosConnectionManager.getNamingService(); accept(() -> namingService.registerInstance(nacosServiceName, group, instance)); instancesInfo.getInstances().add(new InstanceInfo(instance, namingService)); return; } if (instancesInfo.getInstances().size() == 1 && isSupportBatchRegister) { InstanceInfo previous = instancesInfo.getInstances().get(0); List<Instance> instanceListToRegister = new ArrayList<>(); NamingService namingService = previous.getNamingService(); instanceListToRegister.add(previous.getInstance()); instanceListToRegister.add(instance); try { accept(() -> namingService.batchRegisterInstance(nacosServiceName, group, instanceListToRegister)); instancesInfo.getInstances().add(new InstanceInfo(instance, namingService)); instancesInfo.setBatchRegistered(true); return; } catch (NacosException e) { logger.info("Failed to batch register to nacos. Service Name: " + serviceName + ". Maybe nacos server not support. Will fallback to multi connection register."); // ignore } } if (instancesInfo.isBatchRegistered()) { NamingService namingService = instancesInfo.getInstances().get(0).getNamingService(); List<Instance> instanceListToRegister = new ArrayList<>(); for (InstanceInfo instanceInfo : instancesInfo.getInstances()) { instanceListToRegister.add(instanceInfo.getInstance()); } instanceListToRegister.add(instance); accept(() -> namingService.batchRegisterInstance(nacosServiceName, group, instanceListToRegister)); instancesInfo.getInstances().add(new InstanceInfo(instance, namingService)); return; } // fallback to register one by one Set<NamingService> selectedNamingServices = instancesInfo.getInstances().stream() .map(InstanceInfo::getNamingService) .collect(Collectors.toSet()); NamingService namingService = nacosConnectionManager.getNamingService(selectedNamingServices); accept(() -> namingService.registerInstance(nacosServiceName, group, instance)); instancesInfo.getInstances().add(new InstanceInfo(instance, namingService)); } finally { instancesInfo.unlock(); } } public void updateInstance(String serviceName, String group, Instance oldInstance, Instance newInstance) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent( registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); try { instancesInfo.lock(); if (!instancesInfo.isValid() || instancesInfo.getInstances().isEmpty()) { throw new IllegalArgumentException(serviceName + " has not been registered to nacos."); } Optional<InstanceInfo> optional = instancesInfo.getInstances().stream() .filter(instanceInfo -> instanceInfo.getInstance().equals(oldInstance)) .findAny(); if (!optional.isPresent()) { throw new IllegalArgumentException(oldInstance + " has not been registered to nacos."); } InstanceInfo oldInstanceInfo = optional.get(); instancesInfo.getInstances().remove(oldInstanceInfo); instancesInfo.getInstances().add(new InstanceInfo(newInstance, oldInstanceInfo.getNamingService())); if (isSupportBatchRegister && instancesInfo.isBatchRegistered()) { NamingService namingService = oldInstanceInfo.getNamingService(); List<Instance> instanceListToRegister = instancesInfo.getInstances().stream() .map(InstanceInfo::getInstance) .collect(Collectors.toList()); accept(() -> namingService.batchRegisterInstance(nacosServiceName, group, instanceListToRegister)); return; } // fallback to register one by one accept(() -> oldInstanceInfo.getNamingService().registerInstance(nacosServiceName, group, newInstance)); } finally { instancesInfo.unlock(); } } public void deregisterInstance(String serviceName, String group, String ip, int port) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent( registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); try { instancesInfo.lock(); List<Instance> instances = instancesInfo.getInstances().stream() .map(InstanceInfo::getInstance) .filter(instance -> Objects.equals(instance.getIp(), ip) && instance.getPort() == port) .collect(Collectors.toList()); for (Instance instance : instances) { deregisterInstance(serviceName, group, instance); } } finally { instancesInfo.unlock(); } } public void deregisterInstance(String serviceName, String group, Instance instance) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent( registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); try { instancesInfo.lock(); Optional<InstanceInfo> optional = instancesInfo.getInstances().stream() .filter(instanceInfo -> instanceInfo.getInstance().equals(instance)) .findAny(); if (!optional.isPresent()) { return; } InstanceInfo instanceInfo = optional.get(); instancesInfo.getInstances().remove(instanceInfo); if (instancesInfo.getInstances().isEmpty()) { registerStatus.remove(new InstanceId(nacosServiceName, group)); instancesInfo.setValid(false); } // only one registered if (instancesInfo.getInstances().isEmpty()) { // directly unregister accept(() -> instanceInfo.getNamingService().deregisterInstance(nacosServiceName, group, instance)); instancesInfo.setBatchRegistered(false); return; } if (instancesInfo.isBatchRegistered()) { // register the rest instances List<Instance> instanceListToRegister = new ArrayList<>(); for (InstanceInfo info : instancesInfo.getInstances()) { instanceListToRegister.add(info.getInstance()); } accept(() -> instanceInfo .getNamingService() .batchRegisterInstance(nacosServiceName, group, instanceListToRegister)); } else { // unregister one accept(() -> instanceInfo.getNamingService().deregisterInstance(nacosServiceName, group, instance)); } } finally { instancesInfo.unlock(); } } public ListView<String> getServicesOfServer(int pageNo, int pageSize, String group) throws NacosException { return apply(() -> nacosConnectionManager.getNamingService().getServicesOfServer(pageNo, pageSize, group)); } public List<Instance> selectInstances(String serviceName, String group, boolean healthy) throws NacosException { return apply(() -> nacosConnectionManager .getNamingService() .selectInstances(handleInnerSymbol(serviceName), group, healthy)); } public void shutdown() throws NacosException { this.nacosConnectionManager.shutdownAll(); } /** * see https://github.com/apache/dubbo/issues/7129 * nacos service name just support `0-9a-zA-Z-._:`, grpc interface is inner interface, need compatible. */ private String handleInnerSymbol(String serviceName) { if (StringUtils.isEmpty(serviceName)) { return null; } return serviceName.replace(INNERCLASS_SYMBOL, INNERCLASS_COMPATIBLE_SYMBOL); } protected static class InstanceId { private final String serviceName; private final String group; public InstanceId(String serviceName, String group) { this.serviceName = serviceName; this.group = group; } public String getServiceName() { return serviceName; } public String getGroup() { return group; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InstanceId that = (InstanceId) o; return Objects.equals(serviceName, that.serviceName) && Objects.equals(group, that.group); } @Override public int hashCode() { return Objects.hash(serviceName, group); } } protected static class InstancesInfo { private final Lock lock = new ReentrantLock(); private final List<InstanceInfo> instances = new ArrayList<>(); private volatile boolean batchRegistered = false; private volatile boolean valid = true; public void lock() { lock.lock(); } public void unlock() { lock.unlock(); } public List<InstanceInfo> getInstances() { return instances; } public boolean isBatchRegistered() { return batchRegistered; } public void setBatchRegistered(boolean batchRegistered) { this.batchRegistered = batchRegistered; } public boolean isValid() { return valid; } public void setValid(boolean valid) { this.valid = valid; } } protected static class InstanceInfo { private final Instance instance; private final NamingService namingService; public InstanceInfo(Instance instance, NamingService namingService) { this.instance = instance; this.namingService = namingService; } public Instance getInstance() { return instance; } public NamingService getNamingService() { return namingService; } } private static class SubscribeInfo { private final String serviceName; private final String group; private final EventListener eventListener; public SubscribeInfo(String serviceName, String group, EventListener eventListener) { this.serviceName = serviceName; this.group = group; this.eventListener = eventListener; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubscribeInfo that = (SubscribeInfo) o; return Objects.equals(serviceName, that.serviceName) && Objects.equals(group, that.group) && Objects.equals(eventListener, that.eventListener); } @Override public int hashCode() { return Objects.hash(serviceName, group, eventListener); } } /** * @deprecated for uts only */ @Deprecated protected Map<InstanceId, InstancesInfo> getRegisterStatus() { return registerStatus; } private <R> R apply(NacosFunction<R> command) throws NacosException { NacosException le = null; R result = null; int times = 0; for (; times < retryTimes + 1; times++) { try { result = command.apply(); le = null; break; } catch (NacosException e) { le = e; logger.warn( LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, "", "", "Failed to request nacos naming server. " + (times < retryTimes ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " : "Exceed retry max times.") + "Try times: " + (times + 1), e); if (times < retryTimes) { try { Thread.sleep(sleepMsBetweenRetries); } catch (InterruptedException ex) { logger.warn( LoggerCodeConstants.INTERNAL_INTERRUPTED, "", "", "Interrupted when waiting to retry.", ex); Thread.currentThread().interrupt(); } } } } if (le != null) { throw le; } if (times > 1) { logger.info("Failed to request nacos naming server for " + (times - 1) + " times and finally success. " + "This may caused by high stress of nacos server."); } return result; } private void accept(NacosConsumer command) throws NacosException { NacosException le = null; int times = 0; for (; times < retryTimes + 1; times++) { try { command.accept(); le = null; break; } catch (NacosException e) { le = e; logger.warn( LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, "", "", "Failed to request nacos naming server. " + (times < retryTimes ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " : "Exceed retry max times.") + "Try times: " + (times + 1), e); if (times < retryTimes) { try { Thread.sleep(sleepMsBetweenRetries); } catch (InterruptedException ex) { logger.warn( LoggerCodeConstants.INTERNAL_INTERRUPTED, "", "", "Interrupted when waiting to retry.", ex); Thread.currentThread().interrupt(); } } } } if (le != null) { throw le; } if (times > 1) { logger.info("Failed to request nacos naming server for " + (times - 1) + " times and finally success. " + "This may caused by high stress of nacos server."); } } }
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-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.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.nacos.util; 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.UrlUtils; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.nacos.NacosConnectionManager; import org.apache.dubbo.registry.nacos.NacosNamingServiceWrapper; import org.apache.dubbo.rpc.model.ScopeModelUtil; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.utils.NamingUtils; import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; /** * The utilities class for {@link NamingService} * * @since 2.7.5 */ public class NacosNamingServiceUtils { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosNamingServiceUtils.class); private static final String NACOS_GROUP_KEY = "nacos.group"; private static final String NACOS_RETRY_KEY = "nacos.retry"; private static final String NACOS_RETRY_WAIT_KEY = "nacos.retry-wait"; private static final String NACOS_CHECK_KEY = "nacos.check"; private NacosNamingServiceUtils() { throw new IllegalStateException("NacosNamingServiceUtils should not be instantiated"); } /** * Convert the {@link ServiceInstance} to {@link Instance} * * @param serviceInstance {@link ServiceInstance} * @return non-null * @since 2.7.5 */ public static Instance toInstance(ServiceInstance serviceInstance) { Instance instance = new Instance(); instance.setServiceName(serviceInstance.getServiceName()); instance.setIp(serviceInstance.getHost()); instance.setPort(serviceInstance.getPort()); instance.setMetadata(serviceInstance.getSortedMetadata()); instance.setEnabled(serviceInstance.isEnabled()); instance.setHealthy(serviceInstance.isHealthy()); return instance; } /** * Convert the {@link Instance} to {@link ServiceInstance} * * @param instance {@link Instance} * @return non-null * @since 2.7.5 */ public static ServiceInstance toServiceInstance(URL registryUrl, Instance instance) { DefaultServiceInstance serviceInstance = new DefaultServiceInstance( NamingUtils.getServiceName(instance.getServiceName()), instance.getIp(), instance.getPort(), ScopeModelUtil.getApplicationModel(registryUrl.getScopeModel())); serviceInstance.setMetadata(instance.getMetadata()); serviceInstance.setEnabled(instance.isEnabled()); serviceInstance.setHealthy(instance.isHealthy()); return serviceInstance; } /** * The group of {@link NamingService} to register * * @param connectionURL {@link URL connection url} * @return non-null, "default" as default * @since 2.7.5 */ public static String getGroup(URL connectionURL) { // Compatible with nacos grouping via group. String group = connectionURL.getParameter(GROUP_KEY, DEFAULT_GROUP); return connectionURL.getParameter(NACOS_GROUP_KEY, group); } /** * Create an instance of {@link NamingService} from specified {@link URL connection url} * * @param connectionURL {@link URL connection url} * @return {@link NamingService} * @since 2.7.5 */ public static NacosNamingServiceWrapper createNamingService(URL connectionURL) { boolean check = connectionURL.getParameter(NACOS_CHECK_KEY, true); int retryTimes = connectionURL.getPositiveParameter(NACOS_RETRY_KEY, 10); int sleepMsBetweenRetries = connectionURL.getPositiveParameter(NACOS_RETRY_WAIT_KEY, 10); if (check && !UrlUtils.isCheck(connectionURL)) { check = false; } NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(connectionURL, check, retryTimes, sleepMsBetweenRetries); return new NacosNamingServiceWrapper(nacosConnectionManager, retryTimes, sleepMsBetweenRetries); } }
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-nacos/src/main/java/org/apache/dubbo/registry/nacos/aot/NacosReflectionTypeDescriberRegistrar.java
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/aot/NacosReflectionTypeDescriberRegistrar.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.nacos.aot; import org.apache.dubbo.aot.api.MemberCategory; import org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar; import org.apache.dubbo.aot.api.TypeDescriber; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.ability.ClientAbilities; import com.alibaba.nacos.api.config.ability.ClientConfigAbility; import com.alibaba.nacos.api.config.remote.request.AbstractConfigRequest; import com.alibaba.nacos.api.config.remote.request.ConfigBatchListenRequest; import com.alibaba.nacos.api.config.remote.request.ConfigBatchListenRequest.ConfigListenContext; import com.alibaba.nacos.api.config.remote.request.ConfigPublishRequest; import com.alibaba.nacos.api.config.remote.request.ConfigQueryRequest; import com.alibaba.nacos.api.config.remote.response.ConfigChangeBatchListenResponse; import com.alibaba.nacos.api.config.remote.response.ConfigChangeBatchListenResponse.ConfigContext; import com.alibaba.nacos.api.config.remote.response.ConfigPublishResponse; import com.alibaba.nacos.api.config.remote.response.ConfigQueryResponse; import com.alibaba.nacos.api.grpc.auto.Metadata; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.ability.ClientNamingAbility; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.api.naming.remote.request.AbstractNamingRequest; import com.alibaba.nacos.api.naming.remote.request.InstanceRequest; import com.alibaba.nacos.api.naming.remote.request.NotifySubscriberRequest; import com.alibaba.nacos.api.naming.remote.request.ServiceQueryRequest; import com.alibaba.nacos.api.naming.remote.request.SubscribeServiceRequest; import com.alibaba.nacos.api.naming.remote.response.InstanceResponse; import com.alibaba.nacos.api.naming.remote.response.NotifySubscriberResponse; import com.alibaba.nacos.api.naming.remote.response.QueryServiceResponse; import com.alibaba.nacos.api.naming.remote.response.SubscribeServiceResponse; import com.alibaba.nacos.api.remote.ability.ClientRemoteAbility; import com.alibaba.nacos.api.remote.request.ConnectionSetupRequest; import com.alibaba.nacos.api.remote.request.HealthCheckRequest; import com.alibaba.nacos.api.remote.request.InternalRequest; import com.alibaba.nacos.api.remote.request.Request; import com.alibaba.nacos.api.remote.request.ServerCheckRequest; import com.alibaba.nacos.api.remote.request.ServerRequest; import com.alibaba.nacos.api.remote.response.HealthCheckResponse; import com.alibaba.nacos.api.remote.response.Response; import com.alibaba.nacos.api.remote.response.ServerCheckResponse; import com.alibaba.nacos.client.auth.impl.NacosClientAuthServiceImpl; import com.alibaba.nacos.client.auth.ram.RamClientAuthServiceImpl; import com.alibaba.nacos.client.config.NacosConfigService; import com.alibaba.nacos.client.naming.NacosNamingService; import com.alibaba.nacos.common.notify.DefaultPublisher; import com.alibaba.nacos.common.remote.TlsConfig; import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig; import com.alibaba.nacos.shaded.com.google.common.util.concurrent.AbstractFuture; import com.alibaba.nacos.shaded.com.google.protobuf.Any; import com.alibaba.nacos.shaded.com.google.protobuf.ExtensionRegistry; import com.alibaba.nacos.shaded.io.grpc.internal.DnsNameResolverProvider; import com.alibaba.nacos.shaded.io.grpc.internal.PickFirstLoadBalancerProvider; import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.buffer.AbstractByteBufAllocator; import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.buffer.AbstractReferenceCountedByteBuf; import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.ChannelDuplexHandler; import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.ChannelInboundHandlerAdapter; import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.socket.nio.NioSocketChannel; import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder; import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2ConnectionHandler; import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.ReferenceCountUtil; public class NacosReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar { @Override public List<TypeDescriber> getTypeDescribers() { List<TypeDescriber> typeDescribers = new ArrayList<>(); Class[] classesWithDeclared = { ClientAbilities.class, ClientConfigAbility.class, AbstractConfigRequest.class, ConfigBatchListenRequest.class, ConfigListenContext.class, ConfigPublishRequest.class, ConfigQueryRequest.class, ConfigChangeBatchListenResponse.class, ConfigContext.class, ConfigPublishResponse.class, ConfigQueryResponse.class, ClientNamingAbility.class, Instance.class, ServiceInfo.class, AbstractNamingRequest.class, InstanceRequest.class, NotifySubscriberRequest.class, ServiceQueryRequest.class, SubscribeServiceRequest.class, InstanceResponse.class, NotifySubscriberResponse.class, QueryServiceResponse.class, SubscribeServiceResponse.class, ClientRemoteAbility.class, ConnectionSetupRequest.class, HealthCheckRequest.class, InternalRequest.class, Request.class, ServerCheckRequest.class, ServerRequest.class, HealthCheckResponse.class, Response.class, ServerCheckResponse.class, TlsConfig.class, RpcClientTlsConfig.class }; Class[] classesWithMethods = { Metadata.class, com.alibaba.nacos.api.grpc.auto.Metadata.Builder.class, com.alibaba.nacos.api.grpc.auto.Payload.class, com.alibaba.nacos.api.grpc.auto.Payload.Builder.class, NamingService.class, com.alibaba.nacos.api.remote.Payload.class, NacosClientAuthServiceImpl.class, RamClientAuthServiceImpl.class, NacosConfigService.class, NacosNamingService.class, DefaultPublisher.class, Any.class, com.alibaba.nacos.shaded.com.google.protobuf.Any.Builder.class, ExtensionRegistry.class, AbstractByteBufAllocator.class, ChannelDuplexHandler.class, ChannelInboundHandlerAdapter.class, NioSocketChannel.class, ByteToMessageDecoder.class, Http2ConnectionHandler.class, ReferenceCountUtil.class }; Class[] classesWithFields = {PropertyKeyConst.class, AbstractFuture.class, AbstractReferenceCountedByteBuf.class }; Class[] classesWithDefault = {DnsNameResolverProvider.class, PickFirstLoadBalancerProvider.class}; String[] privateClasses = { "com.alibaba.nacos.shaded.com.google.common.util.concurrent.AbstractFuture.Waiter", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty.AbstractNettyHandler", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty.NettyClientHandler", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty.WriteBufferingAndExceptionHandler", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.HeadContext", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.TailContext", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueColdProducerFields", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueConsumerFields", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueProducerFields", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueConsumerIndexField", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueProducerIndexField", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueProducerLimitField" }; for (Class className : classesWithDeclared) { typeDescribers.add(buildTypeDescriberWithDeclared(className)); } for (Class className : classesWithMethods) { typeDescribers.add(buildTypeDescriberWithMethods(className)); } for (Class className : classesWithFields) { typeDescribers.add(buildTypeDescriberWithFields(className)); } for (Class className : classesWithDefault) { typeDescribers.add(buildTypeDescriberWithDefault(className)); } for (String className : privateClasses) { typeDescribers.add(buildTypeDescriberWithDeclared(className)); } return typeDescribers; } private TypeDescriber buildTypeDescriberWithDeclared(Class<?> cl) { Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); memberCategories.add(MemberCategory.DECLARED_FIELDS); return new TypeDescriber( cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } private TypeDescriber buildTypeDescriberWithFields(Class<?> cl) { Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.DECLARED_FIELDS); return new TypeDescriber( cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } private TypeDescriber buildTypeDescriberWithMethods(Class<?> cl) { Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); return new TypeDescriber( cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } private TypeDescriber buildTypeDescriberWithDefault(Class<?> cl) { return new TypeDescriber( cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), new HashSet<>()); } private TypeDescriber buildTypeDescriberWithDeclared(String className) { Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); memberCategories.add(MemberCategory.DECLARED_FIELDS); return new TypeDescriber(className, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } private TypeDescriber buildTypeDescriberWithFields(String className) { Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.DECLARED_FIELDS); return new TypeDescriber(className, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } private TypeDescriber buildTypeDescriberWithMethods(String className) { Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); return new TypeDescriber(className, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } private TypeDescriber buildTypeDescriberWithDefault(String className) { return new TypeDescriber(className, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), new HashSet<>()); } }
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-nacos/src/main/java/org/apache/dubbo/registry/nacos/function/NacosFunction.java
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/function/NacosFunction.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.nacos.function; import java.util.function.Function; import com.alibaba.nacos.api.exception.NacosException; /** * A function interface for action with {@link NacosException} * * @see Function * @see NacosException * @since 3.1.5 */ @FunctionalInterface public interface NacosFunction<R> { /** * Applies this function to the given argument. * * @return the function result * @throws NacosException if met with any error */ R apply() throws NacosException; }
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-nacos/src/main/java/org/apache/dubbo/registry/nacos/function/NacosConsumer.java
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/function/NacosConsumer.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.nacos.function; import java.util.function.Function; import com.alibaba.nacos.api.exception.NacosException; /** * A function interface for action with {@link NacosException} * * @see Function * @see NacosException * @since 3.1.5 */ @FunctionalInterface public interface NacosConsumer { /** * Applies this function to the given argument. * * @throws NacosException if met with any error */ void accept() throws NacosException; }
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-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java
dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.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.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import com.google.common.collect.Lists; import org.apache.curator.CuratorZookeeperClient; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.imps.CuratorFrameworkState; import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.ServiceCacheBuilder; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; 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.Test; import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; import org.mockito.MockedStatic; import org.mockito.internal.util.collections.Sets; import static java.util.Arrays.asList; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; /** * {@link ZookeeperServiceDiscovery} Test * * @since 2.7.5 */ @DisabledForJreRange(min = JRE.JAVA_16) class ZookeeperServiceDiscoveryTest { private static final String SERVICE_NAME = "A"; private static final String LOCALHOST = "127.0.0.1"; private URL registryUrl; private ZookeeperServiceDiscovery discovery; private static String zookeeperConnectionAddress1; private static MockedStatic<CuratorFrameworkFactory> curatorFrameworkFactoryMockedStatic; private static MockedStatic<ServiceDiscoveryBuilder> serviceDiscoveryBuilderMockedStatic; private CuratorFramework mockCuratorFramework; private CuratorZookeeperClient mockCuratorZookeeperClient; private ServiceDiscoveryBuilder mockServiceDiscoveryBuilder; private ServiceDiscovery mockServiceDiscovery; private ServiceCacheBuilder mockServiceCacheBuilder; private ServiceCache mockServiceCache; private static final CuratorFrameworkFactory.Builder spyBuilder = spy(CuratorFrameworkFactory.builder()); @BeforeAll public static void beforeAll() { zookeeperConnectionAddress1 = "zookeeper://localhost:" + "2181"; curatorFrameworkFactoryMockedStatic = mockStatic(CuratorFrameworkFactory.class); curatorFrameworkFactoryMockedStatic .when(CuratorFrameworkFactory::builder) .thenReturn(spyBuilder); serviceDiscoveryBuilderMockedStatic = mockStatic(ServiceDiscoveryBuilder.class); } @BeforeEach public void init() throws Exception { mockServiceDiscoveryBuilder = mock(ServiceDiscoveryBuilder.class); mockServiceDiscovery = mock(ServiceDiscovery.class); mockServiceCacheBuilder = mock(ServiceCacheBuilder.class); mockCuratorFramework = mock(CuratorFramework.class); mockServiceCache = mock(ServiceCache.class); serviceDiscoveryBuilderMockedStatic .when(() -> ServiceDiscoveryBuilder.builder(any())) .thenReturn(mockServiceDiscoveryBuilder); when(mockServiceDiscoveryBuilder.client(any())).thenReturn(mockServiceDiscoveryBuilder); when(mockServiceDiscoveryBuilder.basePath(any())).thenReturn(mockServiceDiscoveryBuilder); when(mockServiceDiscoveryBuilder.build()).thenReturn(mockServiceDiscovery); when(mockServiceDiscovery.serviceCacheBuilder()).thenReturn(mockServiceCacheBuilder); when(mockServiceCacheBuilder.name(any())).thenReturn(mockServiceCacheBuilder); when(mockServiceCacheBuilder.build()).thenReturn(mockServiceCache); doReturn(mockCuratorFramework).when(spyBuilder).build(); mockCuratorZookeeperClient = mock(CuratorZookeeperClient.class); // mock default is started. If method need other status please replace in test method. when(mockCuratorFramework.getZookeeperClient()).thenReturn(mockCuratorZookeeperClient); when(mockCuratorFramework.getState()).thenReturn(CuratorFrameworkState.STARTED); when(mockCuratorZookeeperClient.isConnected()).thenReturn(true); this.registryUrl = URL.valueOf(zookeeperConnectionAddress1); ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig(SERVICE_NAME)); registryUrl.setScopeModel(applicationModel); this.discovery = new ZookeeperServiceDiscovery(applicationModel, registryUrl); } @AfterEach public void close() throws Exception { discovery.destroy(); } @Test void testRegistration() throws Exception { CountDownLatch latch = new CountDownLatch(1); // Add Listener discovery.addServiceInstancesChangedListener( new ServiceInstancesChangedListener(Sets.newSet(SERVICE_NAME), discovery) { @Override public void onEvent(ServiceInstancesChangedEvent event) { latch.countDown(); } }); discovery.register(); latch.await(); List<ServiceInstance> serviceInstances = discovery.getInstances(SERVICE_NAME); assertEquals(0, serviceInstances.size()); discovery.register(URL.valueOf("dubbo://1.1.2.3:20880/DemoService")); discovery.register(); DefaultServiceInstance serviceInstance = (DefaultServiceInstance) discovery.getLocalInstance(); List<org.apache.curator.x.discovery.ServiceInstance> lists = Lists.newArrayList(org.apache.curator.x.discovery.ServiceInstance.builder() .name(SERVICE_NAME) .address( URL.valueOf("dubbo://1.1.2.3:20880/DemoService").getHost()) .port(20880) .payload(new ZookeeperInstance( "", serviceInstance.getServiceName(), serviceInstance.getMetadata())) .build()); when(mockServiceDiscovery.queryForInstances(any())).thenReturn(lists); serviceInstances = discovery.getInstances(SERVICE_NAME); assertTrue(serviceInstances.contains(serviceInstance)); assertEquals(asList(serviceInstance), serviceInstances); Map<String, String> metadata = new HashMap<>(); metadata.put("message", "Hello,World"); serviceInstance.setMetadata(metadata); discovery.register(URL.valueOf("dubbo://1.1.2.3:20880/DemoService1")); discovery.update(); lists = Lists.newArrayList(org.apache.curator.x.discovery.ServiceInstance.builder() .name(SERVICE_NAME) .address(URL.valueOf("dubbo://1.1.2.3:20880/DemoService").getHost()) .port(20880) .payload(new ZookeeperInstance("", serviceInstance.getServiceName(), metadata)) .build()); when(mockServiceDiscovery.queryForInstances(any())).thenReturn(lists); serviceInstances = discovery.getInstances(SERVICE_NAME); assertEquals(serviceInstance, serviceInstances.get(0)); discovery.unregister(); when(mockServiceDiscovery.queryForInstances(any())).thenReturn(new ArrayList<>()); serviceInstances = discovery.getInstances(SERVICE_NAME); assertTrue(serviceInstances.isEmpty()); } @Test void testRegistryCheckConnectDefault() { when(mockCuratorZookeeperClient.isConnected()).thenReturn(false); URL registryUrl = URL.valueOf(zookeeperConnectionAddress1); ApplicationModel applicationModel = ApplicationModel.defaultModel(); registryUrl.setScopeModel(applicationModel); Assertions.assertThrowsExactly(IllegalStateException.class, () -> { new ZookeeperServiceDiscovery(applicationModel, registryUrl); }); } @Test void testRegistryNotCheckConnect() { when(mockCuratorZookeeperClient.isConnected()).thenReturn(false); URL registryUrl = URL.valueOf(zookeeperConnectionAddress1).addParameter(CHECK_KEY, false); ApplicationModel applicationModel = ApplicationModel.defaultModel(); registryUrl.setScopeModel(applicationModel); Assertions.assertDoesNotThrow(() -> { new ZookeeperServiceDiscovery(applicationModel, registryUrl); }); } @AfterAll public static void afterAll() throws Exception { if (curatorFrameworkFactoryMockedStatic != null) { curatorFrameworkFactoryMockedStatic.close(); } if (serviceDiscoveryBuilderMockedStatic != null) { serviceDiscoveryBuilderMockedStatic.close(); } } }
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-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryTest.java
dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryTest.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.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClientManager; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import com.google.common.collect.Lists; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class ZookeeperRegistryTest { private static String zookeeperConnectionAddress1; private ZookeeperRegistry zookeeperRegistry; private String service = "org.apache.dubbo.test.injvmServie"; private String url = "zookeeper://zookeeper/" + service + "?notify=false&methods=test1,test2"; private URL serviceUrl = URL.valueOf(url); private URL anyUrl = URL.valueOf("zookeeper://zookeeper/*"); private URL registryUrl; private ZookeeperRegistryFactory zookeeperRegistryFactory; private NotifyListener listener; // mock object private static ZookeeperClientManager mockZookeeperClientManager; private static ZookeeperClient mockZookeeperClient; @BeforeAll public static void beforeAll() { zookeeperConnectionAddress1 = "zookeeper://localhost:" + "2181"; } @BeforeEach public void setUp() throws Exception { mockZookeeperClientManager = mock(ZookeeperClientManager.class); mockZookeeperClient = mock(ZookeeperClient.class); this.registryUrl = URL.valueOf(zookeeperConnectionAddress1); zookeeperRegistryFactory = new ZookeeperRegistryFactory(ApplicationModel.defaultModel()); zookeeperRegistryFactory.setZookeeperTransporter(mockZookeeperClientManager); when(mockZookeeperClientManager.connect(registryUrl)).thenReturn(mockZookeeperClient); this.zookeeperRegistry = (ZookeeperRegistry) zookeeperRegistryFactory.createRegistry(registryUrl); } @Test void testAnyHost() { Assertions.assertThrows(IllegalStateException.class, () -> { URL errorUrl = URL.valueOf("multicast://0.0.0.0/"); new ZookeeperRegistryFactory(ApplicationModel.defaultModel()).createRegistry(errorUrl); }); } @Test void testRegister() { Set<URL> registered; for (int i = 0; i < 2; i++) { zookeeperRegistry.register(serviceUrl); registered = zookeeperRegistry.getRegistered(); assertThat(registered.contains(serviceUrl), is(true)); } registered = zookeeperRegistry.getRegistered(); assertThat(registered.size(), is(1)); } @Test void testSubscribe() { NotifyListener listener = mock(NotifyListener.class); zookeeperRegistry.subscribe(serviceUrl, listener); Map<URL, Set<NotifyListener>> subscribed = zookeeperRegistry.getSubscribed(); assertThat(subscribed.size(), is(1)); assertThat(subscribed.get(serviceUrl).size(), is(1)); zookeeperRegistry.unsubscribe(serviceUrl, listener); subscribed = zookeeperRegistry.getSubscribed(); assertThat(subscribed.size(), is(1)); assertThat(subscribed.get(serviceUrl).size(), is(0)); } @Test void testAvailable() { zookeeperRegistry.register(serviceUrl); when(mockZookeeperClient.isConnected()).thenReturn(true); assertThat(zookeeperRegistry.isAvailable(), is(true)); zookeeperRegistry.destroy(); assertThat(zookeeperRegistry.isAvailable(), is(false)); } @Test void testLookup() { when(mockZookeeperClient.getChildren(any())).thenReturn(Lists.newArrayList(url)); List<URL> lookup = zookeeperRegistry.lookup(serviceUrl); assertThat(lookup.size(), is(1)); zookeeperRegistry.register(serviceUrl); lookup = zookeeperRegistry.lookup(serviceUrl); assertThat(lookup.size(), is(1)); } @Test void testLookupIllegalUrl() { try { zookeeperRegistry.lookup(null); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), containsString("lookup url == null")); } } @Test void testLookupWithException() { URL errorUrl = URL.valueOf("multicast://0.0.0.0/"); when(mockZookeeperClient.getChildren(any())).thenThrow(new IllegalStateException()); Assertions.assertThrows(RpcException.class, () -> zookeeperRegistry.lookup(errorUrl)); } @Test void testSubscribeAnyValue() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); zookeeperRegistry.register(serviceUrl); zookeeperRegistry.subscribe(anyUrl, urls -> latch.countDown()); doAnswer(invocationOnMock -> { latch.countDown(); return null; }) .when(mockZookeeperClient) .create(any(), anyBoolean(), anyBoolean()); zookeeperRegistry.register(serviceUrl); latch.await(); } @Test void testDestroy() { zookeeperRegistry.destroy(); assertThat(zookeeperRegistry.isAvailable(), is(false)); } @Test void testDoRegisterWithException() { doThrow(new IllegalStateException()).when(mockZookeeperClient).create(any(), anyBoolean(), anyBoolean()); Assertions.assertThrows(RpcException.class, () -> { URL errorUrl = URL.valueOf("multicast://0.0.0.0/"); zookeeperRegistry.doRegister(errorUrl); }); } @Test void testDoUnregisterWithException() { doThrow(new IllegalStateException()).when(mockZookeeperClient).delete(any()); Assertions.assertThrows(RpcException.class, () -> { URL errorUrl = URL.valueOf("multicast://0.0.0.0/"); zookeeperRegistry.doUnregister(errorUrl); }); } @Test void testDoSubscribeWithException() { Assertions.assertThrows(RpcException.class, () -> zookeeperRegistry.doSubscribe(anyUrl, 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-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtilsTest.java
dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtilsTest.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.zookeeper.util; import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.zookeeper.ZookeeperInstance; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.curator.CuratorZookeeperClient; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.imps.CuratorFrameworkState; import org.apache.curator.x.discovery.ServiceDiscovery; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; 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.zookeeper.util.CuratorFrameworkParams.ROOT_PATH; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; /** * {@link CuratorFrameworkUtils} Test */ class CuratorFrameworkUtilsTest { private static URL registryUrl; private static String zookeeperConnectionAddress1; private static MetadataReport metadataReport; private static MockedStatic<CuratorFrameworkFactory> curatorFrameworkFactoryMockedStatic; CuratorFrameworkFactory.Builder spyBuilder = CuratorFrameworkFactory.builder(); private CuratorFramework mockCuratorFramework; private CuratorZookeeperClient mockCuratorZookeeperClient; @BeforeAll public static void init() throws Exception { zookeeperConnectionAddress1 = "zookeeper://localhost:" + "2181"; registryUrl = URL.valueOf(zookeeperConnectionAddress1); registryUrl.setScopeModel(ApplicationModel.defaultModel()); metadataReport = Mockito.mock(MetadataReport.class); // mock begin // create mock bean begin CuratorFrameworkFactory.Builder realBuilder = CuratorFrameworkFactory.builder(); CuratorFrameworkFactory.Builder spyBuilder = spy(realBuilder); curatorFrameworkFactoryMockedStatic = mockStatic(CuratorFrameworkFactory.class); curatorFrameworkFactoryMockedStatic .when(CuratorFrameworkFactory::builder) .thenReturn(spyBuilder); } @BeforeEach public void setUp() throws Exception { mockCuratorFramework = mock(CuratorFramework.class); doReturn(mockCuratorFramework).when(spyBuilder).build(); mockCuratorZookeeperClient = mock(CuratorZookeeperClient.class); // mock default is started. If method need other status please replace in test method. when(mockCuratorFramework.getZookeeperClient()).thenReturn(mockCuratorZookeeperClient); when(mockCuratorFramework.getState()).thenReturn(CuratorFrameworkState.STARTED); when(mockCuratorZookeeperClient.isConnected()).thenReturn(true); } @Test void testBuildCuratorFramework() throws Exception { CuratorFramework curatorFramework = CuratorFrameworkUtils.buildCuratorFramework(registryUrl, null); Assertions.assertNotNull(curatorFramework); Assertions.assertTrue(curatorFramework.getZookeeperClient().isConnected()); curatorFramework.getZookeeperClient().close(); } @Test void testBuildServiceDiscovery() throws Exception { CuratorFramework curatorFramework = CuratorFrameworkUtils.buildCuratorFramework(registryUrl, null); ServiceDiscovery<ZookeeperInstance> discovery = CuratorFrameworkUtils.buildServiceDiscovery(curatorFramework, ROOT_PATH.getParameterValue(registryUrl)); Assertions.assertNotNull(discovery); curatorFramework.getZookeeperClient().close(); } @Test void testBuildCuratorFrameworkCheckConnectDefault() { when(mockCuratorZookeeperClient.isConnected()).thenReturn(false); Assertions.assertThrowsExactly(IllegalStateException.class, () -> { CuratorFramework curatorFramework = CuratorFrameworkUtils.buildCuratorFramework(registryUrl, null); curatorFramework.getZookeeperClient().close(); }); } @Test void testBuildCuratorFrameworkNotCheckConnect() { when(mockCuratorZookeeperClient.isConnected()).thenReturn(false); URL url = registryUrl.addParameter(CHECK_KEY, false); Assertions.assertDoesNotThrow(() -> { CuratorFramework curatorFramework = CuratorFrameworkUtils.buildCuratorFramework(url, null); curatorFramework.getZookeeperClient().close(); }); } @Test void testBuild() { ServiceInstance dubboServiceInstance = new DefaultServiceInstance("A", "127.0.0.1", 8888, ApplicationModel.defaultModel()); Map<String, String> metadata = dubboServiceInstance.getMetadata(); metadata.put(METADATA_STORAGE_TYPE_PROPERTY_NAME, "remote"); metadata.put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, "111"); metadata.put("site", "dubbo"); // convert {org.apache.dubbo.registry.client.ServiceInstance} to // {org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance>} org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance> curatorServiceInstance = CuratorFrameworkUtils.build(dubboServiceInstance); Assertions.assertEquals(curatorServiceInstance.getId(), dubboServiceInstance.getAddress()); Assertions.assertEquals(curatorServiceInstance.getName(), dubboServiceInstance.getServiceName()); Assertions.assertEquals(curatorServiceInstance.getAddress(), dubboServiceInstance.getHost()); Assertions.assertEquals(curatorServiceInstance.getPort(), dubboServiceInstance.getPort()); ZookeeperInstance payload = curatorServiceInstance.getPayload(); Assertions.assertNotNull(payload); Assertions.assertEquals(payload.getMetadata(), metadata); Assertions.assertEquals(payload.getName(), dubboServiceInstance.getServiceName()); // convert {org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance>} to // {org.apache.dubbo.registry.client.ServiceInstance} ServiceInstance serviceInstance = CuratorFrameworkUtils.build(registryUrl, curatorServiceInstance); Assertions.assertEquals(serviceInstance, dubboServiceInstance); // convert {Collection<org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance>>} to // {List<org.apache.dubbo.registry.client.ServiceInstance>} List<ServiceInstance> serviceInstances = CuratorFrameworkUtils.build(registryUrl, Arrays.asList(curatorServiceInstance)); Assertions.assertNotNull(serviceInstances); Assertions.assertEquals(serviceInstances.get(0), dubboServiceInstance); } @AfterAll public static void afterAll() throws Exception { if (curatorFrameworkFactoryMockedStatic != null) { curatorFrameworkFactoryMockedStatic.close(); } } }
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-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java
dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.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.zookeeper; import java.util.HashMap; import java.util.Map; /** * Represents the default payload of a registered service in Zookeeper. * <p> * It's compatible with Spring Cloud * * @since 2.7.5 */ public class ZookeeperInstance { private String id; private String name; private Map<String, String> metadata = new HashMap<>(); @SuppressWarnings("unused") private ZookeeperInstance() {} public ZookeeperInstance(String id, String name, Map<String, String> metadata) { this.id = id; this.name = name; this.metadata = metadata; } public String getId() { return this.id; } public String getName() { return this.name; } public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } public Map<String, String> getMetadata() { return this.metadata; } public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } @Override public String toString() { return "ZookeeperInstance{" + "id='" + this.id + '\'' + ", name='" + this.name + '\'' + ", metadata=" + this.metadata + '}'; } }
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-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java
dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.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.zookeeper; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.registry.RegistryNotifier; 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.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.details.ServiceCacheListener; import org.apache.zookeeper.Watcher; /** * Zookeeper {@link ServiceDiscovery} Change {@link CuratorWatcher watcher} only interests in * {@link Watcher.Event.EventType#NodeChildrenChanged} and {@link Watcher.Event.EventType#NodeDataChanged} event types, * which will multicast a {@link ServiceInstancesChangedEvent} when the service node has been changed. * * @since 2.7.5 */ public class ZookeeperServiceDiscoveryChangeWatcher implements ServiceCacheListener { private final Set<ServiceInstancesChangedListener> listeners = new ConcurrentHashSet<>(); private final ServiceCache<ZookeeperInstance> cacheInstance; private final ZookeeperServiceDiscovery zookeeperServiceDiscovery; private final RegistryNotifier notifier; private final String serviceName; private final CountDownLatch latch; public ZookeeperServiceDiscoveryChangeWatcher( ZookeeperServiceDiscovery zookeeperServiceDiscovery, ServiceCache<ZookeeperInstance> cacheInstance, String serviceName, CountDownLatch latch) { this.zookeeperServiceDiscovery = zookeeperServiceDiscovery; this.cacheInstance = cacheInstance; this.serviceName = serviceName; this.notifier = new RegistryNotifier( zookeeperServiceDiscovery.getUrl(), zookeeperServiceDiscovery.getDelay(), ScopeModelUtil.getFrameworkModel( zookeeperServiceDiscovery.getUrl().getScopeModel()) .getBeanFactory() .getBean(FrameworkExecutorRepository.class) .getServiceDiscoveryAddressNotificationExecutor()) { @Override protected void doNotify(Object rawAddresses) { listeners.forEach(listener -> listener.onEvent((ServiceInstancesChangedEvent) rawAddresses)); } }; this.latch = latch; } @Override public void cacheChanged() { try { latch.await(); } catch (InterruptedException ignore) { Thread.currentThread().interrupt(); } List<ServiceInstance> instanceList = zookeeperServiceDiscovery.getInstances(serviceName); notifier.notify(new ServiceInstancesChangedEvent(serviceName, instanceList)); } @Override public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) { // ignore: taken care by curator ServiceDiscovery } public ServiceCache<ZookeeperInstance> getCacheInstance() { return cacheInstance; } public Set<ServiceInstancesChangedListener> getListeners() { return listeners; } public void addListener(ServiceInstancesChangedListener listener) { listeners.add(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-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java
dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.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.zookeeper; 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.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.support.CacheableFailbackRegistry; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.zookeeper.curator5.ChildListener; import org.apache.dubbo.remoting.zookeeper.curator5.StateListener; import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClientManager; import org.apache.dubbo.rpc.RpcException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; 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.CountDownLatch; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_DESERIALIZE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; 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.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; public class ZookeeperRegistry extends CacheableFailbackRegistry { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ZookeeperRegistry.class); private static final String DEFAULT_ROOT = "dubbo"; private final String root; private final Set<String> anyServices = new ConcurrentHashSet<>(); private final ConcurrentMap<URL, ConcurrentMap<NotifyListener, ChildListener>> zkListeners = new ConcurrentHashMap<>(); private ZookeeperClient zkClient; public ZookeeperRegistry(URL url, ZookeeperClientManager zookeeperClientManager) { super(url); if (url.isAnyHost()) { throw new IllegalStateException("registry address == null"); } String group = url.getGroup(DEFAULT_ROOT); if (!group.startsWith(PATH_SEPARATOR)) { group = PATH_SEPARATOR + group; } this.root = group; this.zkClient = zookeeperClientManager.connect(url); this.zkClient.addStateListener((state) -> { if (state == StateListener.RECONNECTED) { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Trying to fetch the latest urls, in case there are provider changes during connection loss.\n" + " Since ephemeral ZNode will not get deleted for a connection lose, " + "there's no need to re-register url of this instance."); ZookeeperRegistry.this.fetchLatestAddresses(); } else if (state == StateListener.NEW_SESSION_CREATED) { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Trying to re-register urls and re-subscribe listeners of this instance to registry..."); try { ZookeeperRegistry.this.recover(); } catch (Exception e) { logger.error(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", e.getMessage(), e); } } else if (state == StateListener.SESSION_LOST) { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Url of this instance will be deleted from registry soon. " + "Dubbo client will try to re-register once a new session is created."); } else if (state == StateListener.SUSPENDED) { } else if (state == StateListener.CONNECTED) { } }); } @Override public boolean isAvailable() { return zkClient != null && zkClient.isConnected(); } @Override public void destroy() { super.destroy(); // remove child listener Set<URL> urls = zkListeners.keySet(); for (URL url : urls) { ConcurrentMap<NotifyListener, ChildListener> map = zkListeners.get(url); if (CollectionUtils.isEmptyMap(map)) { continue; } Collection<ChildListener> childListeners = map.values(); if (CollectionUtils.isEmpty(childListeners)) { continue; } if (ANY_VALUE.equals(url.getServiceInterface())) { String root = toRootPath(); childListeners.stream().forEach(childListener -> zkClient.removeChildListener(root, childListener)); } else { for (String path : toCategoriesPath(url)) { childListeners.stream().forEach(childListener -> zkClient.removeChildListener(path, childListener)); } } } zkListeners.clear(); // Just release zkClient reference, but can not close zk client here for zk client is shared somewhere else. // See org.apache.dubbo.remoting.zookeeper.AbstractZookeeperTransporter#destroy() zkClient = null; } private void checkDestroyed() { if (zkClient == null) { throw new IllegalStateException("registry is destroyed"); } } @Override public void doRegister(URL url) { try { checkDestroyed(); zkClient.create(toUrlPath(url), url.getParameter(DYNAMIC_KEY, true), true); } catch (Throwable e) { throw new RpcException( "Failed to register " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } } @Override public void doUnregister(URL url) { try { checkDestroyed(); zkClient.delete(toUrlPath(url)); } catch (Throwable e) { throw new RpcException( "Failed to unregister " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } } @Override public void doSubscribe(final URL url, final NotifyListener listener) { try { checkDestroyed(); if (ANY_VALUE.equals(url.getServiceInterface())) { String root = toRootPath(); boolean check = url.getParameter(CHECK_KEY, false); ConcurrentMap<NotifyListener, ChildListener> listeners = ConcurrentHashMapUtils.computeIfAbsent(zkListeners, url, k -> new ConcurrentHashMap<>()); ChildListener zkListener = ConcurrentHashMapUtils.computeIfAbsent( listeners, listener, k -> (parentPath, currentChildren) -> { for (String child : currentChildren) { try { child = URL.decode(child); if (!(JsonUtils.checkJson(child))) { throw new Exception("dubbo-admin subscribe " + child + " failed, because " + child + "is root path in " + url); } } catch (Exception e) { logger.warn(PROTOCOL_ERROR_DESERIALIZE, "", "", e.getMessage()); } if (!anyServices.contains(child)) { anyServices.add(child); subscribe( url.setPath(child) .addParameters( INTERFACE_KEY, child, Constants.CHECK_KEY, String.valueOf(check)), k); } } }); zkClient.create(root, false, true); List<String> services = zkClient.addChildListener(root, zkListener); if (CollectionUtils.isNotEmpty(services)) { for (String service : services) { service = URL.decode(service); anyServices.add(service); subscribe( url.setPath(service) .addParameters( INTERFACE_KEY, service, Constants.CHECK_KEY, String.valueOf(check)), listener); } } } else { CountDownLatch latch = new CountDownLatch(1); try { List<URL> urls = new ArrayList<>(); /* Iterate over the category value in URL. With default settings, the path variable can be when url is a consumer URL: /dubbo/[service name]/providers, /dubbo/[service name]/configurators /dubbo/[service name]/routers */ for (String path : toCategoriesPath(url)) { ConcurrentMap<NotifyListener, ChildListener> listeners = ConcurrentHashMapUtils.computeIfAbsent( zkListeners, url, k -> new ConcurrentHashMap<>()); ChildListener zkListener = ConcurrentHashMapUtils.computeIfAbsent( listeners, listener, k -> new RegistryChildListenerImpl(url, k, latch)); if (zkListener instanceof RegistryChildListenerImpl) { ((RegistryChildListenerImpl) zkListener).setLatch(latch); } // create "directories". zkClient.create(path, false, true); // Add children (i.e. service items). List<String> children = zkClient.addChildListener(path, zkListener); if (children != null) { // The invocation point that may cause 1-1. urls.addAll(toUrlsWithEmpty(url, path, children)); } } notify(url, listener, urls); } finally { // tells the listener to run only after the sync notification of main thread finishes. latch.countDown(); } } } catch (Throwable e) { throw new RpcException( "Failed to subscribe " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } } @Override public void doUnsubscribe(URL url, NotifyListener listener) { super.doUnsubscribe(url, listener); checkDestroyed(); ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.get(url); if (listeners != null) { ChildListener zkListener = listeners.remove(listener); if (zkListener != null) { if (ANY_VALUE.equals(url.getServiceInterface())) { String root = toRootPath(); zkClient.removeChildListener(root, zkListener); } else { for (String path : toCategoriesPath(url)) { zkClient.removeChildListener(path, zkListener); } } } if (listeners.isEmpty()) { zkListeners.remove(url); } } } @Override public List<URL> lookup(URL url) { if (url == null) { throw new IllegalArgumentException("lookup url == null"); } try { checkDestroyed(); List<String> providers = new ArrayList<>(); for (String path : toCategoriesPath(url)) { List<String> children = zkClient.getChildren(path); if (children != null) { providers.addAll(children); } } return toUrlsWithoutEmpty(url, providers); } catch (Throwable e) { throw new RpcException( "Failed to lookup " + url + " from zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } } private String toRootDir() { if (root.equals(PATH_SEPARATOR)) { return root; } return root + PATH_SEPARATOR; } private String toRootPath() { return root; } private String toServicePath(URL url) { String name = url.getServiceInterface(); if (ANY_VALUE.equals(name)) { return toRootPath(); } return toRootDir() + URL.encode(name); } private String[] toCategoriesPath(URL url) { String[] categories; if (ANY_VALUE.equals(url.getCategory())) { categories = new String[] {PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, CONFIGURATORS_CATEGORY}; } else { categories = url.getCategory(new String[] {DEFAULT_CATEGORY}); } String[] paths = new String[categories.length]; for (int i = 0; i < categories.length; i++) { paths[i] = toServicePath(url) + PATH_SEPARATOR + categories[i]; } return paths; } private String toCategoryPath(URL url) { return toServicePath(url) + PATH_SEPARATOR + url.getCategory(DEFAULT_CATEGORY); } private String toUrlPath(URL url) { return toCategoryPath(url) + PATH_SEPARATOR + URL.encode(url.toFullString()); } /** * When zookeeper connection recovered from a connection loss, it needs to fetch the latest provider list. * re-register watcher is only a side effect and is not mandate. */ private void fetchLatestAddresses() { // subscribe Map<URL, Set<NotifyListener>> recoverSubscribed = new HashMap<>(getSubscribed()); if (!recoverSubscribed.isEmpty()) { if (logger.isInfoEnabled()) { logger.info("Fetching the latest urls of " + recoverSubscribed.keySet()); } for (Map.Entry<URL, Set<NotifyListener>> entry : recoverSubscribed.entrySet()) { URL url = entry.getKey(); for (NotifyListener listener : entry.getValue()) { removeFailedSubscribed(url, listener); addFailedSubscribed(url, listener); } } } } @Override protected boolean isMatch(URL subscribeUrl, URL providerUrl) { return UrlUtils.isMatch(subscribeUrl, providerUrl); } /** * Triggered when children get changed. It will be invoked by implementation of CuratorWatcher. * <p> * 'org.apache.dubbo.remoting.zookeeper.curator5.Curator5ZookeeperClient.CuratorWatcherImpl' (Curator 5) */ private class RegistryChildListenerImpl implements ChildListener { private final ZookeeperRegistryNotifier notifier; private volatile CountDownLatch latch; public RegistryChildListenerImpl(URL consumerUrl, NotifyListener listener, CountDownLatch latch) { this.latch = latch; this.notifier = new ZookeeperRegistryNotifier(consumerUrl, listener, ZookeeperRegistry.this.getDelay()); } public void setLatch(CountDownLatch latch) { this.latch = latch; } @Override public void childChanged(String path, List<String> children) { // Notify 'notifiers' one by one. try { latch.await(); } catch (InterruptedException e) { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Zookeeper children listener thread was interrupted unexpectedly, may cause race condition with the main thread."); } notifier.notify(path, children); } } /** * Customized Registry Notifier for zookeeper registry. */ public class ZookeeperRegistryNotifier { private long lastExecuteTime; private final URL consumerUrl; private final NotifyListener listener; private final long delayTime; public ZookeeperRegistryNotifier(URL consumerUrl, NotifyListener listener, long delayTime) { this.consumerUrl = consumerUrl; this.listener = listener; this.delayTime = delayTime; } public void notify(String path, Object rawAddresses) { // notify immediately if it's notification of governance rules. if (path.endsWith(CONFIGURATORS_CATEGORY) || path.endsWith(ROUTERS_CATEGORY)) { this.doNotify(path, rawAddresses); } // if address notification, check if delay is necessary. if (delayTime <= 0) { this.doNotify(path, rawAddresses); } else { long interval = delayTime - (System.currentTimeMillis() - lastExecuteTime); if (interval > 0) { try { Thread.sleep(interval); } catch (InterruptedException e) { // ignore } } lastExecuteTime = System.currentTimeMillis(); this.doNotify(path, rawAddresses); } } protected void doNotify(String path, Object rawAddresses) { ZookeeperRegistry.this.notify( consumerUrl, listener, ZookeeperRegistry.this.toUrlsWithEmpty(consumerUrl, path, (List<String>) rawAddresses)); } } }
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-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java
dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.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.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.function.ThrowableConsumer; import org.apache.dubbo.common.function.ThrowableFunction; 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.registry.client.AbstractServiceDiscovery; 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.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; import java.io.IOException; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.x.discovery.ServiceCache; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; import static org.apache.dubbo.common.function.ThrowableFunction.execute; 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.zookeeper.util.CuratorFrameworkUtils.build; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.buildCuratorFramework; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.buildServiceDiscovery; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.getRootPath; import static org.apache.dubbo.rpc.RpcException.REGISTRY_EXCEPTION; /** * Zookeeper {@link ServiceDiscovery} implementation based on * <a href="https://curator.apache.org/curator-x-discovery/index.html">Apache Curator X Discovery</a> * <p> * TODO, replace curator CuratorFramework with dubbo ZookeeperClient */ public class ZookeeperServiceDiscovery extends AbstractServiceDiscovery { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); public static final String DEFAULT_GROUP = "/services"; private final CuratorFramework curatorFramework; private final String rootPath; private final org.apache.curator.x.discovery.ServiceDiscovery<ZookeeperInstance> serviceDiscovery; /** * The Key is watched Zookeeper path, the value is an instance of {@link CuratorWatcher} */ private final ConcurrentHashMap<String, ZookeeperServiceDiscoveryChangeWatcher> watcherCaches = new ConcurrentHashMap<>(); public ZookeeperServiceDiscovery(ApplicationModel applicationModel, URL registryURL) { super(applicationModel, registryURL); try { this.curatorFramework = buildCuratorFramework(registryURL, this); this.rootPath = getRootPath(registryURL); this.serviceDiscovery = buildServiceDiscovery(curatorFramework, rootPath); this.serviceDiscovery.start(); } catch (Exception e) { throw new IllegalStateException("Create zookeeper service discovery failed.", e); } } @Override public void doDestroy() throws Exception { serviceDiscovery.close(); curatorFramework.close(); watcherCaches.clear(); } @Override public void doRegister(ServiceInstance serviceInstance) { try { serviceDiscovery.registerService(build(serviceInstance)); } catch (Exception e) { throw new RpcException(REGISTRY_EXCEPTION, "Failed register instance " + serviceInstance.toString(), e); } } @Override public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException { if (serviceInstance != null) { doInServiceRegistry(serviceDiscovery -> serviceDiscovery.unregisterService(build(serviceInstance))); } } @Override protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) throws RuntimeException { if (EMPTY_REVISION.equals(getExportedServicesRevision(newServiceInstance)) || EMPTY_REVISION.equals( oldServiceInstance.getMetadata().get(EXPORTED_SERVICES_REVISION_PROPERTY_NAME))) { super.doUpdate(oldServiceInstance, newServiceInstance); return; } org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance> oldInstance = build(oldServiceInstance); org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance> newInstance = build(newServiceInstance); if (!Objects.equals(newInstance.getName(), oldInstance.getName()) || !Objects.equals(newInstance.getId(), oldInstance.getId())) { // Ignore if id changed. Should unregister first. super.doUpdate(oldServiceInstance, newServiceInstance); return; } try { this.serviceInstance = newServiceInstance; reportMetadata(newServiceInstance.getServiceMetadata()); serviceDiscovery.updateService(newInstance); } catch (Exception e) { throw new RpcException(REGISTRY_EXCEPTION, "Failed register instance " + newServiceInstance.toString(), e); } } @Override public Set<String> getServices() { return doInServiceDiscovery(s -> new LinkedHashSet<>(s.queryForNames())); } @Override public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException { return doInServiceDiscovery(s -> build(registryURL, s.queryForInstances(serviceName))); } @Override public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { // check if listener has already been added through another interface/service if (!instanceListeners.add(listener)) { return; } listener.getServiceNames().forEach(serviceName -> registerServiceWatcher(serviceName, listener)); } @Override public void removeServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws IllegalArgumentException { if (!instanceListeners.remove(listener)) { return; } listener.getServiceNames().forEach(serviceName -> { ZookeeperServiceDiscoveryChangeWatcher watcher = watcherCaches.get(serviceName); if (watcher != null) { watcher.getListeners().remove(listener); if (watcher.getListeners().isEmpty()) { watcherCaches.remove(serviceName); try { watcher.getCacheInstance().close(); } catch (IOException e) { logger.error( REGISTRY_ZOOKEEPER_EXCEPTION, "curator stop watch failed", "", "Curator Stop service discovery watch failed. Service Name: " + serviceName); } } } }); } @Override public boolean isAvailable() { // Fix the issue of timeout for all calls to the isAvailable method after the zookeeper is disconnected return !isDestroy() && isConnected() && CollectionUtils.isNotEmpty(getServices()); } private boolean isConnected() { if (curatorFramework == null || curatorFramework.getZookeeperClient() == null) { return false; } return curatorFramework.getZookeeperClient().isConnected(); } private void doInServiceRegistry(ThrowableConsumer<org.apache.curator.x.discovery.ServiceDiscovery> consumer) { ThrowableConsumer.execute(serviceDiscovery, s -> consumer.accept(s)); } private <R> R doInServiceDiscovery(ThrowableFunction<org.apache.curator.x.discovery.ServiceDiscovery, R> function) { return execute(serviceDiscovery, function); } protected void registerServiceWatcher(String serviceName, ServiceInstancesChangedListener listener) { CountDownLatch latch = new CountDownLatch(1); ZookeeperServiceDiscoveryChangeWatcher watcher = ConcurrentHashMapUtils.computeIfAbsent(watcherCaches, serviceName, name -> { ServiceCache<ZookeeperInstance> serviceCache = serviceDiscovery.serviceCacheBuilder().name(name).build(); ZookeeperServiceDiscoveryChangeWatcher newer = new ZookeeperServiceDiscoveryChangeWatcher(this, serviceCache, name, latch); serviceCache.addListener(newer); try { serviceCache.start(); } catch (Exception e) { throw new RpcException(REGISTRY_EXCEPTION, "Failed subscribe service: " + name, e); } return newer; }); watcher.addListener(listener); listener.onEvent(new ServiceInstancesChangedEvent(serviceName, this.getInstances(serviceName))); latch.countDown(); } }
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-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryFactory.java
dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryFactory.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.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.AbstractServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceDiscovery; public class ZookeeperServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory { @Override protected ServiceDiscovery createDiscovery(URL registryURL) { return new ZookeeperServiceDiscovery(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-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryFactory.java
dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryFactory.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.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.DisableInject; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.support.AbstractRegistryFactory; import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClientManager; import org.apache.dubbo.rpc.model.ApplicationModel; /** * ZookeeperRegistryFactory. */ public class ZookeeperRegistryFactory extends AbstractRegistryFactory { private ZookeeperClientManager zookeeperClientManager; // for compatible usage public ZookeeperRegistryFactory() { this(ApplicationModel.defaultModel()); } public ZookeeperRegistryFactory(ApplicationModel applicationModel) { this.applicationModel = applicationModel; this.zookeeperClientManager = ZookeeperClientManager.getInstance(applicationModel); } @DisableInject public void setZookeeperTransporter(ZookeeperClientManager zookeeperClientManager) { this.zookeeperClientManager = zookeeperClientManager; } @Override public Registry createRegistry(URL url) { return new ZookeeperRegistry(url, zookeeperClientManager); } }
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-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java
dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.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.zookeeper.util; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.ServiceInstance; import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.apache.curator.framework.CuratorFramework; import static org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscovery.DEFAULT_GROUP; /** * The enumeration for the parameters of {@link CuratorFramework} * * @see CuratorFramework * @since 2.7.5 */ public enum CuratorFrameworkParams { /** * The root path of Dubbo Service */ ROOT_PATH("rootPath", DEFAULT_GROUP, value -> value), GROUP_PATH("group", DEFAULT_GROUP, value -> value), /** * The host of current {@link ServiceInstance service instance} that will be registered */ INSTANCE_HOST("instanceHost", null, value -> value), /** * The port of current {@link ServiceInstance service instance} that will be registered */ INSTANCE_PORT("instancePort", null, value -> value), /** * Initial amount of time to wait between retries */ BASE_SLEEP_TIME("baseSleepTimeMs", 50, Integer::valueOf), /** * Max number of times to retry. */ MAX_RETRIES("maxRetries", 10, Integer::valueOf), /** * Max time in ms to sleep on each retry. */ MAX_SLEEP("maxSleepMs", 500, Integer::valueOf), /** * Wait time to block on connection to Zookeeper. */ BLOCK_UNTIL_CONNECTED_WAIT("blockUntilConnectedWait", 10, Integer::valueOf), /** * The unit of time related to blocking on connection to Zookeeper. */ BLOCK_UNTIL_CONNECTED_UNIT("blockUntilConnectedUnit", TimeUnit.SECONDS, TimeUnit::valueOf), ; private final String name; private final Object defaultValue; private final Function<String, Object> converter; <T> CuratorFrameworkParams(String name, T defaultValue, Function<String, T> converter) { this.name = name; this.defaultValue = defaultValue; this.converter = (Function<String, Object>) converter; } /** * Get the parameter value from the specified {@link URL} * * @param url the Dubbo registry {@link URL} * @param <T> the type of value * @return the parameter value if present, or return <code>null</code> */ public <T> T getParameterValue(URL url) { String param = url.getParameter(name); Object value = param != null ? converter.apply(param) : defaultValue; return (T) value; } }
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-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java
dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.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.zookeeper.util; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.zookeeper.ZookeeperInstance; import org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscovery; import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.CuratorFrameworkFactory.Builder; import org.apache.curator.framework.api.ACLProvider; import org.apache.curator.framework.imps.CuratorFrameworkState; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.ServiceInstanceBuilder; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import static org.apache.curator.x.discovery.ServiceInstance.builder; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.SESSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ZOOKEEPER_ENSEMBLE_TRACKER_KEY; import static org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscovery.DEFAULT_GROUP; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.BASE_SLEEP_TIME; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.BLOCK_UNTIL_CONNECTED_UNIT; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.BLOCK_UNTIL_CONNECTED_WAIT; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.GROUP_PATH; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.MAX_RETRIES; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.MAX_SLEEP; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.ROOT_PATH; /** * Curator Framework Utilities Class * * @since 2.7.5 */ public abstract class CuratorFrameworkUtils { protected static int DEFAULT_SESSION_TIMEOUT_MS = 60 * 1000; public static ServiceDiscovery<ZookeeperInstance> buildServiceDiscovery( CuratorFramework curatorFramework, String basePath) { return ServiceDiscoveryBuilder.builder(ZookeeperInstance.class) .client(curatorFramework) .basePath(basePath) .build(); } public static CuratorFramework buildCuratorFramework(URL connectionURL, ZookeeperServiceDiscovery serviceDiscovery) throws Exception { int sessionTimeoutMs = connectionURL.getParameter(SESSION_KEY, DEFAULT_SESSION_TIMEOUT_MS); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() .connectString(connectionURL.getBackupAddress()) .sessionTimeoutMs(sessionTimeoutMs) .retryPolicy(buildRetryPolicy(connectionURL)); try { // use reflect to check method exist to compatibility with curator4, can remove in dubbo3.3 and direct call // the method because 3.3 only supported curator5 Class<? extends Builder> builderClass = builder.getClass(); Method ignore = builderClass.getMethod("ensembleTracker", boolean.class); boolean ensembleTrackerFlag = connectionURL.getParameter(ZOOKEEPER_ENSEMBLE_TRACKER_KEY, true); builder.ensembleTracker(ensembleTrackerFlag); } catch (Throwable ignore) { } String userInformation = connectionURL.getUserInformation(); if (StringUtils.isNotEmpty(userInformation)) { builder = builder.authorization("digest", userInformation.getBytes(StandardCharsets.UTF_8)); builder.aclProvider(new ACLProvider() { @Override public List<ACL> getDefaultAcl() { return ZooDefs.Ids.CREATOR_ALL_ACL; } @Override public List<ACL> getAclForPath(String path) { return ZooDefs.Ids.CREATOR_ALL_ACL; } }); } CuratorFramework curatorFramework = builder.build(); curatorFramework.start(); curatorFramework.blockUntilConnected( BLOCK_UNTIL_CONNECTED_WAIT.getParameterValue(connectionURL), BLOCK_UNTIL_CONNECTED_UNIT.getParameterValue(connectionURL)); if (!curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { throw new IllegalStateException("zookeeper client initialization failed"); } boolean check = UrlUtils.isCheck(connectionURL); if (check && !curatorFramework.getZookeeperClient().isConnected()) { throw new IllegalStateException("failed to connect to zookeeper server"); } return curatorFramework; } public static RetryPolicy buildRetryPolicy(URL connectionURL) { int baseSleepTimeMs = BASE_SLEEP_TIME.getParameterValue(connectionURL); int maxRetries = MAX_RETRIES.getParameterValue(connectionURL); int getMaxSleepMs = MAX_SLEEP.getParameterValue(connectionURL); return new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries, getMaxSleepMs); } public static List<ServiceInstance> build( URL registryUrl, Collection<org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance>> instances) { return instances.stream().map((i) -> build(registryUrl, i)).collect(Collectors.toList()); } public static ServiceInstance build( URL registryUrl, org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance> instance) { String name = instance.getName(); String host = instance.getAddress(); int port = instance.getPort(); ZookeeperInstance zookeeperInstance = instance.getPayload(); DefaultServiceInstance serviceInstance = new DefaultServiceInstance( name, host, port, ScopeModelUtil.getApplicationModel(registryUrl.getScopeModel())); serviceInstance.setMetadata(zookeeperInstance.getMetadata()); return serviceInstance; } public static org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance> build( ServiceInstance serviceInstance) { ServiceInstanceBuilder builder; String serviceName = serviceInstance.getServiceName(); String host = serviceInstance.getHost(); int port = serviceInstance.getPort(); Map<String, String> metadata = serviceInstance.getSortedMetadata(); String id = generateId(host, port); ZookeeperInstance zookeeperInstance = new ZookeeperInstance(id, serviceName, metadata); try { builder = builder().id(id).name(serviceName).address(host).port(port).payload(zookeeperInstance); } catch (Exception e) { throw new RuntimeException(e); } return builder.build(); } public static String generateId(String host, int port) { return host + ":" + port; } public static String getRootPath(URL registryURL) { String group = ROOT_PATH.getParameterValue(registryURL); if (group.equalsIgnoreCase(DEFAULT_GROUP)) { group = GROUP_PATH.getParameterValue(registryURL); if (!group.startsWith(PATH_SEPARATOR)) { group = PATH_SEPARATOR + group; } } return 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-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/aot/ZookeeperReflectionTypeDescriberRegistrar.java
dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/aot/ZookeeperReflectionTypeDescriberRegistrar.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.zookeeper.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.zookeeper.ZookeeperInstance; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ZookeeperReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar { @Override public List<TypeDescriber> getTypeDescribers() { List<TypeDescriber> typeDescribers = new ArrayList<>(); typeDescribers.add(buildTypeDescriberWithDeclared(ZookeeperInstance.class)); return typeDescribers; } private TypeDescriber buildTypeDescriberWithDeclared(Class<?> cl) { Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); memberCategories.add(MemberCategory.DECLARED_FIELDS); 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-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistryTestUtil.java
dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistryTestUtil.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.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.registry.ListenerRegistryWrapper; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.zookeeper.ZookeeperRegistry; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; 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.DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; /** * 2019-05-13 */ public class MultipleRegistryTestUtil { public static ZookeeperRegistry getZookeeperRegistry(Collection<Registry> registryCollection) { for (Registry registry : registryCollection) { if (registry instanceof ListenerRegistryWrapper) { registry = ((ListenerRegistryWrapper) registry).getRegistry(); } if (registry instanceof ZookeeperRegistry) { return (ZookeeperRegistry) registry; } } return null; } /** * copy from @org.apache.dubbo.registry.integration.RegistryDirectory#notify(java.util.List) * * @param urls * @return */ public static List<URL> getProviderURLsFromNotifyURLS(List<URL> urls) { Map<String, List<URL>> categoryUrls = urls.stream() .filter(Objects::nonNull) .filter(MultipleRegistryTestUtil::isValidCategory) .filter(MultipleRegistryTestUtil::isNotCompatibleFor26x) .collect(Collectors.groupingBy(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 ""; })); // providers List<URL> providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList()); return providerURLs; } private static boolean isValidCategory(URL url) { String category = url.getCategory(DEFAULT_CATEGORY); if ((ROUTERS_CATEGORY.equals(category) || ROUTE_PROTOCOL.equals(url.getProtocol())) || PROVIDERS_CATEGORY.equals(category) || CONFIGURATORS_CATEGORY.equals(category) || DYNAMIC_CONFIGURATORS_CATEGORY.equals(category) || APP_DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)) { return true; } return false; } private static boolean isNotCompatibleFor26x(URL url) { return StringUtils.isEmpty(url.getParameter(COMPATIBLE_CONFIG_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-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscoveryTest.java
dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscoveryTest.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.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.Assert; 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.config.ApplicationConfig; import org.apache.dubbo.metadata.MetadataInfo; import org.apache.dubbo.registry.client.DefaultServiceInstance; 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.event.listener.ServiceInstancesChangedListener; 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.List; import java.util.Map; import com.google.common.collect.Sets; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME; public class MultipleServiceDiscoveryTest { private static String zookeeperConnectionAddress1, zookeeperConnectionAddress2; @Test public void testOnEvent() { try { 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\"}}" + "}}"; MetadataInfo metadataInfo = JsonUtils.toJavaObject(metadata_111, MetadataInfo.class); ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("app2")); zookeeperConnectionAddress1 = "multiple://127.0.0.1:2181?reference-registry=127.0.0.1:2181?enableEmptyProtection=false&child.a1=zookeeper://127.0.0.1:2181"; 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"); URL url = URL.valueOf(zookeeperConnectionAddress1); url.setScopeModel(applicationModel); MultipleServiceDiscovery multipleServiceDiscovery = new MultipleServiceDiscovery(url); Class<MultipleServiceDiscovery> multipleServiceDiscoveryClass = MultipleServiceDiscovery.class; Field serviceDiscoveries = multipleServiceDiscoveryClass.getDeclaredField("serviceDiscoveries"); serviceDiscoveries.setAccessible(true); ServiceDiscovery serviceDiscoveryMock = Mockito.mock(ServiceDiscovery.class); Mockito.when(serviceDiscoveryMock.getRemoteMetadata(Mockito.anyString(), Mockito.anyList())) .thenReturn(metadataInfo); serviceDiscoveries.set( multipleServiceDiscovery, Collections.singletonMap("child.a1", serviceDiscoveryMock)); MultipleServiceDiscovery.MultiServiceInstancesChangedListener listener = (MultipleServiceDiscovery.MultiServiceInstancesChangedListener) multipleServiceDiscovery.createListener(Sets.newHashSet("app1")); multipleServiceDiscovery.addServiceInstancesChangedListener(listener); MultipleServiceDiscovery.SingleServiceInstancesChangedListener singleServiceInstancesChangedListener = listener.getAndComputeIfAbsent("child.a1", (a1) -> null); Assert.notNull( singleServiceInstancesChangedListener, "singleServiceInstancesChangedListener can not be null"); singleServiceInstancesChangedListener.onEvent( new ServiceInstancesChangedEvent("app1", buildInstances(urlsSameRevision))); Mockito.verify(serviceDiscoveryMock, Mockito.times(1)) .getRemoteMetadata(Mockito.anyString(), Mockito.anyList()); Field serviceUrlsField = ServiceInstancesChangedListener.class.getDeclaredField("serviceUrls"); serviceUrlsField.setAccessible(true); Map<String, List<ServiceInstancesChangedListener.ProtocolServiceKeyWithUrls>> map = (Map<String, List<ServiceInstancesChangedListener.ProtocolServiceKeyWithUrls>>) serviceUrlsField.get(listener); Assert.assertTrue(!CollectionUtils.isEmptyMap(map), "url can not be empty"); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } static List<ServiceInstance> buildInstances(List<Object> rawURls) { List<ServiceInstance> instances = new ArrayList<>(); for (Object obj : rawURls) { String rawURL = (String) obj; DefaultServiceInstance instance = new DefaultServiceInstance(); final URL dubboUrl = URL.valueOf(rawURL); instance.setRawAddress(rawURL); instance.setHost(dubboUrl.getHost()); instance.setEnabled(true); instance.setHealthy(true); instance.setPort(dubboUrl.getPort()); instance.setRegistryCluster("default"); instance.setApplicationModel(ApplicationModel.defaultModel()); Map<String, String> metadata = new HashMap<>(); if (StringUtils.isNotEmpty(dubboUrl.getParameter(REVISION_KEY))) { metadata.put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, dubboUrl.getParameter(REVISION_KEY)); } instance.setMetadata(metadata); instances.add(instance); } return instances; } }
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-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java
dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.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.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.zookeeper.ZookeeperRegistry; import org.apache.dubbo.remoting.zookeeper.curator5.Curator5ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClient; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; /** * 2019-04-30 */ class MultipleRegistry2S2RTest { private static final String SERVICE_NAME = "org.apache.dubbo.registry.MultipleService2S2R"; private static final String SERVICE2_NAME = "org.apache.dubbo.registry.MultipleService2S2R2"; private static MultipleRegistry multipleRegistry; // for test content private static ZookeeperClient zookeeperClient; private static ZookeeperClient zookeeperClient2; private static ZookeeperRegistry zookeeperRegistry; private static ZookeeperRegistry zookeeperRegistry2; private static String zookeeperConnectionAddress1, zookeeperConnectionAddress2; @BeforeAll public static void beforeAll() { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); zookeeperConnectionAddress2 = System.getProperty("zookeeper.connection.address.2"); URL url = URL.valueOf("multiple://127.0.0.1?application=vic&enable-empty-protection=false&" + MultipleRegistry.REGISTRY_FOR_SERVICE + "=" + zookeeperConnectionAddress1 + "," + zookeeperConnectionAddress2 + "&" + MultipleRegistry.REGISTRY_FOR_REFERENCE + "=" + zookeeperConnectionAddress1 + "," + zookeeperConnectionAddress2); multipleRegistry = (MultipleRegistry) new MultipleRegistryFactory().createRegistry(url); // for test validation zookeeperClient = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress1)); zookeeperRegistry = MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getServiceRegistries().values()); zookeeperClient2 = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress2)); zookeeperRegistry2 = MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getServiceRegistries().values()); } @Test void testParamConfig() { Assertions.assertEquals(2, multipleRegistry.origReferenceRegistryURLs.size()); Assertions.assertTrue(multipleRegistry.origReferenceRegistryURLs.contains(zookeeperConnectionAddress1)); Assertions.assertTrue(multipleRegistry.origReferenceRegistryURLs.contains(zookeeperConnectionAddress2)); Assertions.assertEquals(2, multipleRegistry.origServiceRegistryURLs.size()); Assertions.assertTrue(multipleRegistry.origServiceRegistryURLs.contains(zookeeperConnectionAddress1)); Assertions.assertTrue(multipleRegistry.origServiceRegistryURLs.contains(zookeeperConnectionAddress2)); Assertions.assertEquals(2, multipleRegistry.effectReferenceRegistryURLs.size()); Assertions.assertTrue(multipleRegistry.effectReferenceRegistryURLs.contains(zookeeperConnectionAddress1)); Assertions.assertTrue(multipleRegistry.effectReferenceRegistryURLs.contains(zookeeperConnectionAddress2)); Assertions.assertEquals(2, multipleRegistry.effectServiceRegistryURLs.size()); Assertions.assertTrue(multipleRegistry.effectServiceRegistryURLs.contains(zookeeperConnectionAddress1)); Assertions.assertTrue(multipleRegistry.effectServiceRegistryURLs.contains(zookeeperConnectionAddress2)); Assertions.assertTrue(multipleRegistry.getServiceRegistries().containsKey(zookeeperConnectionAddress1)); Assertions.assertTrue(multipleRegistry.getServiceRegistries().containsKey(zookeeperConnectionAddress2)); Assertions.assertEquals( 2, multipleRegistry.getServiceRegistries().values().size()); // java.util.Iterator<Registry> registryIterable = // multipleRegistry.getServiceRegistries().values().iterator(); // Registry firstRegistry = registryIterable.next(); // Registry secondRegistry = registryIterable.next(); Assertions.assertNotNull(MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getServiceRegistries().values())); Assertions.assertNotNull(MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getReferenceRegistries().values())); Assertions.assertEquals( MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getServiceRegistries().values()), MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getReferenceRegistries().values())); Assertions.assertEquals( MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getServiceRegistries().values()), MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getReferenceRegistries().values())); Assertions.assertEquals(multipleRegistry.getApplicationName(), "vic"); Assertions.assertTrue(multipleRegistry.isAvailable()); } @Test void testRegistryAndUnRegistry() throws InterruptedException { URL serviceUrl = URL.valueOf( "http2://multiple/" + SERVICE_NAME + "?notify=false&methods=test1,test2&category=providers"); // URL serviceUrl2 = URL.valueOf("http2://multiple2/" + SERVICE_NAME + // "?notify=false&methods=test1,test2&category=providers"); multipleRegistry.register(serviceUrl); String path = "/dubbo/" + SERVICE_NAME + "/providers"; List<String> providerList = zookeeperClient.getChildren(path); Assertions.assertTrue(!providerList.isEmpty()); final List<URL> list = new ArrayList<URL>(); multipleRegistry.subscribe(serviceUrl, new NotifyListener() { @Override public void notify(List<URL> urls) { list.clear(); list.addAll(urls); } }); Thread.sleep(1500); Assertions.assertEquals(2, list.size()); multipleRegistry.unregister(serviceUrl); Thread.sleep(1500); Assertions.assertEquals(1, list.size()); List<URL> urls = MultipleRegistryTestUtil.getProviderURLsFromNotifyURLS(list); Assertions.assertEquals(1, list.size()); Assertions.assertEquals("empty", list.get(0).getProtocol()); } @Test void testSubscription() throws InterruptedException { URL serviceUrl = URL.valueOf( "http2://multiple/" + SERVICE2_NAME + "?notify=false&methods=test1,test2&category=providers"); // URL serviceUrl2 = URL.valueOf("http2://multiple2/" + SERVICE_NAME + // "?notify=false&methods=test1,test2&category=providers"); multipleRegistry.register(serviceUrl); String path = "/dubbo/" + SERVICE2_NAME + "/providers"; List<String> providerList = zookeeperClient.getChildren(path); Assumptions.assumeTrue(!providerList.isEmpty()); final List<URL> list = new ArrayList<URL>(); multipleRegistry.subscribe(serviceUrl, new NotifyListener() { @Override public void notify(List<URL> urls) { list.clear(); list.addAll(urls); } }); Thread.sleep(1500); Assertions.assertEquals(2, list.size()); List<Registry> serviceRegistries = new ArrayList<Registry>(multipleRegistry.getServiceRegistries().values()); serviceRegistries.get(0).unregister(serviceUrl); Thread.sleep(1500); Assertions.assertEquals(1, list.size()); List<URL> urls = MultipleRegistryTestUtil.getProviderURLsFromNotifyURLS(list); Assertions.assertEquals(1, list.size()); Assertions.assertTrue(!"empty".equals(list.get(0).getProtocol())); serviceRegistries.get(1).unregister(serviceUrl); Thread.sleep(1500); Assertions.assertEquals(1, list.size()); urls = MultipleRegistryTestUtil.getProviderURLsFromNotifyURLS(list); Assertions.assertEquals(1, list.size()); Assertions.assertEquals("empty", list.get(0).getProtocol()); } @Test void testAggregation() { List<URL> result = new ArrayList<URL>(); List<URL> listToAggregate = new ArrayList<URL>(); URL url1 = URL.valueOf("dubbo://127.0.0.1:20880/service1"); URL url2 = URL.valueOf("dubbo://127.0.0.1:20880/service1"); listToAggregate.add(url1); listToAggregate.add(url2); URL registryURL = URL.valueOf( "mock://127.0.0.1/RegistryService?attachments=zone=hangzhou,tag=middleware&enable-empty-protection=false"); MultipleRegistry.MultipleNotifyListenerWrapper.aggregateRegistryUrls(result, listToAggregate, registryURL); Assertions.assertEquals(2, result.size()); Assertions.assertEquals(2, result.get(0).getParameters().size()); Assertions.assertEquals("hangzhou", result.get(0).getParameter("zone")); Assertions.assertEquals("middleware", result.get(1).getParameter("tag")); } }
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-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistryFactory.java
dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistryFactory.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.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.support.AbstractRegistryFactory; public class MultipleRegistryFactory extends AbstractRegistryFactory { @Override protected Registry createRegistry(URL url) { return new MultipleRegistry(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-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscoveryFactory.java
dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscoveryFactory.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.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.AbstractServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceDiscovery; public class MultipleServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory { @Override protected ServiceDiscovery createDiscovery(URL registryURL) { return new MultipleServiceDiscovery(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-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java
dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.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.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.Logger; 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.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.support.AbstractRegistry; import java.util.ArrayList; 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.stream.Collectors; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; public class MultipleRegistry extends AbstractRegistry { public static final Logger LOGGER = LoggerFactory.getLogger(MultipleRegistry.class); public static final String REGISTRY_FOR_SERVICE = "service-registry"; public static final String REGISTRY_FOR_REFERENCE = "reference-registry"; public static final String REGISTRY_SEPARATOR = "separator"; private final Map<String, Registry> serviceRegistries = new ConcurrentHashMap<>(4); private final Map<String, Registry> referenceRegistries = new ConcurrentHashMap<>(4); private final Map<NotifyListener, MultipleNotifyListenerWrapper> multipleNotifyListenerMap = new ConcurrentHashMap<>(32); private final URL registryUrl; private final String applicationName; protected RegistryFactory registryFactory; protected List<String> origServiceRegistryURLs; protected List<String> origReferenceRegistryURLs; protected List<String> effectServiceRegistryURLs; protected List<String> effectReferenceRegistryURLs; public MultipleRegistry(URL url) { this(url, true, true); boolean defaultRegistry = url.getParameter(CommonConstants.DEFAULT_KEY, true); if (defaultRegistry && effectServiceRegistryURLs.isEmpty() && effectReferenceRegistryURLs.isEmpty()) { throw new IllegalArgumentException("Illegal registry url. You need to configure parameter " + REGISTRY_FOR_SERVICE + " or " + REGISTRY_FOR_REFERENCE); } } public MultipleRegistry(URL url, boolean initServiceRegistry, boolean initReferenceRegistry) { super(url); this.registryUrl = url; this.applicationName = url.getApplication(); this.registryFactory = url.getOrDefaultApplicationModel() .getExtensionLoader(RegistryFactory.class) .getAdaptiveExtension(); init(); checkApplicationName(this.applicationName); // This urls contain parameter, and it does not inherit from the parameter of url in MultipleRegistry Map<String, Registry> registryMap = new HashMap<>(); if (initServiceRegistry) { initServiceRegistry(url, registryMap); } if (initReferenceRegistry) { initReferenceRegistry(url, registryMap); } } protected void initServiceRegistry(URL url, Map<String, Registry> registryMap) { String serviceRegistryString = url.getParameter(REGISTRY_FOR_SERVICE); char separator = url.getParameter(REGISTRY_SEPARATOR, COMMA_SEPARATOR).charAt(0); origServiceRegistryURLs = StringUtils.splitToList(serviceRegistryString, separator); effectServiceRegistryURLs = this.filterServiceRegistry(origServiceRegistryURLs); for (String tmpUrl : effectServiceRegistryURLs) { if (registryMap.get(tmpUrl) != null) { serviceRegistries.put(tmpUrl, registryMap.get(tmpUrl)); continue; } final URL registryUrl = URL.valueOf(tmpUrl) .addParametersIfAbsent(url.getParameters()) .addParameterIfAbsent(CHECK_KEY, url.getParameter(CHECK_KEY, "true")); Registry registry = registryFactory.getRegistry(registryUrl); registryMap.put(tmpUrl, registry); serviceRegistries.put(tmpUrl, registry); } } protected void initReferenceRegistry(URL url, Map<String, Registry> registryMap) { String serviceRegistryString = url.getParameter(REGISTRY_FOR_REFERENCE); char separator = url.getParameter(REGISTRY_SEPARATOR, COMMA_SEPARATOR).charAt(0); origReferenceRegistryURLs = StringUtils.splitToList(serviceRegistryString, separator); effectReferenceRegistryURLs = this.filterReferenceRegistry(origReferenceRegistryURLs); for (String tmpUrl : effectReferenceRegistryURLs) { if (registryMap.get(tmpUrl) != null) { referenceRegistries.put(tmpUrl, registryMap.get(tmpUrl)); continue; } final URL registryUrl = URL.valueOf(tmpUrl) .addParametersIfAbsent(url.getParameters()) .addParameterIfAbsent(CHECK_KEY, url.getParameter(CHECK_KEY, "true")); Registry registry = registryFactory.getRegistry(registryUrl); registryMap.put(tmpUrl, registry); referenceRegistries.put(tmpUrl, registry); } } @Override public URL getUrl() { return registryUrl; } @Override public boolean isAvailable() { boolean available = serviceRegistries.isEmpty(); for (Registry serviceRegistry : serviceRegistries.values()) { if (serviceRegistry.isAvailable()) { available = true; } } if (!available) { return false; } available = referenceRegistries.isEmpty(); for (Registry referenceRegistry : referenceRegistries.values()) { if (referenceRegistry.isAvailable()) { available = true; } } if (!available) { return false; } return true; } @Override public void destroy() { Set<Registry> registries = new HashSet<>(serviceRegistries.values()); registries.addAll(referenceRegistries.values()); for (Registry registry : registries) { registry.destroy(); } } @Override public void register(URL url) { super.register(url); for (Registry registry : serviceRegistries.values()) { registry.register(url); } } @Override public void unregister(URL url) { super.unregister(url); for (Registry registry : serviceRegistries.values()) { registry.unregister(url); } } @Override public void subscribe(URL url, NotifyListener listener) { MultipleNotifyListenerWrapper multipleNotifyListenerWrapper = new MultipleNotifyListenerWrapper(listener); multipleNotifyListenerMap.put(listener, multipleNotifyListenerWrapper); for (Registry registry : referenceRegistries.values()) { SingleNotifyListener singleNotifyListener = new SingleNotifyListener(multipleNotifyListenerWrapper, registry); multipleNotifyListenerWrapper.putRegistryMap(registry.getUrl(), singleNotifyListener); registry.subscribe(url, singleNotifyListener); } super.subscribe(url, multipleNotifyListenerWrapper); } @Override public void unsubscribe(URL url, NotifyListener listener) { MultipleNotifyListenerWrapper notifyListener = multipleNotifyListenerMap.remove(listener); for (Registry registry : referenceRegistries.values()) { SingleNotifyListener singleNotifyListener = notifyListener.registryMap.get(registry.getUrl()); registry.unsubscribe(url, singleNotifyListener); } if (notifyListener != null) { super.unsubscribe(url, notifyListener); notifyListener.destroy(); } } @Override public List<URL> lookup(URL url) { List<URL> urls = new ArrayList<>(); for (Registry registry : referenceRegistries.values()) { List<URL> tmpUrls = registry.lookup(url); if (!CollectionUtils.isEmpty(tmpUrls)) { urls.addAll(tmpUrls); } } return urls.stream().distinct().collect(Collectors.toList()); } protected void init() {} protected List<String> filterServiceRegistry(List<String> serviceRegistryURLs) { return serviceRegistryURLs; } protected List<String> filterReferenceRegistry(List<String> referenceRegistryURLs) { return referenceRegistryURLs; } protected void checkApplicationName(String applicationName) {} protected String getApplicationName() { return applicationName; } public Map<String, Registry> getServiceRegistries() { return serviceRegistries; } public Map<String, Registry> getReferenceRegistries() { return referenceRegistries; } public List<String> getOrigServiceRegistryURLs() { return origServiceRegistryURLs; } public List<String> getOrigReferenceRegistryURLs() { return origReferenceRegistryURLs; } public List<String> getEffectServiceRegistryURLs() { return effectServiceRegistryURLs; } public List<String> getEffectReferenceRegistryURLs() { return effectReferenceRegistryURLs; } protected static class MultipleNotifyListenerWrapper implements NotifyListener { Map<URL, SingleNotifyListener> registryMap = new ConcurrentHashMap<>(4); NotifyListener sourceNotifyListener; public MultipleNotifyListenerWrapper(NotifyListener sourceNotifyListener) { this.sourceNotifyListener = sourceNotifyListener; } public void putRegistryMap(URL registryURL, SingleNotifyListener singleNotifyListener) { this.registryMap.put(registryURL, singleNotifyListener); } public void destroy() { for (SingleNotifyListener singleNotifyListener : registryMap.values()) { if (singleNotifyListener != null) { singleNotifyListener.destroy(); } } registryMap.clear(); sourceNotifyListener = null; } public synchronized void notifySourceListener() { List<URL> notifyURLs = new ArrayList<>(); URL emptyURL = null; for (SingleNotifyListener singleNotifyListener : registryMap.values()) { List<URL> tmpUrls = singleNotifyListener.getUrlList(); if (CollectionUtils.isEmpty(tmpUrls)) { continue; } // empty protocol if (tmpUrls.size() == 1 && tmpUrls.get(0) != null && EMPTY_PROTOCOL.equals(tmpUrls.get(0).getProtocol())) { // if only one empty if (emptyURL == null) { emptyURL = tmpUrls.get(0); } continue; } URL registryURL = singleNotifyListener.getRegistry().getUrl(); aggregateRegistryUrls(notifyURLs, tmpUrls, registryURL); } // if no notify URL, add empty protocol URL if (emptyURL != null && notifyURLs.isEmpty()) { notifyURLs.add(emptyURL); LOGGER.info("No provider after aggregation, notify url with EMPTY protocol."); } else { LOGGER.info("Aggregated provider url size " + notifyURLs.size()); } this.notify(notifyURLs); } /** * Aggregate urls from different registries into one unified list while appending registry specific 'attachments' into each url. * * These 'attachments' can be very useful for traffic management among registries. * * @param notifyURLs unified url list * @param singleURLs single registry url list * @param registryURL single registry configuration url */ public static void aggregateRegistryUrls(List<URL> notifyURLs, List<URL> singleURLs, URL registryURL) { String registryAttachments = registryURL.getParameter("attachments"); if (StringUtils.isNotBlank(registryAttachments)) { LOGGER.info("Registry attachments " + registryAttachments + " found, will append to provider urls, urls size " + singleURLs.size()); String[] pairs = registryAttachments.split(COMMA_SEPARATOR); Map<String, String> attachments = new HashMap<>(pairs.length); for (String rawPair : pairs) { String[] keyValuePair = rawPair.split("="); if (keyValuePair.length == 2) { String key = keyValuePair[0]; String value = keyValuePair[1]; attachments.put(key, value); } } for (URL tmpUrl : singleURLs) { for (Map.Entry<String, String> entry : attachments.entrySet()) { tmpUrl = tmpUrl.addParameterIfAbsent(entry.getKey(), entry.getValue()); } notifyURLs.add(tmpUrl); } } else { LOGGER.info("Single registry " + registryURL + " has url size " + singleURLs.size()); notifyURLs.addAll(singleURLs); } } @Override public void notify(List<URL> urls) { sourceNotifyListener.notify(urls); } public Map<URL, SingleNotifyListener> getRegistryMap() { return registryMap; } } protected static class SingleNotifyListener implements NotifyListener { MultipleNotifyListenerWrapper multipleNotifyListenerWrapper; Registry registry; volatile List<URL> urlList; public SingleNotifyListener(MultipleNotifyListenerWrapper multipleNotifyListenerWrapper, Registry registry) { this.registry = registry; this.multipleNotifyListenerWrapper = multipleNotifyListenerWrapper; } @Override public synchronized void notify(List<URL> urls) { this.urlList = urls; if (multipleNotifyListenerWrapper != null) { this.multipleNotifyListenerWrapper.notifySourceListener(); } } public void destroy() { this.multipleNotifyListenerWrapper = null; this.registry = null; } public List<URL> getUrlList() { return urlList; } public Registry getRegistry() { return 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-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscovery.java
dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscovery.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.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.metadata.MetadataInfo; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import java.util.ArrayList; import java.util.HashSet; 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.function.Function; public class MultipleServiceDiscovery implements ServiceDiscovery { public static final String REGISTRY_PREFIX_KEY = "child."; private static final String REGISTRY_TYPE = "registry-type"; private static final String SERVICE = "service"; private final Map<String, ServiceDiscovery> serviceDiscoveries = new ConcurrentHashMap<>(); private URL registryURL; private String applicationName; private volatile boolean isDestroy; public MultipleServiceDiscovery(URL registryURL) { this.registryURL = registryURL; this.applicationName = registryURL.getApplication(); Map<String, String> parameters = registryURL.getParameters(); for (String key : parameters.keySet()) { if (key.startsWith(REGISTRY_PREFIX_KEY)) { URL url = URL.valueOf(registryURL.getParameter(key)) .addParameter(CommonConstants.APPLICATION_KEY, applicationName) .addParameter(REGISTRY_TYPE, SERVICE); ServiceDiscovery serviceDiscovery = ServiceDiscoveryFactory.getExtension(url).getServiceDiscovery(url); serviceDiscoveries.put(key, serviceDiscovery); } } } @Override public URL getUrl() { return registryURL; } @Override public void destroy() throws Exception { this.isDestroy = true; for (ServiceDiscovery serviceDiscovery : serviceDiscoveries.values()) { serviceDiscovery.destroy(); } } @Override public boolean isDestroy() { return isDestroy; } @Override public void register() throws RuntimeException { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.register()); } @Override public void update() throws RuntimeException { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.update()); } @Override public void unregister() throws RuntimeException { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.unregister()); } @Override public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { MultiServiceInstancesChangedListener multiListener = (MultiServiceInstancesChangedListener) listener; for (String registryKey : serviceDiscoveries.keySet()) { ServiceDiscovery serviceDiscovery = serviceDiscoveries.get(registryKey); SingleServiceInstancesChangedListener singleListener = multiListener.getAndComputeIfAbsent( registryKey, k -> new SingleServiceInstancesChangedListener( listener.getServiceNames(), serviceDiscovery, multiListener)); serviceDiscovery.addServiceInstancesChangedListener(singleListener); } } @Override public ServiceInstancesChangedListener createListener(Set<String> serviceNames) { return new MultiServiceInstancesChangedListener(serviceNames, this); } @Override public List<ServiceInstance> getInstances(String serviceName) { List<ServiceInstance> serviceInstanceList = new ArrayList<>(); for (ServiceDiscovery serviceDiscovery : serviceDiscoveries.values()) { serviceInstanceList.addAll(serviceDiscovery.getInstances(serviceName)); } return serviceInstanceList; } @Override public Set<String> getServices() { Set<String> services = new HashSet<>(); for (ServiceDiscovery serviceDiscovery : serviceDiscoveries.values()) { services.addAll(serviceDiscovery.getServices()); } return services; } @Override public ServiceInstance getLocalInstance() { return null; } @Override public MetadataInfo getLocalMetadata() { throw new UnsupportedOperationException( "Multiple registry implementation does not support getMetadata() method."); } @Override public MetadataInfo getLocalMetadata(String revision) { MetadataInfo metadataInfo = MetadataInfo.EMPTY; for (ServiceDiscovery serviceDiscovery : serviceDiscoveries.values()) { MetadataInfo remoteMetadata = serviceDiscovery.getLocalMetadata(revision); if (!Objects.equals(MetadataInfo.EMPTY, remoteMetadata)) { metadataInfo = remoteMetadata; break; } } return metadataInfo; } @Override public MetadataInfo getRemoteMetadata(String revision) { throw new UnsupportedOperationException( "Multiple registry implementation does not support getMetadata() method."); } @Override public MetadataInfo getRemoteMetadata(String revision, List<ServiceInstance> instances) { MetadataInfo metadataInfo = MetadataInfo.EMPTY; for (ServiceDiscovery serviceDiscovery : serviceDiscoveries.values()) { MetadataInfo remoteMetadata = serviceDiscovery.getRemoteMetadata(revision, instances); if (!Objects.equals(MetadataInfo.EMPTY, remoteMetadata)) { metadataInfo = remoteMetadata; break; } } return metadataInfo; } @Override public void register(URL url) { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.register(url)); } @Override public void unregister(URL url) { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.unregister(url)); } @Override public void subscribe(URL url, NotifyListener listener) { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.subscribe(url, listener)); } @Override public void unsubscribe(URL url, NotifyListener listener) { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.unsubscribe(url, listener)); } @Override public List<URL> lookup(URL url) { throw new UnsupportedOperationException("Multiple registry implementation does not support lookup() method."); } protected static class MultiServiceInstancesChangedListener extends ServiceInstancesChangedListener { private final ConcurrentMap<String, SingleServiceInstancesChangedListener> singleListenerMap; public MultiServiceInstancesChangedListener(Set<String> serviceNames, ServiceDiscovery serviceDiscovery) { super(serviceNames, serviceDiscovery); this.singleListenerMap = new ConcurrentHashMap<>(); } @Override public void onEvent(ServiceInstancesChangedEvent event) { List<ServiceInstance> serviceInstances = new ArrayList<>(); for (SingleServiceInstancesChangedListener singleListener : singleListenerMap.values()) { if (null != singleListener.event && null != singleListener.event.getServiceInstances()) { for (ServiceInstance serviceInstance : singleListener.event.getServiceInstances()) { if (!serviceInstances.contains(serviceInstance)) { serviceInstances.add(serviceInstance); } } } } super.onEvent(new ServiceInstancesChangedEvent(event.getServiceName(), serviceInstances)); } public void putSingleListener(String registryKey, SingleServiceInstancesChangedListener singleListener) { singleListenerMap.put(registryKey, singleListener); } public SingleServiceInstancesChangedListener getAndComputeIfAbsent( String registryKey, Function<String, SingleServiceInstancesChangedListener> func) { return ConcurrentHashMapUtils.computeIfAbsent(singleListenerMap, registryKey, func); } } protected static class SingleServiceInstancesChangedListener extends ServiceInstancesChangedListener { private final MultiServiceInstancesChangedListener multiListener; volatile ServiceInstancesChangedEvent event; public SingleServiceInstancesChangedListener( Set<String> serviceNames, ServiceDiscovery serviceDiscovery, MultiServiceInstancesChangedListener multiListener) { super(serviceNames, serviceDiscovery); this.multiListener = multiListener; } @Override public void onEvent(ServiceInstancesChangedEvent event) { this.event = event; if (multiListener != null) { multiListener.onEvent(event); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/NettyMetricsConstants.java
dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/NettyMetricsConstants.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.metrics.registry; import org.apache.dubbo.metrics.model.key.MetricsKey; import java.util.Arrays; import java.util.List; import static org.apache.dubbo.metrics.model.key.MetricsKey.NETTY_ALLOCATOR_CHUNK_SIZE; import static org.apache.dubbo.metrics.model.key.MetricsKey.NETTY_ALLOCATOR_DIRECT_ARENAS_NUM; import static org.apache.dubbo.metrics.model.key.MetricsKey.NETTY_ALLOCATOR_DIRECT_MEMORY_USED; import static org.apache.dubbo.metrics.model.key.MetricsKey.NETTY_ALLOCATOR_HEAP_ARENAS_NUM; import static org.apache.dubbo.metrics.model.key.MetricsKey.NETTY_ALLOCATOR_HEAP_MEMORY_USED; import static org.apache.dubbo.metrics.model.key.MetricsKey.NETTY_ALLOCATOR_NORMAL_CACHE_SIZE; import static org.apache.dubbo.metrics.model.key.MetricsKey.NETTY_ALLOCATOR_PINNED_DIRECT_MEMORY; import static org.apache.dubbo.metrics.model.key.MetricsKey.NETTY_ALLOCATOR_PINNED_HEAP_MEMORY; import static org.apache.dubbo.metrics.model.key.MetricsKey.NETTY_ALLOCATOR_SMALL_CACHE_SIZE; import static org.apache.dubbo.metrics.model.key.MetricsKey.NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM; public interface NettyMetricsConstants { // App-level List<MetricsKey> APP_LEVEL_KEYS = Arrays.asList( NETTY_ALLOCATOR_HEAP_MEMORY_USED, NETTY_ALLOCATOR_DIRECT_MEMORY_USED, NETTY_ALLOCATOR_PINNED_DIRECT_MEMORY, NETTY_ALLOCATOR_PINNED_HEAP_MEMORY, NETTY_ALLOCATOR_HEAP_ARENAS_NUM, NETTY_ALLOCATOR_DIRECT_ARENAS_NUM, NETTY_ALLOCATOR_NORMAL_CACHE_SIZE, NETTY_ALLOCATOR_SMALL_CACHE_SIZE, NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM, NETTY_ALLOCATOR_CHUNK_SIZE); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java
dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.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.metrics.registry.collector; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.collector.CombMetricsCollector; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.data.ApplicationStatComposite; import org.apache.dubbo.metrics.data.BaseStatComposite; import org.apache.dubbo.metrics.data.RtStatComposite; import org.apache.dubbo.metrics.data.ServiceStatComposite; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.registry.NettyMetricsConstants; import org.apache.dubbo.metrics.registry.event.NettyEvent; import org.apache.dubbo.metrics.registry.event.NettySubDispatcher; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * Netty implementation of {@link MetricsCollector} */ @Activate public class NettyMetricsCollector extends CombMetricsCollector<NettyEvent> { private Boolean collectEnabled = null; private final ApplicationModel applicationModel; public NettyMetricsCollector(ApplicationModel applicationModel) { super(new BaseStatComposite(applicationModel) { @Override protected void init(ApplicationStatComposite applicationStatComposite) { super.init(applicationStatComposite); applicationStatComposite.init(NettyMetricsConstants.APP_LEVEL_KEYS); } @Override protected void init(ServiceStatComposite serviceStatComposite) { super.init(serviceStatComposite); } @Override protected void init(RtStatComposite rtStatComposite) { super.init(rtStatComposite); } }); super.setEventMulticaster(new NettySubDispatcher(this)); this.applicationModel = applicationModel; } public void setCollectEnabled(Boolean collectEnabled) { if (collectEnabled != null) { this.collectEnabled = collectEnabled; } } @Override public boolean isCollectEnabled() { if (collectEnabled == null) { ConfigManager configManager = applicationModel.getApplicationConfigManager(); configManager.getMetrics().ifPresent(metricsConfig -> setCollectEnabled(metricsConfig.getEnableNetty())); } return Optional.ofNullable(collectEnabled).orElse(false); } @Override public List<MetricSample> collect() { List<MetricSample> list = new ArrayList<>(); if (!isCollectEnabled()) { return list; } list.addAll(super.export(MetricsCategory.NETTY)); return list; } @Override public boolean calSamplesChanged() { return stats.calSamplesChanged(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.java
dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.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.metrics.registry.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.metrics.registry.collector.NettyMetricsCollector; import org.apache.dubbo.rpc.model.ApplicationModel; import static org.apache.dubbo.metrics.MetricsConstants.NETTY_METRICS_MAP; /** * Netty related events */ public class NettyEvent extends TimeCounterEvent { public NettyEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { super(applicationModel, typeWrapper); ScopeBeanFactory beanFactory = getSource().getBeanFactory(); NettyMetricsCollector collector; if (!beanFactory.isDestroyed()) { collector = beanFactory.getBean(NettyMetricsCollector.class); super.setAvailable(collector != null && collector.isCollectEnabled()); } } public static NettyEvent toNettyEvent(ApplicationModel applicationModel) { return new NettyEvent(applicationModel, new TypeWrapper(MetricsLevel.APP, null, null, null)) { @Override public void customAfterPost(Object postResult) { super.putAttachment(NETTY_METRICS_MAP, postResult); } }; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java
dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.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.metrics.registry.event; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.event.SimpleMetricsEventMulticaster; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.listener.AbstractMetricsKeyListener; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.registry.collector.NettyMetricsCollector; import java.util.Collections; import java.util.Map; import static org.apache.dubbo.metrics.MetricsConstants.NETTY_METRICS_MAP; public final class NettySubDispatcher extends SimpleMetricsEventMulticaster { public NettySubDispatcher(NettyMetricsCollector collector) { super.addListener(new AbstractMetricsKeyListener(null) { @Override public boolean isSupport(MetricsEvent event) { return true; } @Override public void onEventFinish(TimeCounterEvent event) { Map<String, Long> lastNumMap = Collections.unmodifiableMap(event.getAttachmentValue(NETTY_METRICS_MAP)); lastNumMap.forEach((k, v) -> { MetricsKey metricsKey = MetricsKey.getMetricsByName(k); collector.setAppNum(metricsKey, v); }); } }); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java
dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.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.metrics; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.ServiceKeyMetric; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS; public class MetricsSupportTest { @AfterEach public void destroy() { ApplicationModel.defaultModel().destroy(); } @Test void testFillZero() { ApplicationModel applicationModel = FrameworkModel.defaultModel().newApplication(); ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); ConcurrentHashMap<MetricsKeyWrapper, ConcurrentHashMap<ServiceKeyMetric, AtomicLong>> data = new ConcurrentHashMap<>(); MetricsKeyWrapper key1 = new MetricsKeyWrapper( METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)); MetricsKeyWrapper key2 = new MetricsKeyWrapper( METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)); ServiceKeyMetric sm1 = new ServiceKeyMetric(applicationModel, "a.b.c"); ServiceKeyMetric sm2 = new ServiceKeyMetric(applicationModel, "a.b.d"); data.computeIfAbsent(key1, k -> new ConcurrentHashMap<>()).put(sm1, new AtomicLong(1)); data.computeIfAbsent(key1, k -> new ConcurrentHashMap<>()).put(sm2, new AtomicLong(1)); data.put(key2, new ConcurrentHashMap<>()); Assertions.assertEquals( 2, data.values().stream().mapToLong(map -> map.values().size()).sum()); MetricsSupport.fillZero(data); Assertions.assertEquals( 4, data.values().stream().mapToLong(map -> map.values().size()).sum()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/model/ApplicationMetricTest.java
dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/model/ApplicationMetricTest.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.metrics.model; import org.apache.dubbo.common.Version; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.MetricsConstants.*; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_GIT_COMMITID_METRIC; import static org.junit.jupiter.api.Assertions.*; class ApplicationMetricTest { @Test void getApplicationModel() { ApplicationMetric applicationMetric = new ApplicationMetric(ApplicationModel.defaultModel()); Assertions.assertNotNull(applicationMetric.getApplicationModel()); } @Test void getApplicationName() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; applicationModel .getApplicationConfigManager() .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); Assertions.assertNotNull(applicationMetric); Assertions.assertEquals(mockMetrics, applicationMetric.getApplicationName()); } @Test void getTags() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; applicationModel .getApplicationConfigManager() .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); Map<String, String> tags = applicationMetric.getTags(); Assertions.assertEquals(tags.get(TAG_IP), getLocalHost()); Assertions.assertEquals(tags.get(TAG_HOSTNAME), getLocalHostName()); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName()); Assertions.assertEquals(tags.get(METADATA_GIT_COMMITID_METRIC.getName()), Version.getLastCommitId()); } @Test void gitTags() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; applicationModel .getApplicationConfigManager() .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); Map<String, String> tags = applicationMetric.getTags(); Assertions.assertEquals(tags.get(METADATA_GIT_COMMITID_METRIC.getName()), Version.getLastCommitId()); } @Test void hostTags() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; applicationModel .getApplicationConfigManager() .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); Map<String, String> tags = applicationMetric.getTags(); Assertions.assertEquals(tags.get(TAG_IP), getLocalHost()); Assertions.assertEquals(tags.get(TAG_HOSTNAME), getLocalHostName()); } @Test void getExtraInfo() {} @Test void setExtraInfo() {} @Test void testEquals() {} @Test void testHashCode() {} @AfterEach public void destroy() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel.destroy(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounterTest.java
dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounterTest.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.metrics.aggregate; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class TimeWindowCounterTest { @Test void test() { TimeWindowCounter counter = new TimeWindowCounter(10, 1); counter.increment(); Assertions.assertEquals(1, counter.get()); counter.decrement(); Assertions.assertEquals(0, counter.get()); counter.increment(); counter.increment(); Assertions.assertEquals(2, counter.get()); Assertions.assertTrue(counter.bucketLivedSeconds() <= 1); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantileTest.java
dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantileTest.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.metrics.aggregate; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; class TimeWindowQuantileTest { @Test void test() { TimeWindowQuantile quantile = new TimeWindowQuantile(100, 10, 1); for (int i = 1; i <= 100; i++) { quantile.add(i); } Assertions.assertEquals(quantile.quantile(0.01), 2); Assertions.assertEquals(quantile.quantile(0.99), 100); } @Test @RepeatedTest(100) void testMulti() { ExecutorService executorService = Executors.newFixedThreadPool(200); TimeWindowQuantile quantile = new TimeWindowQuantile(100, 10, 120); int index = 0; while (index < 100) { for (int i = 0; i < 100; i++) { int finalI = i; Assertions.assertDoesNotThrow(() -> quantile.add(finalI)); executorService.execute(() -> quantile.add(finalI)); } index++; // try { // Thread.sleep(1); // } catch (InterruptedException e) { // e.printStackTrace(); // } } executorService.shutdown(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/SlidingWindowTest.java
dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/SlidingWindowTest.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.metrics.aggregate; import java.util.concurrent.atomic.LongAdder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class SlidingWindowTest { static final int paneCount = 10; static final long intervalInMs = 2000; TestSlidingWindow window; @BeforeEach void setup() { window = new TestSlidingWindow(paneCount, intervalInMs); } @RepeatedTest(1000) void testCurrentPane() { assertNull(window.currentPane(/* invalid time*/ -1L)); long timeInMs = System.currentTimeMillis(); Pane<LongAdder> currentPane = window.currentPane(timeInMs); assertNotNull(currentPane); // reuse test assertEquals(currentPane, window.currentPane(timeInMs + window.getPaneIntervalInMs() * paneCount)); } @Test void testGetPaneData() { assertNull(window.getPaneValue(/* invalid time*/ -1L)); long time = System.currentTimeMillis(); window.currentPane(time); assertNotNull(window.getPaneValue(time)); assertNull(window.getPaneValue(time + window.getPaneIntervalInMs())); } @Test void testNewEmptyValue() { assertEquals(0L, window.newEmptyValue(System.currentTimeMillis()).sum()); } @Test void testResetPaneTo() { Pane<LongAdder> currentPane = window.currentPane(); currentPane.getValue().add(2); currentPane.getValue().add(1); assertEquals(3, currentPane.getValue().sum()); window.resetPaneTo(currentPane, System.currentTimeMillis()); assertEquals(0, currentPane.getValue().sum()); currentPane.getValue().add(1); assertEquals(1, currentPane.getValue().sum()); } @Test void testCalculatePaneStart() { long time = System.currentTimeMillis(); assertTrue(window.calculatePaneStart(time) <= time); assertTrue(time < window.calculatePaneStart(time) + window.getPaneIntervalInMs()); } @Test void testIsPaneDeprecated() { Pane<LongAdder> currentPane = window.currentPane(); currentPane.setStartInMs(1000000L); assertTrue(window.isPaneDeprecated(currentPane)); } @Test void testList() { window.currentPane(); assertTrue(0 < window.list().size()); } @Test void testValues() { window.currentPane().getValue().add(10); long sum = 0; for (LongAdder value : window.values()) { sum += value.sum(); } assertEquals(10, sum); } @Test void testGetIntervalInMs() { assertEquals(intervalInMs, window.getIntervalInMs()); } @Test void testGetPaneIntervalInMs() { assertEquals(intervalInMs / paneCount, window.getPaneIntervalInMs()); } private static class TestSlidingWindow extends SlidingWindow<LongAdder> { public TestSlidingWindow(int paneCount, long intervalInMs) { super(paneCount, intervalInMs); } @Override public LongAdder newEmptyValue(long timeMillis) { return new LongAdder(); } @Override protected Pane<LongAdder> resetPaneTo(Pane<LongAdder> pane, long startInMs) { pane.setStartInMs(startInMs); pane.getValue().reset(); return pane; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/PaneTest.java
dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/PaneTest.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.metrics.aggregate; import java.util.concurrent.atomic.LongAdder; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class PaneTest { @Test void testIntervalInMs() { Pane<?> pane = mock(Pane.class); when(pane.getIntervalInMs()).thenReturn(100L); assertEquals(100L, pane.getIntervalInMs()); } @Test void testStartInMs() { Pane<?> pane = mock(Pane.class); long startTime = System.currentTimeMillis(); when(pane.getStartInMs()).thenReturn(startTime); assertEquals(startTime, pane.getStartInMs()); } @Test void testEndInMs() { long startTime = System.currentTimeMillis(); Pane<?> pane = new Pane<>(10, startTime, new Object()); assertEquals(startTime + 10, pane.getEndInMs()); } @Test @SuppressWarnings("unchecked") void testValue() { Pane<LongAdder> pane = mock(Pane.class); LongAdder count = new LongAdder(); when(pane.getValue()).thenReturn(count); assertEquals(count, pane.getValue()); when(pane.getValue()).thenReturn(null); assertNotEquals(count, pane.getValue()); } @Test void testIsTimeInWindow() { Pane<?> pane = new Pane<>(10, System.currentTimeMillis(), new Object()); assertTrue(pane.isTimeInWindow(System.currentTimeMillis())); assertFalse(pane.isTimeInWindow(System.currentTimeMillis() + 10)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregatorTest.java
dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregatorTest.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.metrics.aggregate; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TimeWindowAggregatorTest { @Test public void testTimeWindowAggregator() { TimeWindowAggregator aggregator = new TimeWindowAggregator(5, 5); // First time window, time range: 0 - 5 seconds aggregator.add(10); aggregator.add(20); aggregator.add(30); SampleAggregatedEntry entry1 = aggregator.get(); Assertions.assertEquals(20, entry1.getAvg()); Assertions.assertEquals(60, entry1.getTotal()); Assertions.assertEquals(3, entry1.getCount()); Assertions.assertEquals(30, entry1.getMax()); Assertions.assertEquals(10, entry1.getMin()); // Second time window, time range: 5 - 10 seconds try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } aggregator.add(15); aggregator.add(25); aggregator.add(35); SampleAggregatedEntry entry2 = aggregator.get(); Assertions.assertEquals(25, entry2.getAvg()); Assertions.assertEquals(75, entry2.getTotal()); Assertions.assertEquals(3, entry2.getCount()); Assertions.assertEquals(35, entry2.getMax()); Assertions.assertEquals(15, entry2.getMin()); // Third time window, time range: 10 - 15 seconds try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } aggregator.add(12); aggregator.add(22); aggregator.add(32); SampleAggregatedEntry entry3 = aggregator.get(); Assertions.assertEquals(22, entry3.getAvg()); Assertions.assertEquals(66, entry3.getTotal()); Assertions.assertEquals(3, entry3.getCount()); Assertions.assertEquals(32, entry3.getMax()); Assertions.assertEquals(12, entry3.getMin()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.java
dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.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.metrics.event; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.listener.AbstractMetricsListener; import org.apache.dubbo.metrics.listener.MetricsLifeListener; import org.apache.dubbo.rpc.model.ApplicationModel; 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 static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; public class SimpleMetricsEventMulticasterTest { private SimpleMetricsEventMulticaster eventMulticaster; private Object[] objects; private final Object obj = new Object(); private TimeCounterEvent requestEvent; @BeforeEach public void setup() { eventMulticaster = new SimpleMetricsEventMulticaster(); objects = new Object[] {obj}; eventMulticaster.addListener(new AbstractMetricsListener<MetricsEvent>() { @Override public void onEvent(MetricsEvent event) { objects[0] = new Object(); } }); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); applicationModel.setConfigManager(configManager); requestEvent = new TimeCounterEvent(applicationModel, null) {}; } @AfterEach public void destroy() { ApplicationModel.defaultModel().destroy(); } @Test void testPublishFinishEvent() { // do nothing with no MetricsLifeListener eventMulticaster.publishFinishEvent(requestEvent); Assertions.assertSame(obj, objects[0]); // do onEventFinish with MetricsLifeListener eventMulticaster.addListener((new MetricsLifeListener<TimeCounterEvent>() { @Override public boolean isSupport(MetricsEvent event) { return event instanceof TimeCounterEvent; } @Override public void onEvent(TimeCounterEvent event) {} @Override public void onEventFinish(TimeCounterEvent event) { objects[0] = new Object(); } @Override public void onEventError(TimeCounterEvent event) {} })); eventMulticaster.publishFinishEvent(requestEvent); Assertions.assertNotSame(obj, objects[0]); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.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.metrics.collector; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.rpc.Invocation; /** * Method-level metrics collection for rpc invocation scenarios */ public interface MethodMetricsCollector<E extends TimeCounterEvent> extends MetricsCollector<E> { void increment(MethodMetric methodMetric, MetricsKeyWrapper wrapper, int size); void addMethodRt(Invocation invocation, String registryOpType, Long responseTime); void init(Invocation invocation, MetricsKeyWrapper wrapper); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.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.metrics.collector; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.listener.MetricsLifeListener; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.List; /** * Metrics Collector. * An interface of collector to collect framework internal metrics. */ @SPI public interface MetricsCollector<E extends TimeCounterEvent> extends MetricsLifeListener<E> { default boolean isCollectEnabled() { return false; } /** * Collect metrics as {@link MetricSample} * * @return List of MetricSample */ List<MetricSample> collect(); /** * Check if samples have been changed. * Note that this method will reset the changed flag to false using CAS. * * @return true if samples have been changed */ boolean calSamplesChanged(); default void initMetrics(MetricsEvent event) {} ; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.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.metrics.collector; import org.apache.dubbo.metrics.data.BaseStatComposite; import org.apache.dubbo.metrics.event.MetricsEventMulticaster; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.listener.AbstractMetricsListener; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.Invocation; import java.util.List; import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; public abstract class CombMetricsCollector<E extends TimeCounterEvent> extends AbstractMetricsListener<E> implements ApplicationMetricsCollector<E>, ServiceMetricsCollector<E>, MethodMetricsCollector<E> { protected final BaseStatComposite stats; private MetricsEventMulticaster eventMulticaster; public CombMetricsCollector(BaseStatComposite stats) { this.stats = stats; } protected void setEventMulticaster(MetricsEventMulticaster eventMulticaster) { this.eventMulticaster = eventMulticaster; } @Override public void setNum(MetricsKeyWrapper metricsKey, String serviceKey, int num) { this.stats.setServiceKey(metricsKey, serviceKey, num); } @Override public void increment(MetricsKey metricsKey) { this.stats.incrementApp(metricsKey, SELF_INCREMENT_SIZE); } public void increment(String serviceKey, MetricsKeyWrapper metricsKeyWrapper, int size) { this.stats.incrementServiceKey(metricsKeyWrapper, serviceKey, size); } @Override public void addApplicationRt(String registryOpType, Long responseTime) { stats.calcApplicationRt(registryOpType, responseTime); } @Override public void addServiceRt(String serviceKey, String registryOpType, Long responseTime) { stats.calcServiceKeyRt(serviceKey, registryOpType, responseTime); } @Override public void addServiceRt(Invocation invocation, String registryOpType, Long responseTime) { stats.calcServiceKeyRt(invocation, registryOpType, responseTime); } @Override public void addMethodRt(Invocation invocation, String registryOpType, Long responseTime) { stats.calcMethodKeyRt(invocation, registryOpType, responseTime); } public void setAppNum(MetricsKey metricsKey, Long num) { stats.setAppKey(metricsKey, num); } @Override public void increment(MethodMetric methodMetric, MetricsKeyWrapper wrapper, int size) { this.stats.incrementMethodKey(wrapper, methodMetric, size); } @Override public void init(Invocation invocation, MetricsKeyWrapper wrapper) { this.stats.initMethodKey(wrapper, invocation); } protected List<MetricSample> export(MetricsCategory category) { return stats.export(category); } public MetricsEventMulticaster getEventMulticaster() { return eventMulticaster; } @Override public void onEvent(TimeCounterEvent event) { eventMulticaster.publishEvent(event); } @Override public void onEventFinish(TimeCounterEvent event) { eventMulticaster.publishFinishEvent(event); } @Override public void onEventError(TimeCounterEvent event) { eventMulticaster.publishErrorEvent(event); } protected BaseStatComposite getStats() { return stats; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.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.metrics.collector; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.key.MetricsKey; /** * Application-level collector. * registration center, configuration center and other scenarios * * @Params <T> metrics type */ public interface ApplicationMetricsCollector<E extends TimeCounterEvent> extends MetricsCollector<E> { void increment(MetricsKey metricsKey); void addApplicationRt(String registryOpType, Long responseTime); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.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.metrics.collector; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.rpc.Invocation; /** * Service-level collector. * registration center, configuration center and other scenarios */ public interface ServiceMetricsCollector<E extends TimeCounterEvent> extends MetricsCollector<E> { void increment(String serviceKey, MetricsKeyWrapper wrapper, int size); void setNum(MetricsKeyWrapper metricsKey, String serviceKey, int num); void addServiceRt(String serviceKey, String registryOpType, Long responseTime); void addServiceRt(Invocation invocation, String registryOpType, Long responseTime); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/stat/MetricsStatHandler.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/stat/MetricsStatHandler.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.metrics.collector.stat; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.rpc.Invocation; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; public interface MetricsStatHandler { Map<MethodMetric, AtomicLong> get(); MetricsEvent increase(String applicationName, Invocation invocation); MetricsEvent decrease(String applicationName, Invocation invocation); MetricsEvent addApplication(String applicationName); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.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.metrics.service; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; /** * The exporter of {@link MetricsService} */ @SPI(value = "default", scope = ExtensionScope.APPLICATION) public interface MetricsServiceExporter { /** * Initialize exporter */ void init(); /** * Exports the {@link MetricsService} as a Dubbo service * * @return {@link MetricsServiceExporter itself} */ MetricsServiceExporter export(); /** * Unexports the {@link MetricsService} * * @return {@link MetricsServiceExporter itself} */ MetricsServiceExporter unexport(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsService.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsService.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.metrics.service; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.model.MetricsCategory; import java.util.List; import java.util.Map; import static org.apache.dubbo.metrics.service.MetricsService.DEFAULT_EXTENSION_NAME; /** * Metrics Service. * Provide an interface to get metrics from {@link MetricsCollector} */ @SPI(value = DEFAULT_EXTENSION_NAME, scope = ExtensionScope.APPLICATION) public interface MetricsService { /** * Default {@link MetricsService} extension name. */ String DEFAULT_EXTENSION_NAME = "default"; /** * The contract version of {@link MetricsService}, the future update must make sure compatible. */ String VERSION = "1.0.0"; /** * Get metrics by prefixes * * @param categories categories * @return metrics - key=MetricCategory value=MetricsEntityList */ Map<MetricsCategory, List<MetricsEntity>> getMetricsByCategories(List<MetricsCategory> categories); /** * Get metrics by interface and prefixes * * @param serviceUniqueName serviceUniqueName (eg.group/interfaceName:version) * @param categories categories * @return metrics - key=MetricCategory value=MetricsEntityList */ Map<MetricsCategory, List<MetricsEntity>> getMetricsByCategories( String serviceUniqueName, List<MetricsCategory> categories); /** * Get metrics by interface、method and prefixes * * @param serviceUniqueName serviceUniqueName (eg.group/interfaceName:version) * @param methodName methodName * @param parameterTypes method parameter types * @param categories categories * @return metrics - key=MetricCategory value=MetricsEntityList */ Map<MetricsCategory, List<MetricsEntity>> getMetricsByCategories( String serviceUniqueName, String methodName, Class<?>[] parameterTypes, List<MetricsCategory> categories); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsEntity.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsEntity.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.metrics.service; import org.apache.dubbo.metrics.model.MetricsCategory; import java.util.Map; import java.util.Objects; /** * Metrics response entity. */ public class MetricsEntity { private String name; private Map<String, String> tags; private MetricsCategory category; private Object value; public MetricsEntity() {} public MetricsEntity(String name, Map<String, String> tags, MetricsCategory category, Object value) { this.name = name; this.tags = tags; this.category = category; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, String> getTags() { return tags; } public void setTags(Map<String, String> tags) { this.tags = tags; } public MetricsCategory getCategory() { return category; } public void setCategory(MetricsCategory category) { this.category = category; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetricsEntity entity = (MetricsEntity) o; return Objects.equals(name, entity.name) && Objects.equals(tags, entity.tags) && Objects.equals(category, entity.category) && Objects.equals(value, entity.value); } @Override public int hashCode() { return Objects.hash(name, tags, category, value); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/Metric.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/Metric.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.metrics.model; import java.util.Map; public interface Metric { Map<String, String> getTags(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsCategory.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsCategory.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.metrics.model; /** * Metric category. */ public enum MetricsCategory { RT, QPS, REQUESTS, APPLICATION, CONFIGCENTER, REGISTRY, METADATA, THREAD_POOL, ERROR_CODE, NETTY, }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ServiceKeyMetric.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ServiceKeyMetric.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.metrics.model; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; import java.util.Objects; /** * Metric class for service. */ public class ServiceKeyMetric extends ApplicationMetric { private final String serviceKey; public ServiceKeyMetric(ApplicationModel applicationModel, String serviceKey) { super(applicationModel); this.serviceKey = serviceKey; } @Override public Map<String, String> getTags() { return MetricsSupport.serviceTags(getApplicationModel(), serviceKey, getExtraInfo()); } public String getServiceKey() { return serviceKey; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ServiceKeyMetric)) { return false; } ServiceKeyMetric that = (ServiceKeyMetric) o; return serviceKey.equals(that.serviceKey) && Objects.equals(extraInfo, that.extraInfo); } private volatile int hashCode = 0; @Override public int hashCode() { if (hashCode == 0) { hashCode = Objects.hash(getApplicationName(), serviceKey, extraInfo); } return hashCode; } @Override public String toString() { return "ServiceKeyMetric{" + "applicationName='" + getApplicationName() + '\'' + ", serviceKey='" + serviceKey + '\'' + '}'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MethodMetric.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MethodMetric.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.metrics.model; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.support.RpcUtils; import java.util.Map; import java.util.Objects; import java.util.Optional; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_VERSION_KEY; /** * Metric class for method. */ public class MethodMetric extends ServiceKeyMetric { private String side; private final String methodName; private String group; private String version; public MethodMetric(ApplicationModel applicationModel, Invocation invocation, boolean serviceLevel) { super(applicationModel, MetricsSupport.getInterfaceName(invocation)); this.side = MetricsSupport.getSide(invocation); this.group = MetricsSupport.getGroup(invocation); this.version = MetricsSupport.getVersion(invocation); this.methodName = serviceLevel ? null : RpcUtils.getMethodName(invocation); } public static boolean isServiceLevel(ApplicationModel applicationModel) { if (applicationModel == null) { return false; } ConfigManager applicationConfigManager = applicationModel.getApplicationConfigManager(); if (applicationConfigManager == null) { return false; } Optional<MetricsConfig> metrics = applicationConfigManager.getMetrics(); if (!metrics.isPresent()) { return false; } String rpcLevel = metrics.map(MetricsConfig::getRpcLevel).orElse(MetricsLevel.METHOD.name()); rpcLevel = StringUtils.isBlank(rpcLevel) ? MetricsLevel.METHOD.name() : rpcLevel; return MetricsLevel.SERVICE.name().equalsIgnoreCase(rpcLevel); } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public Map<String, String> getTags() { Map<String, String> tags = MetricsSupport.methodTags(getApplicationModel(), getServiceKey(), methodName); tags.put(TAG_GROUP_KEY, group); tags.put(TAG_VERSION_KEY, version); return tags; } public String getMethodName() { return methodName; } public String getSide() { return side; } public void setSide(String side) { this.side = side; } @Override public String toString() { return "MethodMetric{" + "applicationName='" + getApplicationName() + '\'' + ", side='" + side + '\'' + ", interfaceName='" + getServiceKey() + '\'' + ", methodName='" + methodName + '\'' + ", group='" + group + '\'' + ", version='" + version + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MethodMetric that = (MethodMetric) o; return Objects.equals(getApplicationModel(), that.getApplicationModel()) && Objects.equals(side, that.side) && Objects.equals(getServiceKey(), that.getServiceKey()) && Objects.equals(methodName, that.methodName) && Objects.equals(group, that.group) && Objects.equals(version, that.version); } private volatile int hashCode = 0; @Override public int hashCode() { if (hashCode == 0) { hashCode = Objects.hash(getApplicationModel(), side, getServiceKey(), methodName, group, version); } return hashCode; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolRejectMetric.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolRejectMetric.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.metrics.model; import org.apache.dubbo.common.utils.ConfigUtils; import java.util.HashMap; import java.util.Map; import java.util.Objects; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_PID; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_THREAD_NAME; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; public class ThreadPoolRejectMetric implements Metric { private String applicationName; private String threadPoolName; public ThreadPoolRejectMetric(String applicationName, String threadPoolName) { this.applicationName = applicationName; this.threadPoolName = threadPoolName; } public String getThreadPoolName() { return threadPoolName; } public void setThreadPoolName(String threadPoolName) { this.threadPoolName = threadPoolName; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ThreadPoolRejectMetric that = (ThreadPoolRejectMetric) o; return Objects.equals(applicationName, that.applicationName) && Objects.equals(threadPoolName, that.threadPoolName); } @Override public int hashCode() { return Objects.hash(applicationName, threadPoolName); } @Override public Map<String, String> getTags() { Map<String, String> tags = new HashMap<>(); tags.put(TAG_IP, getLocalHost()); tags.put(TAG_PID, ConfigUtils.getPid() + ""); tags.put(TAG_HOSTNAME, getLocalHostName()); tags.put(TAG_APPLICATION_NAME, applicationName); tags.put(TAG_THREAD_NAME, threadPoolName); return tags; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.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.metrics.model; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.lang.Nullable; 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.metrics.collector.MethodMetricsCollector; import org.apache.dubbo.metrics.collector.ServiceMetricsCollector; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_CHAR_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_MODULE; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_VERSION_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_INTERFACE_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_METHOD_KEY; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE; import static org.apache.dubbo.metrics.MetricsConstants.INVOCATION; import static org.apache.dubbo.metrics.MetricsConstants.METHOD_METRICS; import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; public class MetricsSupport { private static final String version = Version.getVersion(); private static final String commitId = Version.getLastCommitId(); public static Map<String, String> applicationTags(ApplicationModel applicationModel) { return applicationTags(applicationModel, null); } public static Map<String, String> applicationTags( ApplicationModel applicationModel, @Nullable Map<String, String> extraInfo) { Map<String, String> tags = new HashMap<>(); tags.put(TAG_APPLICATION_NAME, applicationModel.getApplicationName()); tags.put(TAG_APPLICATION_MODULE, applicationModel.getInternalId()); if (CollectionUtils.isNotEmptyMap(extraInfo)) { tags.putAll(extraInfo); } return tags; } public static Map<String, String> gitTags(Map<String, String> tags) { tags.put(MetricsKey.METADATA_GIT_COMMITID_METRIC.getName(), commitId); tags.put(TAG_APPLICATION_VERSION_KEY, version); return tags; } public static Map<String, String> hostTags(Map<String, String> tags) { tags.put(TAG_IP, getLocalHost()); tags.put(TAG_HOSTNAME, getLocalHostName()); return tags; } public static Map<String, String> serviceTags( ApplicationModel applicationModel, String serviceKey, Map<String, String> extraInfo) { Map<String, String> tags = applicationTags(applicationModel, extraInfo); tags.put(TAG_INTERFACE_KEY, serviceKey); return tags; } public static Map<String, String> methodTags( ApplicationModel applicationModel, String serviceKey, String methodName) { Map<String, String> tags = applicationTags(applicationModel); tags.put(TAG_INTERFACE_KEY, serviceKey); tags.put(TAG_METHOD_KEY, methodName); return tags; } public static MetricsKey getMetricsKey(Throwable throwable) { MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_FAILED; if (throwable instanceof RpcException) { RpcException e = (RpcException) throwable; if (e.isTimeout()) { targetKey = MetricsKey.METRIC_REQUESTS_TIMEOUT; } if (e.isLimitExceed()) { targetKey = MetricsKey.METRIC_REQUESTS_LIMIT; } if (e.isBiz()) { targetKey = MetricsKey.METRIC_REQUEST_BUSINESS_FAILED; } if (e.isSerialization()) { targetKey = MetricsKey.METRIC_REQUESTS_CODEC_FAILED; } if (e.isNetwork()) { targetKey = MetricsKey.METRIC_REQUESTS_NETWORK_FAILED; } } else { targetKey = MetricsKey.METRIC_REQUEST_BUSINESS_FAILED; } return targetKey; } public static MetricsKey getAggMetricsKey(Throwable throwable) { MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_FAILED_AGG; if (throwable instanceof RpcException) { RpcException e = (RpcException) throwable; if (e.isTimeout()) { targetKey = MetricsKey.METRIC_REQUESTS_TIMEOUT_AGG; } if (e.isLimitExceed()) { targetKey = MetricsKey.METRIC_REQUESTS_LIMIT_AGG; } if (e.isBiz()) { targetKey = MetricsKey.METRIC_REQUEST_BUSINESS_FAILED_AGG; } if (e.isSerialization()) { targetKey = MetricsKey.METRIC_REQUESTS_CODEC_FAILED_AGG; } if (e.isNetwork()) { targetKey = MetricsKey.METRIC_REQUESTS_NETWORK_FAILED_AGG; } } else { targetKey = MetricsKey.METRIC_REQUEST_BUSINESS_FAILED_AGG; } return targetKey; } public static String getSide(Invocation invocation) { Optional<? extends Invoker<?>> invoker = Optional.ofNullable(invocation.getInvoker()); return invoker.isPresent() ? invoker.get().getUrl().getSide() : PROVIDER_SIDE; } public static String getInterfaceName(Invocation invocation) { if (invocation.getServiceModel() != null && invocation.getServiceModel().getServiceMetadata() != null) { return invocation.getServiceModel().getServiceMetadata().getServiceInterfaceName(); } else { String serviceUniqueName = invocation.getTargetServiceUniqueName(); String interfaceAndVersion; if (StringUtils.isBlank(serviceUniqueName)) { return ""; } String[] arr = serviceUniqueName.split(PATH_SEPARATOR); if (arr.length == 2) { interfaceAndVersion = arr[1]; } else { interfaceAndVersion = arr[0]; } String[] ivArr = interfaceAndVersion.split(GROUP_CHAR_SEPARATOR); return ivArr[0]; } } public static String getGroup(Invocation invocation) { if (invocation.getServiceModel() != null && invocation.getServiceModel().getServiceMetadata() != null) { return invocation.getServiceModel().getServiceMetadata().getGroup(); } else { String serviceUniqueName = invocation.getTargetServiceUniqueName(); String group = null; String[] arr = serviceUniqueName.split(PATH_SEPARATOR); if (arr.length == 2) { group = arr[0]; } return group; } } public static String getVersion(Invocation invocation) { if (invocation.getServiceModel() != null && invocation.getServiceModel().getServiceMetadata() != null) { return invocation.getServiceModel().getServiceMetadata().getVersion(); } else { String interfaceAndVersion; String[] arr = invocation.getTargetServiceUniqueName().split(PATH_SEPARATOR); if (arr.length == 2) { interfaceAndVersion = arr[1]; } else { interfaceAndVersion = arr[0]; } String[] ivArr = interfaceAndVersion.split(GROUP_CHAR_SEPARATOR); return ivArr.length == 2 ? ivArr[1] : null; } } /** * Incr service num */ public static void increment( MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector<TimeCounterEvent> collector, MetricsEvent event) { collector.increment( event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), new MetricsKeyWrapper(metricsKey, placeType), SELF_INCREMENT_SIZE); } /** * Incr service num&&rt */ public static void incrAndAddRt( MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector<TimeCounterEvent> collector, TimeCounterEvent event) { collector.increment( event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), new MetricsKeyWrapper(metricsKey, placeType), SELF_INCREMENT_SIZE); Invocation invocation = event.getAttachmentValue(INVOCATION); if (invocation != null) { collector.addServiceRt( invocation, placeType.getType(), event.getTimePair().calc()); } else { collector.addServiceRt( (String) event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), placeType.getType(), event.getTimePair().calc()); } } /** * Incr method num */ public static void increment( MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector<TimeCounterEvent> collector, MetricsEvent event) { collector.increment( event.getAttachmentValue(METHOD_METRICS), new MetricsKeyWrapper(metricsKey, placeType), SELF_INCREMENT_SIZE); } public static void init( MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector<TimeCounterEvent> collector, MetricsEvent event) { collector.init(event.getAttachmentValue(INVOCATION), new MetricsKeyWrapper(metricsKey, placeType)); } /** * Dec method num */ public static void dec( MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector<TimeCounterEvent> collector, MetricsEvent event) { collector.increment( event.getAttachmentValue(METHOD_METRICS), new MetricsKeyWrapper(metricsKey, placeType), -SELF_INCREMENT_SIZE); } /** * Incr method num&&rt */ public static void incrAndAddRt( MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector<TimeCounterEvent> collector, TimeCounterEvent event) { collector.increment( event.getAttachmentValue(METHOD_METRICS), new MetricsKeyWrapper(metricsKey, placeType), SELF_INCREMENT_SIZE); collector.addMethodRt( event.getAttachmentValue(INVOCATION), placeType.getType(), event.getTimePair().calc()); } /** * Generate a complete indicator item for an interface/method */ public static <T> void fillZero(ConcurrentHashMap<?, ConcurrentHashMap<T, AtomicLong>> data) { if (CollectionUtils.isEmptyMap(data)) { return; } Set<T> allKeyMetrics = data.values().stream().flatMap(map -> map.keySet().stream()).collect(Collectors.toSet()); data.forEach((keyWrapper, mapVal) -> { for (T key : allKeyMetrics) { ConcurrentHashMapUtils.computeIfAbsent(mapVal, key, k -> new AtomicLong(0)); } }); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ApplicationMetric.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ApplicationMetric.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.metrics.model; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; import java.util.Objects; public class ApplicationMetric implements Metric { private final ApplicationModel applicationModel; protected Map<String, String> extraInfo; public ApplicationMetric(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } public ApplicationModel getApplicationModel() { return applicationModel; } public String getApplicationName() { return getApplicationModel().getApplicationName(); } @Override public Map<String, String> getTags() { return hostTags(gitTags(MetricsSupport.applicationTags(applicationModel, getExtraInfo()))); } public Map<String, String> gitTags(Map<String, String> tags) { return MetricsSupport.gitTags(tags); } public Map<String, String> hostTags(Map<String, String> tags) { return MetricsSupport.hostTags(tags); } public Map<String, String> getExtraInfo() { return extraInfo; } public void setExtraInfo(Map<String, String> extraInfo) { this.extraInfo = extraInfo; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ApplicationMetric that = (ApplicationMetric) o; return getApplicationName().equals(that.applicationModel.getApplicationName()) && Objects.equals(extraInfo, that.extraInfo); } private volatile int hashCode; @Override public int hashCode() { if (hashCode == 0) { hashCode = Objects.hash(getApplicationName(), extraInfo); } return hashCode; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolMetric.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolMetric.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.metrics.model; import org.apache.dubbo.common.utils.ConfigUtils; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.ThreadPoolExecutor; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_PID; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_THREAD_NAME; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; public class ThreadPoolMetric implements Metric { private String applicationName; private String threadPoolName; private ThreadPoolExecutor threadPoolExecutor; public ThreadPoolMetric(String applicationName, String threadPoolName, ThreadPoolExecutor threadPoolExecutor) { this.applicationName = applicationName; this.threadPoolExecutor = threadPoolExecutor; this.threadPoolName = threadPoolName; } public String getThreadPoolName() { return threadPoolName; } public void setThreadPoolName(String threadPoolName) { this.threadPoolName = threadPoolName; } public ThreadPoolExecutor getThreadPoolExecutor() { return threadPoolExecutor; } public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) { this.threadPoolExecutor = threadPoolExecutor; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ThreadPoolMetric that = (ThreadPoolMetric) o; return Objects.equals(applicationName, that.applicationName) && Objects.equals(threadPoolName, that.threadPoolName); } @Override public int hashCode() { return Objects.hash(applicationName, threadPoolName); } @Override public Map<String, String> getTags() { Map<String, String> tags = new HashMap<>(); tags.put(TAG_IP, getLocalHost()); tags.put(TAG_PID, ConfigUtils.getPid() + ""); tags.put(TAG_HOSTNAME, getLocalHostName()); tags.put(TAG_APPLICATION_NAME, applicationName); tags.put(TAG_THREAD_NAME, threadPoolName); return tags; } public double getCorePoolSize() { return threadPoolExecutor.getCorePoolSize(); } public double getLargestPoolSize() { return threadPoolExecutor.getLargestPoolSize(); } public double getMaximumPoolSize() { return threadPoolExecutor.getMaximumPoolSize(); } public double getActiveCount() { return threadPoolExecutor.getActiveCount(); } public double getPoolSize() { return threadPoolExecutor.getPoolSize(); } public double getQueueSize() { return threadPoolExecutor.getQueue().size(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ConfigCenterMetric.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ConfigCenterMetric.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.metrics.model; import java.util.HashMap; import java.util.Map; import java.util.Objects; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_CHANGE_TYPE; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_CONFIG_CENTER; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_KEY_KEY; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; public class ConfigCenterMetric implements Metric { private String applicationName; private String key; private String group; private String configCenter; private String changeType; public ConfigCenterMetric() {} public ConfigCenterMetric( String applicationName, String key, String group, String configCenter, String changeType) { this.applicationName = applicationName; this.key = key; this.group = group; this.configCenter = configCenter; this.changeType = changeType; } @Override public Map<String, String> getTags() { Map<String, String> tags = new HashMap<>(); tags.put(TAG_IP, getLocalHost()); tags.put(TAG_HOSTNAME, getLocalHostName()); tags.put(TAG_APPLICATION_NAME, applicationName); tags.put(TAG_KEY_KEY, key); tags.put(TAG_GROUP_KEY, group); tags.put(TAG_CONFIG_CENTER, configCenter); tags.put(TAG_CHANGE_TYPE, changeType.toLowerCase()); return tags; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConfigCenterMetric that = (ConfigCenterMetric) o; if (!Objects.equals(applicationName, that.applicationName)) return false; if (!Objects.equals(key, that.key)) return false; if (!Objects.equals(group, that.group)) return false; if (!Objects.equals(configCenter, that.configCenter)) return false; return Objects.equals(changeType, that.changeType); } @Override public int hashCode() { return Objects.hash(applicationName, key, group, configCenter, changeType); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ErrorCodeMetric.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ErrorCodeMetric.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.metrics.model; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_ERROR_CODE; /** * ErrorCodeMetric. Provide tags for error code metrics. */ public class ErrorCodeMetric implements Metric { private final String errorCode; private final String applicationName; public ErrorCodeMetric(String applicationName, String errorCode) { this.errorCode = errorCode; this.applicationName = applicationName; } @Override public Map<String, String> getTags() { Map<String, String> tags = new HashMap<>(); tags.put(TAG_ERROR_CODE, errorCode); tags.put(TAG_APPLICATION_NAME, applicationName); return tags; } public String getErrorCode() { return errorCode; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKeyWrapper.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKeyWrapper.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.metrics.model.key; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.Objects; import io.micrometer.common.lang.Nullable; /** * Let {@link MetricsKey MetricsKey} output dynamic, custom string content */ public class MetricsKeyWrapper { /** * Metrics key when exporting */ private final MetricsKey metricsKey; /** * The value corresponding to the MetricsKey placeholder (if exist) */ private final MetricsPlaceValue placeType; /** * Exported sample type */ private MetricSample.Type sampleType = MetricSample.Type.COUNTER; /** * When the MetricsPlaceType is null, it is equivalent to a single MetricsKey. * Use the decorator mode to share a container with MetricsKey */ public MetricsKeyWrapper(MetricsKey metricsKey, @Nullable MetricsPlaceValue placeType) { this.metricsKey = metricsKey; this.placeType = placeType; } public MetricsKeyWrapper setSampleType(MetricSample.Type sampleType) { this.sampleType = sampleType; return this; } public MetricSample.Type getSampleType() { return sampleType; } public MetricsPlaceValue getPlaceType() { return placeType; } public String getType() { return getPlaceType().getType(); } public MetricsKey getMetricsKey() { return metricsKey; } public boolean isKey(MetricsKey metricsKey, String registryOpType) { return metricsKey == getMetricsKey() && registryOpType.equals(getType()); } public MetricsLevel getLevel() { return getPlaceType().getMetricsLevel(); } public String targetKey() { if (placeType == null) { return metricsKey.getName(); } try { return String.format(metricsKey.getName(), getType()); } catch (Exception ignore) { return metricsKey.getName(); } } public String targetDesc() { if (placeType == null) { return metricsKey.getDescription(); } try { return String.format(metricsKey.getDescription(), getType()); } catch (Exception ignore) { return metricsKey.getDescription(); } } public static MetricsKeyWrapper wrapper(MetricsKey metricsKey) { return new MetricsKeyWrapper(metricsKey, null); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetricsKeyWrapper wrapper = (MetricsKeyWrapper) o; if (metricsKey != wrapper.metricsKey) return false; return Objects.equals(placeType, wrapper.placeType); } @Override public int hashCode() { int result = metricsKey != null ? metricsKey.hashCode() : 0; result = 31 * result + (placeType != null ? placeType.hashCode() : 0); return result; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsPlaceValue.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsPlaceValue.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.metrics.model.key; /** * The value corresponding to the placeholder in {@link MetricsKey} */ public class MetricsPlaceValue { private final String type; private final MetricsLevel metricsLevel; private MetricsPlaceValue(String type, MetricsLevel metricsLevel) { this.type = type; this.metricsLevel = metricsLevel; } public static MetricsPlaceValue of(String type, MetricsLevel metricsLevel) { return new MetricsPlaceValue(type, metricsLevel); } public String getType() { return type; } public MetricsLevel getMetricsLevel() { return metricsLevel; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetricsPlaceValue that = (MetricsPlaceValue) o; if (!type.equals(that.type)) return false; return metricsLevel == that.metricsLevel; } @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + metricsLevel.hashCode(); return result; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsCat.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsCat.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.metrics.model.key; import org.apache.dubbo.metrics.collector.CombMetricsCollector; import org.apache.dubbo.metrics.listener.AbstractMetricsKeyListener; import java.util.function.BiFunction; import java.util.function.Function; /** * The behavior wrapper class of MetricsKey, * which saves the complete content of the key {@link MetricsPlaceValue}, * the corresponding collector {@link CombMetricsCollector}, * and the event listener (generate function) at the key level {@link AbstractMetricsKeyListener} */ public class MetricsCat { private MetricsPlaceValue placeType; private final Function<CombMetricsCollector, AbstractMetricsKeyListener> eventFunc; /** * @param metricsKey The key corresponding to the listening event, not necessarily the export key(export key may be dynamic) * @param biFunc Binary function, corresponding to MetricsKey with less content, corresponding to post event */ public MetricsCat( MetricsKey metricsKey, BiFunction<MetricsKey, CombMetricsCollector, AbstractMetricsKeyListener> biFunc) { this.eventFunc = collector -> biFunc.apply(metricsKey, collector); } /** * @param tpFunc Ternary function, corresponding to finish and error events, because an additional record rt is required, and the type of metricsKey is required */ public MetricsCat( MetricsKey metricsKey, TpFunction<MetricsKey, MetricsPlaceValue, CombMetricsCollector, AbstractMetricsKeyListener> tpFunc) { this.eventFunc = collector -> tpFunc.apply(metricsKey, placeType, collector); } public MetricsCat setPlaceType(MetricsPlaceValue placeType) { this.placeType = placeType; return this; } public Function<CombMetricsCollector, AbstractMetricsKeyListener> getEventFunc() { return eventFunc; } @FunctionalInterface public interface TpFunction<T, U, K, R> { R apply(T t, U u, K k); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/CategoryOverall.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/CategoryOverall.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.metrics.model.key; import org.apache.dubbo.common.lang.Nullable; /** * The overall event set, including the event processing functions in three stages */ public class CategoryOverall { private final MetricsCat post; private MetricsCat finish; private MetricsCat error; /** * @param placeType When placeType is null, it means that placeType is obtained dynamically * @param post Statistics of the number of events, as long as it occurs, it will take effect, so it cannot be null */ public CategoryOverall( @Nullable MetricsPlaceValue placeType, MetricsCat post, @Nullable MetricsCat finish, @Nullable MetricsCat error) { this.post = post.setPlaceType(placeType); if (finish != null) { this.finish = finish.setPlaceType(placeType); } if (error != null) { this.error = error.setPlaceType(placeType); } } public MetricsCat getPost() { return post; } public MetricsCat getFinish() { return finish; } public MetricsCat getError() { return error; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongAccumulatorContainer.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongAccumulatorContainer.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.metrics.model.container; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import java.util.concurrent.atomic.LongAccumulator; public class LongAccumulatorContainer extends LongContainer<LongAccumulator> { public LongAccumulatorContainer(MetricsKeyWrapper metricsKeyWrapper, LongAccumulator accumulator) { super( metricsKeyWrapper, () -> accumulator, (responseTime, longAccumulator) -> longAccumulator.accumulate(responseTime)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/AtomicLongContainer.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/AtomicLongContainer.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.metrics.model.container; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; public class AtomicLongContainer extends LongContainer<AtomicLong> { public AtomicLongContainer(MetricsKeyWrapper metricsKeyWrapper) { super(metricsKeyWrapper, AtomicLong::new, (responseTime, longAccumulator) -> longAccumulator.set(responseTime)); } public AtomicLongContainer(MetricsKeyWrapper metricsKeyWrapper, BiConsumer<Long, AtomicLong> consumerFunc) { super(metricsKeyWrapper, AtomicLong::new, consumerFunc); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongContainer.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongContainer.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.metrics.model.container; import org.apache.dubbo.metrics.model.Metric; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Supplier; /** * Long type data container * @param <N> */ public class LongContainer<N extends Number> extends ConcurrentHashMap<Metric, N> { /** * Provide the metric type name */ private final transient MetricsKeyWrapper metricsKeyWrapper; /** * The initial value corresponding to the key is generally 0 of different data types */ private final transient Function<Metric, N> initFunc; /** * Statistical data calculation function, which can be self-increment, self-decrement, or more complex avg function */ private final transient BiConsumer<Long, N> consumerFunc; /** * Data output function required by {@link GaugeMetricSample GaugeMetricSample} */ private transient Function<Metric, Long> valueSupplier; public LongContainer(MetricsKeyWrapper metricsKeyWrapper, Supplier<N> initFunc, BiConsumer<Long, N> consumerFunc) { super(128, 0.5f); this.metricsKeyWrapper = metricsKeyWrapper; this.initFunc = s -> initFunc.get(); this.consumerFunc = consumerFunc; this.valueSupplier = k -> this.get(k).longValue(); } public boolean specifyType(String type) { return type.equals(getMetricsKeyWrapper().getType()); } public MetricsKeyWrapper getMetricsKeyWrapper() { return metricsKeyWrapper; } public boolean isKeyWrapper(MetricsKey metricsKey, String registryOpType) { return metricsKeyWrapper.isKey(metricsKey, registryOpType); } public Function<Metric, N> getInitFunc() { return initFunc; } public BiConsumer<Long, N> getConsumerFunc() { return consumerFunc; } public Function<Metric, Long> getValueSupplier() { return valueSupplier; } public void setValueSupplier(Function<Metric, Long> valueSupplier) { this.valueSupplier = valueSupplier; } @Override public String toString() { return "LongContainer{" + "metricsKeyWrapper=" + metricsKeyWrapper + '}'; } @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; LongContainer<?> that = (LongContainer<?>) o; return metricsKeyWrapper.equals(that.metricsKeyWrapper); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + metricsKeyWrapper.hashCode(); return result; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/CounterMetricSample.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/CounterMetricSample.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.metrics.model.sample; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import java.util.Map; public class CounterMetricSample<T extends Number> extends MetricSample { private final T value; public CounterMetricSample( String name, String description, Map<String, String> tags, MetricsCategory category, T value) { super(name, description, tags, Type.COUNTER, category); this.value = value; } public CounterMetricSample( MetricsKeyWrapper metricsKeyWrapper, Map<String, String> tags, MetricsCategory category, T value) { this(metricsKeyWrapper.targetKey(), metricsKeyWrapper.targetDesc(), tags, category, value); } public T getValue() { return value; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/MetricSample.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/MetricSample.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.metrics.model.sample; import org.apache.dubbo.metrics.model.MetricsCategory; import java.util.Map; import java.util.Objects; /** * MetricSample. */ public class MetricSample { private String name; private String description; private Map<String, String> tags; private Type type; private MetricsCategory category; private String baseUnit; public MetricSample( String name, String description, Map<String, String> tags, Type type, MetricsCategory category) { this(name, description, tags, type, category, null); } public MetricSample( String name, String description, Map<String, String> tags, Type type, MetricsCategory category, String baseUnit) { this.name = name; this.description = description; this.tags = tags; this.type = type; this.category = category; this.baseUnit = baseUnit; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Map<String, String> getTags() { return tags; } public void setTags(Map<String, String> tags) { this.tags = tags; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public MetricsCategory getCategory() { return category; } public void setCategory(MetricsCategory category) { this.category = category; } public String getBaseUnit() { return baseUnit; } public void setBaseUnit(String baseUnit) { this.baseUnit = baseUnit; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetricSample that = (MetricSample) o; return Objects.equals(name, that.name) && Objects.equals(description, that.description) && Objects.equals(baseUnit, that.baseUnit) && type == that.type && Objects.equals(category, that.category) && Objects.equals(tags, that.tags); } @Override public int hashCode() { return Objects.hash(name, description, baseUnit, type, category, tags); } @Override public String toString() { return "MetricSample{" + "name='" + name + '\'' + ", description='" + description + '\'' + ", baseUnit='" + baseUnit + '\'' + ", type=" + type + ", category=" + category + ", tags=" + tags + '}'; } public enum Type { COUNTER, GAUGE, LONG_TASK_TIMER, TIMER, DISTRIBUTION_SUMMARY } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/GaugeMetricSample.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/GaugeMetricSample.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.metrics.model.sample; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.ToDoubleFunction; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION; /** * GaugeMetricSample. */ public class GaugeMetricSample<T> extends MetricSample { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GaugeMetricSample.class); private final AtomicBoolean warned = new AtomicBoolean(false); private final T value; private final ToDoubleFunction<T> apply; public GaugeMetricSample( MetricsKey metricsKey, Map<String, String> tags, MetricsCategory category, T value, ToDoubleFunction<T> apply) { this(metricsKey.getName(), metricsKey.getDescription(), tags, category, null, value, apply); } public GaugeMetricSample( MetricsKeyWrapper metricsKeyWrapper, Map<String, String> tags, MetricsCategory category, T value, ToDoubleFunction<T> apply) { this(metricsKeyWrapper.targetKey(), metricsKeyWrapper.targetDesc(), tags, category, null, value, apply); } public GaugeMetricSample( String name, String description, Map<String, String> tags, MetricsCategory category, T value, ToDoubleFunction<T> apply) { this(name, description, tags, category, null, value, apply); } public GaugeMetricSample( String name, String description, Map<String, String> tags, MetricsCategory category, String baseUnit, T value, ToDoubleFunction<T> apply) { super(name, description, tags, Type.GAUGE, category, baseUnit); this.value = Objects.requireNonNull(value, "The GaugeMetricSample value cannot be null"); Objects.requireNonNull(apply, "The GaugeMetricSample apply cannot be null"); this.apply = (e) -> { try { return apply.applyAsDouble(e); } catch (Throwable t) { if (warned.compareAndSet(false, true)) { logger.error( COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "Unexpected error occurred when applying the GaugeMetricSample", t); } return 0; } }; } public T getValue() { return this.value; } public ToDoubleFunction<T> getApply() { return this.apply; } public long applyAsLong() { return (long) getApply().applyAsDouble(getValue()); } public double applyAsDouble() { return getApply().applyAsDouble(getValue()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SampleAggregatedEntry.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SampleAggregatedEntry.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.metrics.aggregate; public class SampleAggregatedEntry { private Long count; private double max; private double min; private double avg; private double total; public Long getCount() { return count; } public void setCount(Long count) { this.count = count; } public double getMax() { return max; } public void setMax(double max) { this.max = max; } public double getMin() { return min; } public void setMin(double min) { this.min = min; } public double getAvg() { return avg; } public void setAvg(double avg) { this.avg = avg; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/DubboMergingDigest.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/DubboMergingDigest.java
/* * Licensed to Ted Dunning 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.metrics.aggregate; import org.apache.dubbo.metrics.exception.MetricsNeverHappenException; import com.tdunning.math.stats.Centroid; import com.tdunning.math.stats.ScaleFunction; import com.tdunning.math.stats.Sort; import com.tdunning.math.stats.TDigest; import java.nio.ByteBuffer; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicInteger; /** * Maintains a t-digest by collecting new points in a buffer that is then sorted occasionally and merged * into a sorted array that contains previously computed centroids. * <p> * This can be very fast because the cost of sorting and merging is amortized over several insertion. If * we keep N centroids total and have the input array is k long, then the amortized cost is something like * <p> * N/k + log k * <p> * These costs even out when N/k = log k. Balancing costs is often a good place to start in optimizing an * algorithm. For different values of compression factor, the following table shows estimated asymptotic * values of N and suggested values of k: * <table> * <thead> * <tr><td>Compression</td><td>N</td><td>k</td></tr> * </thead> * <tbody> * <tr><td>50</td><td>78</td><td>25</td></tr> * <tr><td>100</td><td>157</td><td>42</td></tr> * <tr><td>200</td><td>314</td><td>73</td></tr> * </tbody> * <caption>Sizing considerations for t-digest</caption> * </table> * <p> * The virtues of this kind of t-digest implementation include: * <ul> * <li>No allocation is required after initialization</li> * <li>The data structure automatically compresses existing centroids when possible</li> * <li>No Java object overhead is incurred for centroids since data is kept in primitive arrays</li> * </ul> * <p> * The current implementation takes the liberty of using ping-pong buffers for implementing the merge resulting * in a substantial memory penalty, but the complexity of an in place merge was not considered as worthwhile * since even with the overhead, the memory cost is less than 40 bytes per centroid which is much less than half * what the AVLTreeDigest uses and no dynamic allocation is required at all. */ public class DubboMergingDigest extends DubboAbstractTDigest { private int mergeCount = 0; private final double publicCompression; private final double compression; // points to the first unused centroid private final AtomicInteger lastUsedCell = new AtomicInteger(0); // sum_i weight[i] See also unmergedWeight private double totalWeight = 0; // number of points that have been added to each merged centroid private final double[] weight; // mean of points added to each merged centroid private final double[] mean; // history of all data added to centroids (for testing purposes) private List<List<Double>> data = null; double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; // sum_i tempWeight[i] private AtomicInteger unmergedWeight = new AtomicInteger(0); // this is the index of the next temporary centroid // this is a more Java-like convention than lastUsedCell uses private final AtomicInteger tempUsed = new AtomicInteger(0); private final double[] tempWeight; private final double[] tempMean; private List<List<Double>> tempData = null; // array used for sorting the temp centroids. This is a field // to avoid allocations during operation private final int[] order; // if true, alternate upward and downward merge passes public boolean useAlternatingSort = true; // if true, use higher working value of compression during construction, then reduce on presentation public boolean useTwoLevelCompression = true; // this forces centroid merging based on size limit rather than // based on accumulated k-index. This can be much faster since we // scale functions are more expensive than the corresponding // weight limits. public static boolean useWeightLimit = true; /** * Allocates a buffer merging t-digest. This is the normally used constructor that * allocates default sized internal arrays. Other versions are available, but should * only be used for special cases. * * @param compression The compression factor */ @SuppressWarnings("WeakerAccess") public DubboMergingDigest(double compression) { this(compression, -1); } /** * If you know the size of the temporary buffer for incoming points, you can use this entry point. * * @param compression Compression factor for t-digest. Same as 1/\delta in the paper. * @param bufferSize How many samples to retain before merging. */ @SuppressWarnings("WeakerAccess") public DubboMergingDigest(double compression, int bufferSize) { // we can guarantee that we only need ceiling(compression). this(compression, bufferSize, -1); } /** * Fully specified constructor. Normally only used for deserializing a buffer t-digest. * * @param compression Compression factor * @param bufferSize Number of temporary centroids * @param size Size of main buffer */ @SuppressWarnings("WeakerAccess") public DubboMergingDigest(double compression, int bufferSize, int size) { // ensure compression >= 10 // default size = 2 * ceil(compression) // default bufferSize = 5 * size // scale = max(2, bufferSize / size - 1) // compression, publicCompression = sqrt(scale-1)*compression, compression // ensure size > 2 * compression + weightLimitFudge // ensure bufferSize > 2*size // force reasonable value. Anything less than 10 doesn't make much sense because // too few centroids are retained if (compression < 10) { compression = 10; } // the weight limit is too conservative about sizes and can require a bit of extra room double sizeFudge = 0; if (useWeightLimit) { sizeFudge = 10; if (compression < 30) sizeFudge += 20; } // default size size = (int) Math.max(2 * compression + sizeFudge, size); // default buffer if (bufferSize == -1) { // TODO update with current numbers // having a big buffer is good for speed // experiments show bufferSize = 1 gives half the performance of bufferSize=10 // bufferSize = 2 gives 40% worse performance than 10 // but bufferSize = 5 only costs about 5-10% // // compression factor time(us) // 50 1 0.275799 // 50 2 0.151368 // 50 5 0.108856 // 50 10 0.102530 // 100 1 0.215121 // 100 2 0.142743 // 100 5 0.112278 // 100 10 0.107753 // 200 1 0.210972 // 200 2 0.148613 // 200 5 0.118220 // 200 10 0.112970 // 500 1 0.219469 // 500 2 0.158364 // 500 5 0.127552 // 500 10 0.121505 bufferSize = 5 * size; } // ensure enough space in buffer if (bufferSize <= 2 * size) { bufferSize = 2 * size; } // scale is the ratio of extra buffer to the final size // we have to account for the fact that we copy all live centroids into the incoming space double scale = Math.max(1, bufferSize / size - 1); //noinspection ConstantConditions if (!useTwoLevelCompression) { scale = 1; } // publicCompression is how many centroids the user asked for // compression is how many we actually keep this.publicCompression = compression; this.compression = Math.sqrt(scale) * publicCompression; // changing the compression could cause buffers to be too small, readjust if so if (size < this.compression + sizeFudge) { size = (int) Math.ceil(this.compression + sizeFudge); } // ensure enough space in buffer (possibly again) if (bufferSize <= 2 * size) { bufferSize = 2 * size; } weight = new double[size]; mean = new double[size]; tempWeight = new double[bufferSize]; tempMean = new double[bufferSize]; order = new int[bufferSize]; lastUsedCell.set(0); } public double getMin() { return min; } public double getMax() { return max; } /** * Over-ride the min and max values for testing purposes */ @SuppressWarnings("SameParameterValue") void setMinMax(double min, double max) { this.min = min; this.max = max; } /** * Turns on internal data recording. */ @Override public TDigest recordAllData() { super.recordAllData(); data = new ArrayList<>(); tempData = new ArrayList<>(); return this; } @Override void add(double x, int w, Centroid base) { add(x, w, base.data()); } @Override public void add(double x, int w) { add(x, w, (List<Double>) null); } private void add(double x, int w, List<Double> history) { if (Double.isNaN(x)) { return; } int where; synchronized (this) { // There is a small probability of entering here if (tempUsed.get() >= tempWeight.length - lastUsedCell.get() - 1) { mergeNewValues(); } where = tempUsed.getAndIncrement(); tempWeight[where] = w; tempMean[where] = x; unmergedWeight.addAndGet(w); } if (x < min) { min = x; } if (x > max) { max = x; } if (data != null) { if (tempData == null) { tempData = new ArrayList<>(); } while (tempData.size() <= where) { tempData.add(new ArrayList<Double>()); } if (history == null) { history = Collections.singletonList(x); } tempData.get(where).addAll(history); } } @Override public void add(List<? extends TDigest> others) { throw new MetricsNeverHappenException("Method not used"); } private void mergeNewValues() { mergeNewValues(false, compression); } private void mergeNewValues(boolean force, double compression) { if (totalWeight == 0 && unmergedWeight.get() == 0) { // seriously nothing to do return; } if (force || unmergedWeight.get() > 0) { // note that we run the merge in reverse every other merge to avoid left-to-right bias in merging merge(tempMean, tempWeight, tempUsed.get(), tempData, order, unmergedWeight.get(), useAlternatingSort & mergeCount % 2 == 1, compression); mergeCount++; tempUsed.set(0); unmergedWeight.set(0); if (data != null) { tempData = new ArrayList<>(); } } } private void merge(double[] incomingMean, double[] incomingWeight, int incomingCount, List<List<Double>> incomingData, int[] incomingOrder, double unmergedWeight, boolean runBackwards, double compression) { // when our incoming buffer fills up, we combine our existing centroids with the incoming data, // and then reduce the centroids by merging if possible assert lastUsedCell.get() <= 0 || weight[0] == 1; assert lastUsedCell.get() <= 0 || weight[lastUsedCell.get() - 1] == 1; System.arraycopy(mean, 0, incomingMean, incomingCount, lastUsedCell.get()); System.arraycopy(weight, 0, incomingWeight, incomingCount, lastUsedCell.get()); incomingCount += lastUsedCell.get(); if (incomingData != null) { for (int i = 0; i < lastUsedCell.get(); i++) { assert data != null; incomingData.add(data.get(i)); } data = new ArrayList<>(); } if (incomingOrder == null) { incomingOrder = new int[incomingCount]; } Sort.stableSort(incomingOrder, incomingMean, incomingCount); totalWeight += unmergedWeight; // option to run backwards is to help investigate bias in errors if (runBackwards) { Sort.reverse(incomingOrder, 0, incomingCount); } // start by copying the least incoming value to the normal buffer lastUsedCell.set(0); mean[lastUsedCell.get()] = incomingMean[incomingOrder[0]]; weight[lastUsedCell.get()] = incomingWeight[incomingOrder[0]]; double wSoFar = 0; if (data != null) { assert incomingData != null; data.add(incomingData.get(incomingOrder[0])); } // weight will contain all zeros after this loop double normalizer = scale.normalizer(compression, totalWeight); double k1 = scale.k(0, normalizer); double wLimit = totalWeight * scale.q(k1 + 1, normalizer); for (int i = 1; i < incomingCount; i++) { int ix = incomingOrder[i]; double proposedWeight = weight[lastUsedCell.get()] + incomingWeight[ix]; double projectedW = wSoFar + proposedWeight; boolean addThis; if (useWeightLimit) { double q0 = wSoFar / totalWeight; double q2 = (wSoFar + proposedWeight) / totalWeight; addThis = proposedWeight <= totalWeight * Math.min(scale.max(q0, normalizer), scale.max(q2, normalizer)); } else { addThis = projectedW <= wLimit; } if (i == 1 || i == incomingCount - 1) { // force last centroid to never merge addThis = false; } if (addThis) { // next point will fit // so merge into existing centroid weight[lastUsedCell.get()] += incomingWeight[ix]; mean[lastUsedCell.get()] = mean[lastUsedCell.get()] + (incomingMean[ix] - mean[lastUsedCell.get()]) * incomingWeight[ix] / weight[lastUsedCell.get()]; incomingWeight[ix] = 0; if (data != null) { while (data.size() <= lastUsedCell.get()) { data.add(new ArrayList<Double>()); } assert incomingData != null; assert data.get(lastUsedCell.get()) != incomingData.get(ix); data.get(lastUsedCell.get()).addAll(incomingData.get(ix)); } } else { // didn't fit ... move to next output, copy out first centroid wSoFar += weight[lastUsedCell.get()]; if (!useWeightLimit) { k1 = scale.k(wSoFar / totalWeight, normalizer); wLimit = totalWeight * scale.q(k1 + 1, normalizer); } lastUsedCell.getAndIncrement(); mean[lastUsedCell.get()] = incomingMean[ix]; weight[lastUsedCell.get()] = incomingWeight[ix]; incomingWeight[ix] = 0; if (data != null) { assert incomingData != null; assert data.size() == lastUsedCell.get(); data.add(incomingData.get(ix)); } } } // points to next empty cell lastUsedCell.getAndIncrement(); // sanity check double sum = 0; for (int i = 0; i < lastUsedCell.get(); i++) { sum += weight[i]; } assert sum == totalWeight; if (runBackwards) { Sort.reverse(mean, 0, lastUsedCell.get()); Sort.reverse(weight, 0, lastUsedCell.get()); if (data != null) { Collections.reverse(data); } } assert weight[0] == 1; assert weight[lastUsedCell.get() - 1] == 1; if (totalWeight > 0) { min = Math.min(min, mean[0]); max = Math.max(max, mean[lastUsedCell.get() - 1]); } } /** * Merges any pending inputs and compresses the data down to the public setting. * Note that this typically loses a bit of precision and thus isn't a thing to * be doing all the time. It is best done only when we want to show results to * the outside world. */ @Override public void compress() { mergeNewValues(true, publicCompression); } @Override public long size() { return (long) (totalWeight + unmergedWeight.get()); } @Override public double cdf(double x) { if (Double.isNaN(x) || Double.isInfinite(x)) { throw new IllegalArgumentException(String.format("Invalid value: %f", x)); } mergeNewValues(); if (lastUsedCell.get() == 0) { // no data to examine return Double.NaN; } else if (lastUsedCell.get() == 1) { // exactly one centroid, should have max==min double width = max - min; if (x < min) { return 0; } else if (x > max) { return 1; } else if (x - min <= width) { // min and max are too close together to do any viable interpolation return 0.5; } else { // interpolate if somehow we have weight > 0 and max != min return (x - min) / (max - min); } } else { int n = lastUsedCell.get(); if (x < min) { return 0; } if (x > max) { return 1; } // check for the left tail if (x < mean[0]) { // note that this is different than mean[0] > min // ... this guarantees we divide by non-zero number and interpolation works if (mean[0] - min > 0) { // must be a sample exactly at min if (x == min) { return 0.5 / totalWeight; } else { return (1 + (x - min) / (mean[0] - min) * (weight[0] / 2 - 1)) / totalWeight; } } else { // this should be redundant with the check x < min return 0; } } assert x >= mean[0]; // and the right tail if (x > mean[n - 1]) { if (max - mean[n - 1] > 0) { if (x == max) { return 1 - 0.5 / totalWeight; } else { // there has to be a single sample exactly at max double dq = (1 + (max - x) / (max - mean[n - 1]) * (weight[n - 1] / 2 - 1)) / totalWeight; return 1 - dq; } } else { return 1; } } // we know that there are at least two centroids and mean[0] < x < mean[n-1] // that means that there are either one or more consecutive centroids all at exactly x // or there are consecutive centroids, c0 < x < c1 double weightSoFar = 0; for (int it = 0; it < n - 1; it++) { // weightSoFar does not include weight[it] yet if (mean[it] == x) { // we have one or more centroids == x, treat them as one // dw will accumulate the weight of all of the centroids at x double dw = 0; while (it < n && mean[it] == x) { dw += weight[it]; it++; } return (weightSoFar + dw / 2) / totalWeight; } else if (mean[it] <= x && x < mean[it + 1]) { // landed between centroids ... check for floating point madness if (mean[it + 1] - mean[it] > 0) { // note how we handle singleton centroids here // the point is that for singleton centroids, we know that their entire // weight is exactly at the centroid and thus shouldn't be involved in // interpolation double leftExcludedW = 0; double rightExcludedW = 0; if (weight[it] == 1) { if (weight[it + 1] == 1) { // two singletons means no interpolation // left singleton is in, right is out return (weightSoFar + 1) / totalWeight; } else { leftExcludedW = 0.5; } } else if (weight[it + 1] == 1) { rightExcludedW = 0.5; } double dw = (weight[it] + weight[it + 1]) / 2; // can't have double singleton (handled that earlier) assert dw > 1; assert (leftExcludedW + rightExcludedW) <= 0.5; // adjust endpoints for any singleton double left = mean[it]; double right = mean[it + 1]; double dwNoSingleton = dw - leftExcludedW - rightExcludedW; // adjustments have only limited effect on endpoints assert dwNoSingleton > dw / 2; assert right - left > 0; double base = weightSoFar + weight[it] / 2 + leftExcludedW; return (base + dwNoSingleton * (x - left) / (right - left)) / totalWeight; } else { // this is simply caution against floating point madness // it is conceivable that the centroids will be different // but too near to allow safe interpolation double dw = (weight[it] + weight[it + 1]) / 2; return (weightSoFar + dw) / totalWeight; } } else { weightSoFar += weight[it]; } } if (x == mean[n - 1]) { return 1 - 0.5 / totalWeight; } else { throw new IllegalStateException("Can't happen ... loop fell through"); } } } @Override public double quantile(double q) { if (q < 0 || q > 1) { throw new IllegalArgumentException("q should be in [0,1], got " + q); } mergeNewValues(); if (lastUsedCell.get() == 0) { // no centroids means no data, no way to get a quantile return Double.NaN; } else if (lastUsedCell.get() == 1) { // with one data point, all quantiles lead to Rome return mean[0]; } // we know that there are at least two centroids now int n = lastUsedCell.get(); // if values were stored in a sorted array, index would be the offset we are interested in final double index = q * totalWeight; // beyond the boundaries, we return min or max // usually, the first centroid will have unit weight so this will make it moot if (index < 1) { return min; } // if the left centroid has more than one sample, we still know // that one sample occurred at min so we can do some interpolation if (weight[0] > 1 && index < weight[0] / 2) { // there is a single sample at min so we interpolate with less weight return min + (index - 1) / (weight[0] / 2 - 1) * (mean[0] - min); } // usually the last centroid will have unit weight so this test will make it moot if (index > totalWeight - 1) { return max; } // if the right-most centroid has more than one sample, we still know // that one sample occurred at max so we can do some interpolation if (weight[n - 1] > 1 && totalWeight - index <= weight[n - 1] / 2) { return max - (totalWeight - index - 1) / (weight[n - 1] / 2 - 1) * (max - mean[n - 1]); } // in between extremes we interpolate between centroids double weightSoFar = weight[0] / 2; for (int i = 0; i < n - 1; i++) { double dw = (weight[i] + weight[i + 1]) / 2; if (weightSoFar + dw > index) { // centroids i and i+1 bracket our current point // check for unit weight double leftUnit = 0; if (weight[i] == 1) { if (index - weightSoFar < 0.5) { // within the singleton's sphere return mean[i]; } else { leftUnit = 0.5; } } double rightUnit = 0; if (weight[i + 1] == 1) { if (weightSoFar + dw - index <= 0.5) { // no interpolation needed near singleton return mean[i + 1]; } rightUnit = 0.5; } double z1 = index - weightSoFar - leftUnit; double z2 = weightSoFar + dw - index - rightUnit; return weightedAverage(mean[i], z2, mean[i + 1], z1); } weightSoFar += dw; } // we handled singleton at end up above assert weight[n - 1] > 1; assert index <= totalWeight; assert index >= totalWeight - weight[n - 1] / 2; // weightSoFar = totalWeight - weight[n-1]/2 (very nearly) // so we interpolate out to max value ever seen double z1 = index - totalWeight - weight[n - 1] / 2.0; double z2 = weight[n - 1] / 2 - z1; return weightedAverage(mean[n - 1], z1, max, z2); } @Override public int centroidCount() { mergeNewValues(); return lastUsedCell.get(); } @Override public Collection<Centroid> centroids() { // we don't actually keep centroid structures around so we have to fake it compress(); return new AbstractCollection<Centroid>() { @Override public Iterator<Centroid> iterator() { return new Iterator<Centroid>() { int i = 0; @Override public boolean hasNext() { return i < lastUsedCell.get(); } @Override public Centroid next() { if (!hasNext()) { throw new NoSuchElementException(); } Centroid rc = new Centroid(mean[i], (int) weight[i]); List<Double> datas = data != null ? data.get(i) : null; if (datas != null) { datas.forEach(rc::insertData); } i++; return rc; } @Override public void remove() { throw new UnsupportedOperationException("Default operation"); } }; } @Override public int size() { return lastUsedCell.get(); } }; } @Override public double compression() { return publicCompression; } @Override public int byteSize() { compress(); // format code, compression(float), buffer-size(int), temp-size(int), #centroids-1(int), // then two doubles per centroid return lastUsedCell.get() * 16 + 32; } @Override public int smallByteSize() { compress(); // format code(int), compression(float), buffer-size(short), temp-size(short), #centroids-1(short), // then two floats per centroid return lastUsedCell.get() * 8 + 30; } @SuppressWarnings("WeakerAccess") public ScaleFunction getScaleFunction() { return scale; } @Override public void setScaleFunction(ScaleFunction scaleFunction) { super.setScaleFunction(scaleFunction); } public enum Encoding { VERBOSE_ENCODING(1), SMALL_ENCODING(2); private final int code; Encoding(int code) { this.code = code; } } @Override public void asBytes(ByteBuffer buf) { compress(); buf.putInt(DubboMergingDigest.Encoding.VERBOSE_ENCODING.code); buf.putDouble(min); buf.putDouble(max); buf.putDouble(publicCompression); buf.putInt(lastUsedCell.get()); for (int i = 0; i < lastUsedCell.get(); i++) { buf.putDouble(weight[i]); buf.putDouble(mean[i]); } } @Override public void asSmallBytes(ByteBuffer buf) { compress(); buf.putInt(DubboMergingDigest.Encoding.SMALL_ENCODING.code); // 4 buf.putDouble(min); // + 8 buf.putDouble(max); // + 8 buf.putFloat((float) publicCompression); // + 4 buf.putShort((short) mean.length); // + 2 buf.putShort((short) tempMean.length); // + 2 buf.putShort((short) lastUsedCell.get()); // + 2 = 30 for (int i = 0; i < lastUsedCell.get(); i++) { buf.putFloat((float) weight[i]); buf.putFloat((float) mean[i]); } } @Override public String toString() { return "MergingDigest" + "-" + getScaleFunction() + "-" + (useWeightLimit ? "weight" : "kSize") + "-" + (useAlternatingSort ? "alternating" : "stable") + "-" + (useTwoLevelCompression ? "twoLevel" : "oneLevel"); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantile.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantile.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.metrics.aggregate; import java.util.List; import java.util.concurrent.TimeUnit; import com.tdunning.math.stats.TDigest; /** * Wrapper around TDigest. */ public class TimeWindowQuantile { private final double compression; private final DigestSlidingWindow slidingWindow; public TimeWindowQuantile(double compression, int bucketNum, int timeWindowSeconds) { this.compression = compression; this.slidingWindow = new DigestSlidingWindow(compression, bucketNum, TimeUnit.SECONDS.toMillis(timeWindowSeconds)); } public double quantile(double q) { TDigest mergeDigest = new DubboMergingDigest(compression); List<TDigest> validWindows = this.slidingWindow.values(); for (TDigest window : validWindows) { mergeDigest.add(window); } // This may return Double.NaN, and it's correct behavior. // see: https://github.com/prometheus/client_golang/issues/85 return mergeDigest.quantile(q); } public void add(double value) { this.slidingWindow.currentPane().getValue().add(value); } /** * Sliding window of type TDigest. */ private static class DigestSlidingWindow extends SlidingWindow<TDigest> { private final double compression; public DigestSlidingWindow(double compression, int sampleCount, long intervalInMs) { super(sampleCount, intervalInMs); this.compression = compression; } @Override public TDigest newEmptyValue(long timeMillis) { return new DubboMergingDigest(compression); } @Override protected Pane<TDigest> resetPaneTo(final Pane<TDigest> pane, long startTime) { pane.setStartInMs(startTime); pane.setValue(new DubboMergingDigest(compression)); return pane; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/Pane.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/Pane.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.metrics.aggregate; /** * The pane represents a window over a period of time. * * @param <T> The type of value the pane statistics. */ public class Pane<T> { /** * Time interval of the pane in milliseconds. */ private final long intervalInMs; /** * Start timestamp of the pane in milliseconds. */ private volatile long startInMs; /** * End timestamp of the pane in milliseconds. * <p> * endInMs = startInMs + intervalInMs */ private volatile long endInMs; /** * Pane statistics value. */ private T value; /** * @param intervalInMs interval of the pane in milliseconds. * @param startInMs start timestamp of the pane in milliseconds. * @param value the pane value. */ public Pane(long intervalInMs, long startInMs, T value) { this.intervalInMs = intervalInMs; this.startInMs = startInMs; this.endInMs = this.startInMs + this.intervalInMs; this.value = value; } /** * Get the interval of the pane in milliseconds. * * @return the interval of the pane in milliseconds. */ public long getIntervalInMs() { return this.intervalInMs; } /** * Get start timestamp of the pane in milliseconds. * * @return the start timestamp of the pane in milliseconds. */ public long getStartInMs() { return this.startInMs; } /** * Get end timestamp of the pane in milliseconds. * * @return the end timestamp of the pane in milliseconds. */ public long getEndInMs() { return this.endInMs; } /** * Get the pane statistics value. * * @return the pane statistics value. */ public T getValue() { return this.value; } /** * Set the new start timestamp to the pane, for reset the instance. * * @param newStartInMs the new start timestamp. */ public void setStartInMs(long newStartInMs) { this.startInMs = newStartInMs; this.endInMs = this.startInMs + this.intervalInMs; } /** * Set new value to the pane, for reset the instance. * * @param newData the new value. */ public void setValue(T newData) { this.value = newData; } /** * Check whether given timestamp is in current pane. * * @param timeMillis timestamp in milliseconds. * @return true if the given time is in current pane, otherwise false */ public boolean isTimeInWindow(long timeMillis) { // [) return startInMs <= timeMillis && timeMillis < endInMs; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregator.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregator.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.metrics.aggregate; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.DoubleAccumulator; import java.util.concurrent.atomic.LongAdder; public class TimeWindowAggregator { private final SnapshotSlidingWindow slidingWindow; public TimeWindowAggregator(int bucketNum, int timeWindowSeconds) { this.slidingWindow = new SnapshotSlidingWindow(bucketNum, TimeUnit.SECONDS.toMillis(timeWindowSeconds)); } public SnapshotSlidingWindow getSlidingWindow() { return slidingWindow; } public void add(double value) { SnapshotObservation sample = this.slidingWindow.currentPane().getValue(); sample.add(value); } public SampleAggregatedEntry get() { SampleAggregatedEntry aggregatedEntry = new SampleAggregatedEntry(); double total = 0L; long count = 0; double max = Double.MIN_VALUE; double min = Double.MAX_VALUE; List<SnapshotObservation> windows = this.slidingWindow.values(); for (SnapshotObservation window : windows) { total += window.getTotal(); count += window.getCount(); max = Math.max(max, window.getMax()); min = Math.min(min, window.getMin()); } if (count > 0) { double avg = total / count; aggregatedEntry.setAvg(Math.round(avg * 100.0) / 100.0); } else { aggregatedEntry.setAvg(0); } aggregatedEntry.setMax(max == Double.MIN_VALUE ? 0 : max); aggregatedEntry.setMin(min == Double.MAX_VALUE ? 0 : min); aggregatedEntry.setTotal(total); aggregatedEntry.setCount(count); return aggregatedEntry; } public static class SnapshotSlidingWindow extends SlidingWindow<SnapshotObservation> { public SnapshotSlidingWindow(int sampleCount, long intervalInMs) { super(sampleCount, intervalInMs); } @Override public SnapshotObservation newEmptyValue(long timeMillis) { return new SnapshotObservation(); } @Override protected Pane<SnapshotObservation> resetPaneTo(final Pane<SnapshotObservation> pane, long startTime) { pane.setStartInMs(startTime); pane.getValue().reset(); return pane; } } public static class SnapshotObservation { private final AtomicReference<Double> min = new AtomicReference<>(Double.MAX_VALUE); private final AtomicReference<Double> max = new AtomicReference<>(0d); private final DoubleAccumulator total = new DoubleAccumulator((x, y) -> x + y, 0); private final LongAdder count = new LongAdder(); public void add(double sample) { total.accumulate(sample); count.increment(); updateMin(sample); updateMax(sample); } private void updateMin(double sample) { Double curMin; do { curMin = min.get(); } while (sample < curMin && !min.compareAndSet(curMin, sample)); } private void updateMax(double sample) { Double curMax; do { curMax = max.get(); if (sample <= curMax) { return; } } while (!max.compareAndSet(curMax, sample)); } public void reset() { min.set(Double.MAX_VALUE); max.set(0d); count.reset(); total.reset(); } public double getMin() { return min.get(); } public double getMax() { return max.get(); } public Double getTotal() { return total.get(); } public long getCount() { return count.sum(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false