From 2b37f8d007eb0bb68d8265d431aa4b73787ed0e0 Mon Sep 17 00:00:00 2001 From: walklown Date: Sat, 13 Apr 2024 23:30:06 +0800 Subject: [PATCH 01/12] Separate the code for indicator monitoring --- .artifacts | 3 +- dubbo-cluster/pom.xml | 12 - .../cluster/directory/AbstractDirectory.java | 45 ++-- .../directory/DirectoryRefreshEvent.java | 62 ++++++ ...che.dubbo.rpc.cluster.filter.ClusterFilter | 3 +- .../directory/StaticDirectoryTest.java | 3 - .../router/file/FileRouterEngineTest.java | 3 - .../support/AbstractClusterInvokerTest.java | 3 - .../support/ConnectivityValidationTest.java | 3 - .../support/FailoverClusterInvokerTest.java | 3 - .../MockAbstractClusterInvokerTest.java | 3 - .../wrapper/MockClusterInvokerTest.java | 3 - .../wrapper/MockProviderRpcExceptionTest.java | 3 - .../wrapper/ScopeClusterInvokerTest.java | 5 +- .../configcenter/ConfigCenterChangeEvent.java | 76 +++++++ .../event/AbstractDubboLifecycleListener.java | 25 +++ .../common/event/AbstractDubboListener.java | 24 +- .../dubbo/common/event/CustomAfterPost.java | 16 +- .../event/DefaultDubboEventMulticaster.java | 114 ++++++++++ .../DubboApplicationMulticasterRegistry.java | 38 +++- .../apache/dubbo/common/event/DubboEvent.java | 43 ++++ .../dubbo/common/event/DubboEventBus.java | 107 +++++---- .../common/event/DubboEventMulticaster.java | 48 ++++ .../event/DubboLifecycleEventMulticaster.java | 12 +- .../common/event/DubboLifecycleListener.java | 52 +++++ .../dubbo/common/event/DubboListener.java | 16 +- .../apache/dubbo/common/utils}/TimePair.java | 2 +- ...ache.dubbo.rpc.model.ScopeModelInitializer | 1 + .../dubbo/common/event/DubboEventTest.java | 210 ++++++++++++++++++ dubbo-config/dubbo-config-api/pom.xml | 38 +--- .../dubbo/config/InitServiceMethodEvent.java | 35 +++ .../apache/dubbo/config/ServiceConfig.java | 8 +- .../deploy/DefaultApplicationDeployer.java | 120 +--------- .../deploy/event/ApplicationLoadedEvent.java | 17 +- .../deploy/event/ApplicationStartedEvent.java | 27 +++ ...bbo.metrics.service.MetricsServiceExporter | 1 - ...mon.metrics.service.MetricsServiceExporter | 2 +- .../dubbo-configcenter-apollo/pom.xml | 20 -- .../support/apollo/ApolloConstants.java | 22 ++ .../apollo/ApolloDynamicConfiguration.java | 12 +- .../dubbo-configcenter-file/pom.xml | 20 -- .../dubbo-configcenter-nacos/pom.xml | 20 -- .../support/nacos/NacosConstants.java | 22 ++ .../nacos/NacosDynamicConfiguration.java | 12 +- .../dubbo-configcenter-zookeeper/pom.xml | 20 -- .../support/zookeeper/ZookeeperConstants.java | 22 ++ .../zookeeper/ZookeeperDataListener.java | 13 +- dubbo-distribution/dubbo-all-shaded/pom.xml | 16 ++ dubbo-distribution/dubbo-all/pom.xml | 12 +- dubbo-distribution/dubbo-bom/pom.xml | 7 +- dubbo-distribution/dubbo-core-spi/pom.xml | 2 + dubbo-metadata/dubbo-metadata-api/pom.xml | 19 -- .../dubbo/metadata/event/MetaDataEvent.java | 35 +++ .../metadata/event/MetaDataPushEvent.java | 26 +++ .../event/MetaDataServiceSubscribeEvent.java | 33 +++ .../event/MetaDataSubscribeEvent.java | 26 +++ .../support/AbstractMetadataReport.java | 12 +- .../pom.xml | 6 +- .../service/MetricsServiceExporter.java | 0 .../org/apache/dubbo/monitor/Constants.java | 0 .../org/apache/dubbo/monitor/Monitor.java | 0 .../apache/dubbo/monitor/MonitorFactory.java | 0 .../apache/dubbo/monitor/MonitorService.java | 0 dubbo-metrics/dubbo-metrics-api/pom.xml | 2 +- .../dubbo/metrics/MetricsConstants.java | 0 .../dubbo/metrics/MetricsGlobalRegistry.java | 0 .../ApplicationMetricsCollector.java | 3 +- .../collector/CombMetricsCollector.java | 31 +-- .../collector/MethodMetricsCollector.java | 3 +- .../metrics/collector/MetricsCollector.java | 8 +- .../collector/ServiceMetricsCollector.java | 3 +- .../dubbo/metrics/event/MetricsEvent.java | 33 +-- .../dubbo/metrics/event/TimeCounterEvent.java | 16 +- ....java => TimeCounterEventMulticaster.java} | 39 ++-- .../MetricsNeverHappenException.java | 0 .../listener/AbstractMetricsKeyListener.java | 19 +- .../listener/MetricsApplicationListener.java | 14 +- .../listener/MetricsServiceListener.java | 13 +- .../dubbo/metrics/model/MetricsSupport.java | 24 +- .../dubbo/metrics/model/key/MetricsKey.java | 0 .../dubbo/metrics/model/key/MetricsLevel.java | 0 .../dubbo/metrics/model/key/TypeWrapper.java | 0 .../dubbo/metrics/MetricsSupportTest.java | 8 + ...a => SimpleDubboEventMulticasterTest.java} | 30 ++- .../ConfigCenterMetricsCollector.java | 9 +- .../config/event/ConfigCenterEvent.java | 69 ------ .../event/ConfigCenterSubDispatcher.java | 37 +-- .../ConfigCenterMetricsCollectorTest.java | 28 ++- dubbo-metrics/dubbo-metrics-default/pom.xml | 5 + .../DefaultMetricsServiceExporter.java | 2 +- .../collector/AggregateMetricsCollector.java | 187 +++++++++------- .../collector/DefaultMetricsCollector.java | 59 +++-- .../collector/HistogramMetricsCollector.java | 71 +++--- .../metrics/event/DefaultSubDispatcher.java | 55 +++-- .../dubbo/metrics/event/MetricsInitEvent.java | 11 +- ...estEvent.java => RequestMetricsEvent.java} | 31 ++- .../filter}/MetricsConsumerFilter.java | 3 +- .../dubbo/metrics/filter/MetricsFilter.java | 18 +- .../service/DefaultMetricsService.java | 2 +- .../filter/support/MetricsClusterFilter.java | 17 +- ...bbo.metrics.service.MetricsServiceExporter | 1 + ...che.dubbo.rpc.cluster.filter.ClusterFilter | 1 + .../metrics/DefaultMetricsServiceTest.java | 3 + .../AggregateMetricsCollectorTest.java | 60 +++-- .../collector/DefaultCollectorTest.java | 24 +- .../collector/InitServiceMetricsTest.java | 10 +- .../sample/ThreadPoolMetricsSamplerTest.java | 11 + .../metrics/filter/MetricsFilterTest.java | 6 +- dubbo-metrics/dubbo-metrics-metadata/pom.xml | 5 + .../collector/MetadataMetricsCollector.java | 7 +- ...taEvent.java => MetadataMetricsEvent.java} | 54 +++-- .../metadata/event/MetadataSubDispatcher.java | 52 ++++- .../MetadataMetricsCollectorTest.java | 66 +++--- dubbo-metrics/dubbo-metrics-netty/pom.xml | 5 + .../collector/NettyMetricsCollector.java | 6 +- .../metrics/registry/event/NettyEvent.java | 50 ----- .../registry/event/NettyMetricsEvent.java | 68 ++++++ .../registry/event/NettySubDispatcher.java | 32 ++- .../MetricsSupportPrometheusTest.java | 4 +- .../PrometheusMetricsReporterTest.java | 3 +- dubbo-metrics/dubbo-metrics-registry/pom.xml | 5 + .../collector/RegistryMetricsCollector.java | 9 +- .../metrics/registry/event/RegistryEvent.java | 130 ----------- .../registry/event/RegistryMetricsEvent.java | 198 +++++++++++++++++ .../registry/event/RegistrySpecListener.java | 17 +- .../registry/event/RegistrySubDispatcher.java | 69 +++++- .../RegistryMetricsCollectorTest.java | 39 ++-- .../collector/RegistryMetricsTest.java | 39 ++-- dubbo-metrics/dubbo-metrics-starter/pom.xml | 62 ++++++ .../MetricsScopeModelInitializer.java} | 27 ++- .../metrics/MetricsServiceInitializer.java | 173 +++++++++++++++ ...ache.dubbo.rpc.model.ScopeModelInitializer | 0 .../metrics/collector/CollectorInitTest.java | 48 ++++ dubbo-metrics/dubbo-tracing/pom.xml | 2 +- dubbo-metrics/pom.xml | 3 +- dubbo-registry/dubbo-registry-api/pom.xml | 25 --- .../client/AbstractServiceDiscovery.java | 11 +- .../client/ServiceDiscoveryRegistry.java | 8 +- .../registry/client/event/RegistryEvent.java | 35 +++ .../client/event/RegistryNotifyEvent.java | 40 ++++ .../client/event/RegistryRegisterEvent.java | 35 +++ .../client/event/RegistryRsEvent.java | 50 +++++ .../client/event/RegistrySsEvent.java | 49 ++++ .../client/event/RegistrySubscribeEvent.java | 33 +++ .../ServiceInstancesChangedListener.java | 6 +- .../ServiceInstanceMetadataUtils.java | 8 +- .../integration/RegistryDirectory.java | 6 +- .../integration/RegistryProtocol.java | 8 +- .../client/ServiceDiscoveryRegistryTest.java | 4 + .../dubbo/remoting/exchange/Request.java | 3 +- dubbo-remoting/dubbo-remoting-netty4/pom.xml | 10 - .../remoting/transport/netty4/NettyEvent.java | 58 +++++ .../transport/netty4/NettyServer.java | 39 ++-- dubbo-test/dubbo-dependencies-all/pom.xml | 7 +- 154 files changed, 2745 insertions(+), 1392 deletions(-) create mode 100644 dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/DirectoryRefreshEvent.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigCenterChangeEvent.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboLifecycleListener.java rename dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java => dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboListener.java (64%) rename dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java => dubbo-common/src/main/java/org/apache/dubbo/common/event/CustomAfterPost.java (71%) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java rename dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java => dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java (53%) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEvent.java rename dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java => dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java (53%) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java rename dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java => dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleEventMulticaster.java (73%) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleListener.java rename dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java => dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboListener.java (72%) rename {dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model => dubbo-common/src/main/java/org/apache/dubbo/common/utils}/TimePair.java (97%) create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/common/event/DubboEventTest.java create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/InitServiceMethodEvent.java rename dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java => dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationLoadedEvent.java (70%) create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationStartedEvent.java delete mode 100644 dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter create mode 100644 dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloConstants.java create mode 100644 dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosConstants.java create mode 100644 dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperConstants.java create mode 100644 dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataEvent.java create mode 100644 dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataPushEvent.java create mode 100644 dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataServiceSubscribeEvent.java create mode 100644 dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataSubscribeEvent.java rename dubbo-metrics/{dubbo-metrics-event => dubbo-metrics-annotation}/pom.xml (92%) rename dubbo-metrics/{dubbo-metrics-api => dubbo-metrics-annotation}/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java (100%) rename dubbo-metrics/{dubbo-metrics-api => dubbo-metrics-annotation}/src/main/java/org/apache/dubbo/monitor/Constants.java (100%) rename dubbo-metrics/{dubbo-metrics-api => dubbo-metrics-annotation}/src/main/java/org/apache/dubbo/monitor/Monitor.java (100%) rename dubbo-metrics/{dubbo-metrics-api => dubbo-metrics-annotation}/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java (100%) rename dubbo-metrics/{dubbo-metrics-api => dubbo-metrics-annotation}/src/main/java/org/apache/dubbo/monitor/MonitorService.java (100%) rename dubbo-metrics/{dubbo-metrics-event => dubbo-metrics-api}/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java (100%) rename dubbo-metrics/{dubbo-metrics-default => dubbo-metrics-api}/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java (100%) rename dubbo-metrics/{dubbo-metrics-event => dubbo-metrics-api}/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java (77%) rename dubbo-metrics/{dubbo-metrics-event => dubbo-metrics-api}/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java (77%) rename dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/{SimpleMetricsEventMulticaster.java => TimeCounterEventMulticaster.java} (58%) rename dubbo-metrics/{dubbo-metrics-event => dubbo-metrics-api}/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java (100%) rename dubbo-metrics/{dubbo-metrics-event => dubbo-metrics-api}/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java (100%) rename dubbo-metrics/{dubbo-metrics-event => dubbo-metrics-api}/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java (100%) rename dubbo-metrics/{dubbo-metrics-event => dubbo-metrics-api}/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java (100%) rename dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/{SimpleMetricsEventMulticasterTest.java => SimpleDubboEventMulticasterTest.java} (79%) delete mode 100644 dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java rename {dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy => dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics}/DefaultMetricsServiceExporter.java (99%) rename dubbo-metrics/{dubbo-metrics-api => dubbo-metrics-default}/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java (82%) rename dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/{RequestEvent.java => RequestMetricsEvent.java} (80%) rename {dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support => dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter}/MetricsConsumerFilter.java (94%) create mode 100644 dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter rename dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/{MetadataEvent.java => MetadataMetricsEvent.java} (57%) delete mode 100644 dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.java create mode 100644 dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyMetricsEvent.java rename dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployerTest.java => dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/MetricsSupportPrometheusTest.java (92%) delete mode 100644 dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java create mode 100644 dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryMetricsEvent.java create mode 100644 dubbo-metrics/dubbo-metrics-starter/pom.xml rename dubbo-metrics/{dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java => dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java} (62%) create mode 100644 dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java rename dubbo-metrics/{dubbo-metrics-default => dubbo-metrics-starter}/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer (100%) create mode 100644 dubbo-metrics/dubbo-metrics-starter/src/test/java/org/apache/dubbo/metrics/collector/CollectorInitTest.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryNotifyEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRegisterEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRsEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySsEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySubscribeEvent.java create mode 100644 dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEvent.java diff --git a/.artifacts b/.artifacts index 5818a24e9ad..eb3010b473c 100644 --- a/.artifacts +++ b/.artifacts @@ -59,7 +59,8 @@ dubbo-metrics-prometheus dubbo-metrics-registry dubbo-metrics-config-center dubbo-metrics-netty -dubbo-metrics-event +dubbo-metrics-annotation +dubbo-metrics-starter dubbo-native dubbo-parent dubbo-plugin diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index f5136d52cfe..1c7e3332fec 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -75,18 +75,6 @@ ${project.parent.version} test - - org.apache.dubbo - dubbo-metrics-registry - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - true - io.micrometer micrometer-tracing-integration-test diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java index be68810f4ae..eef0600b406 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java @@ -21,6 +21,7 @@ import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.LoggerCodeConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; @@ -28,9 +29,6 @@ import org.apache.dubbo.common.utils.LockUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.model.key.MetricsKey; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcContext; @@ -46,7 +44,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -393,14 +390,13 @@ public void checkConnectivity() { checkConnectivity(); } }); - MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent( - applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish( + new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); }, reconnectTaskPeriod, TimeUnit.MILLISECONDS); } - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); } /** @@ -416,8 +412,7 @@ public void refreshInvoker() { refreshInvokerInternal(); } }); - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); } protected Map getDirectoryMeta() { @@ -452,8 +447,7 @@ public void addDisabledInvoker(Invoker invoker) { logger.info("Disable service address: " + invoker.getUrl() + "."); } }); - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); } @Override @@ -468,8 +462,7 @@ public void recoverDisabledInvoker(Invoker invoker) { } } }); - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); } protected final void refreshRouter(BitList> newlyInvokers, Runnable switchAction) { @@ -532,8 +525,7 @@ protected void setInvokers(BitList> invokers) { this.invokersInitialized = true; }); - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); } protected void destroyInvokers() { @@ -550,8 +542,7 @@ private boolean addValidInvoker(Invoker invoker) { LockUtils.safeLock(invokerRefreshLock, LockUtils.DEFAULT_TIMEOUT, () -> { result.set(this.validInvokers.add(invoker)); }); - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); return result.get(); } @@ -560,8 +551,7 @@ private boolean removeValidInvoker(Invoker invoker) { LockUtils.safeLock(invokerRefreshLock, LockUtils.DEFAULT_TIMEOUT, () -> { result.set(this.validInvokers.remove(invoker)); }); - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); return result.get(); } @@ -581,14 +571,13 @@ protected String joinValidInvokerAddresses() { .collect(Collectors.joining(",")); } - private Map> getSummary() { - Map> summaryMap = new HashMap<>(); - - summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_VALID, groupByServiceKey(getValidInvokers())); - summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_DISABLE, groupByServiceKey(getDisabledInvokers())); - summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_TO_RECONNECT, groupByServiceKey(getInvokersToReconnect())); - summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_ALL, groupByServiceKey(getInvokers())); - return summaryMap; + private DirectoryRefreshEvent.Summary getSummary() { + DirectoryRefreshEvent.Summary summary = new DirectoryRefreshEvent.Summary(); + summary.directoryNumValidMap = groupByServiceKey(getValidInvokers()); + summary.directoryNumDisableMap = groupByServiceKey(getDisabledInvokers()); + summary.directoryNumToReConnectMap = groupByServiceKey(getInvokersToReconnect()); + summary.directoryNumAllMap = groupByServiceKey(getInvokers()); + return summary; } private Map groupByServiceKey(Collection> invokers) { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/DirectoryRefreshEvent.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/DirectoryRefreshEvent.java new file mode 100644 index 00000000000..8cd8ae761c3 --- /dev/null +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/DirectoryRefreshEvent.java @@ -0,0 +1,62 @@ +/* + * 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.rpc.cluster.directory; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.Map; + +public class DirectoryRefreshEvent extends DubboEvent { + + private final TimePair timePair; + + private final Summary summary; + + private final Map attachments; + + public DirectoryRefreshEvent(ApplicationModel applicationModel, Summary summary, Map attachments) { + super(applicationModel); + this.summary = summary; + this.attachments = attachments; + this.timePair = TimePair.start(); + } + + public Summary getSummary() { + return summary; + } + + public Map getAttachments() { + return attachments; + } + + public TimePair getTimePair() { + return timePair; + } + + public static class Summary { + + public Map directoryNumValidMap; + + public Map directoryNumDisableMap; + + public Map directoryNumToReConnectMap; + + public Map directoryNumAllMap; + } +} diff --git a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter index 4e0de2450af..b1494d9a906 100644 --- a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter +++ b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter @@ -1,4 +1,3 @@ consumercontext=org.apache.dubbo.rpc.cluster.filter.support.ConsumerContextFilter consumer-classloader=org.apache.dubbo.rpc.cluster.filter.support.ConsumerClassLoaderFilter -router-snapshot=org.apache.dubbo.rpc.cluster.router.RouterSnapshotFilter -metricsConsumerFilter=org.apache.dubbo.rpc.cluster.filter.support.MetricsConsumerFilter +router-snapshot=org.apache.dubbo.rpc.cluster.router.RouterSnapshotFilter \ No newline at end of file diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java index d18bb8fe66f..a17ae0f74f2 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java @@ -19,14 +19,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.Holder; import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.router.MockInvoker; import org.apache.dubbo.rpc.cluster.router.condition.ConditionStateRouterFactory; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.cluster.router.state.StateRouter; -import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; @@ -70,7 +68,6 @@ void testStaticDirectory() { new RpcInvocation(), false, new Holder<>()); - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); StaticDirectory staticDirectory = new StaticDirectory<>(filteredInvokers); boolean isAvailable = staticDirectory.isAvailable(); Assertions.assertTrue(isAvailable); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java index e2aff971362..67d2b9b26bd 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -31,7 +30,6 @@ import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; -import org.apache.dubbo.rpc.model.ApplicationModel; import javax.script.ScriptEngineManager; @@ -63,7 +61,6 @@ class FileRouterEngineTest { @BeforeAll public static void setUpBeforeClass() throws Exception { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); System.setProperty(ENABLE_CONNECTIVITY_VALIDATION, "false"); } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java index 6cbed8481fc..05d5d05c97a 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java @@ -20,7 +20,6 @@ import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; @@ -34,7 +33,6 @@ import org.apache.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance; import org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance; import org.apache.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance; -import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.Collections; @@ -109,7 +107,6 @@ public static void afterClass() { @SuppressWarnings({"unchecked"}) @BeforeEach public void setUp() throws Exception { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); Map attributes = new HashMap<>(); attributes.put("application", "abstractClusterInvokerTest"); url = url.putAttribute(REFER_KEY, attributes); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java index a2f6b1499fe..11f721bf0ac 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java @@ -19,7 +19,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; @@ -28,7 +27,6 @@ import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; -import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.HashSet; @@ -72,7 +70,6 @@ class ConnectivityValidationTest { @BeforeEach public void setup() { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); invoker1 = Mockito.mock(Invoker.class); invoker2 = Mockito.mock(Invoker.class); invoker3 = Mockito.mock(Invoker.class); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java index bc48b8629c1..baeac3aafbb 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; @@ -30,7 +29,6 @@ import org.apache.dubbo.rpc.cluster.SingleRouterChain; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.router.state.BitList; -import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import java.util.ArrayList; @@ -67,7 +65,6 @@ class FailoverClusterInvokerTest { */ @BeforeEach public void setUp() throws Exception { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MockAbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MockAbstractClusterInvokerTest.java index 5a31ff663a6..bdf5b86e503 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MockAbstractClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MockAbstractClusterInvokerTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; @@ -26,7 +25,6 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; -import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.HashMap; @@ -89,7 +87,6 @@ public static void afterClass() { @SuppressWarnings({"unchecked"}) @BeforeEach public void setUp() throws Exception { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); Map attributes = new HashMap<>(); attributes.put("application", "abstractClusterInvokerTest"); url = url.putAttribute(REFER_KEY, attributes); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java index cc4dbb94bc9..6ffef03bf3b 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; @@ -29,7 +28,6 @@ import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; -import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.support.MockProtocol; import java.util.ArrayList; @@ -51,7 +49,6 @@ class MockClusterInvokerTest { @BeforeEach public void beforeMethod() { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); invokers.clear(); } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java index 4851e1790b5..e63892b37c9 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; @@ -28,7 +27,6 @@ import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; -import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.Arrays; @@ -48,7 +46,6 @@ class MockProviderRpcExceptionTest { @BeforeEach public void beforeMethod() { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); invokers.clear(); } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java index f04617e6687..d59188731e5 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -67,9 +66,7 @@ class ScopeClusterInvokerTest { private final List> exporters = new ArrayList<>(); @BeforeEach - void beforeMonth() { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); - } + void beforeMonth() {} @AfterEach void after() throws Exception { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigCenterChangeEvent.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigCenterChangeEvent.java new file mode 100644 index 00000000000..0770ef7ccfe --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigCenterChangeEvent.java @@ -0,0 +1,76 @@ +/* + * 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.common.config.configcenter; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class ConfigCenterChangeEvent extends DubboEvent { + + private final String key; + + private final String group; + + private final String protocol; + + private final String changeType; + + private final int count; + + private final TimePair timePair; + + public ConfigCenterChangeEvent( + ApplicationModel source, String key, String group, String protocol, String changeType) { + this(source, key, group, protocol, changeType, 1); + } + + public ConfigCenterChangeEvent( + ApplicationModel source, String key, String group, String protocol, String changeType, int count) { + super(source); + this.key = key; + this.group = group; + this.protocol = protocol; + this.changeType = changeType; + this.count = count; + this.timePair = TimePair.start(); + } + + public TimePair getTimePair() { + return timePair; + } + + public String getKey() { + return key; + } + + public String getGroup() { + return group; + } + + public String getProtocol() { + return protocol; + } + + public String getChangeType() { + return changeType; + } + + public int getCount() { + return count; + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboLifecycleListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboLifecycleListener.java new file mode 100644 index 00000000000..6887c4d1f4d --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboLifecycleListener.java @@ -0,0 +1,25 @@ +/* + * 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.common.event; + +/** + * Abstract Dubbo Lifecycle Listener. Abstract Dubbo Listener. Match the event type by generic type. + * + * @param the event to respond to + */ +public abstract class AbstractDubboLifecycleListener extends AbstractDubboListener + implements DubboLifecycleListener {} diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboListener.java similarity index 64% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboListener.java index dce4a8b207a..a3c2dae4af0 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboListener.java @@ -14,27 +14,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.listener; +package org.apache.dubbo.common.event; import org.apache.dubbo.common.utils.ReflectionUtils; -import org.apache.dubbo.metrics.event.MetricsEvent; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -public abstract class AbstractMetricsListener implements MetricsListener { +/** + * Abstract Dubbo Listener. Match the event type by generic type. + * + * @param the event to respond to + */ +public abstract class AbstractDubboListener implements DubboListener { private final Map, Boolean> eventMatchCache = new ConcurrentHashMap<>(); /** * Whether to support the general determination of event points depends on the event type */ - public boolean isSupport(MetricsEvent event) { - Boolean eventMatch = eventMatchCache.computeIfAbsent( - event.getClass(), clazz -> ReflectionUtils.match(getClass(), AbstractMetricsListener.class, event)); - return event.isAvailable() && eventMatch; - } - @Override - public abstract void onEvent(E event); + public boolean support(Class eventClass) { + return eventMatchCache.computeIfAbsent(eventClass, clazz -> { + List> eventTypes = ReflectionUtils.getClassGenerics(getClass(), AbstractDubboListener.class); + return eventTypes.stream().allMatch(eventType -> eventType.isAssignableFrom(clazz)); + }); + } } diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/CustomAfterPost.java similarity index 71% rename from dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/CustomAfterPost.java index 157df551d40..73507cb78dd 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/CustomAfterPost.java @@ -14,12 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.config; +package org.apache.dubbo.common.event; -public interface ConfigCenterMetricsConstants { +/** + * Custom method after post action and before publish after event + * + * @param The result type of post + * @since 3.3.0 + * @see DubboEventBus#after(DubboEvent, Object) + */ +public interface CustomAfterPost { - String ATTACHMENT_KEY_CONFIG_FILE = "configFileKey"; - String ATTACHMENT_KEY_CONFIG_GROUP = "configGroup"; - String ATTACHMENT_KEY_CONFIG_PROTOCOL = "configProtocol"; - String ATTACHMENT_KEY_CHANGE_TYPE = "configChangeType"; + void customAfterPost(R postResult); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java new file mode 100644 index 00000000000..06a37292f10 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java @@ -0,0 +1,114 @@ +/* + * 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.common.event; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArraySet; + +public class DefaultDubboEventMulticaster implements DubboLifecycleEventMulticaster { + + /** + * All registered subscribers, indexed by event type. + * + *

The {@link CopyOnWriteArraySet} values make it easy and relatively lightweight to get an + * immutable snapshot of all current subscribers to an event without any locking. + */ + private final Set> listeners = new CopyOnWriteArraySet<>(); + + final Map, Set>> listenerCache = new ConcurrentHashMap<>(64); + + /** + * Registers all subscriber methods on the given listener object. + * + * @param listener object whose subscriber methods should be registered. + */ + @Override + public void addListener(DubboListener listener) { + synchronized (this.listeners) { + this.listeners.add(listener); + listenerCache.clear(); + } + } + + /** + * Registers all subscriber methods on the given listener object. + * + * @param listener object whose subscriber methods should be registered. + */ + @Override + public void removeListener(DubboListener listener) { + synchronized (this.listeners) { + this.listeners.remove(listener); + listenerCache.clear(); + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void publishEvent(DubboEvent event) { + for (DubboListener listener : getListeners(event.getClass())) { + listener.onEvent(event); + } + } + + /** + * Return the listeners for the given event type. + * + * @param eventType the type of event to find listeners for. + * @return a live {@link Collection} of listeners for the given event type. If no listeners are + * found, this method returns an empty collection. + */ + public Collection> getListeners(Class eventType) { + return listenerCache.computeIfAbsent(eventType, key -> { + Set> listeners = new CopyOnWriteArraySet<>(); + for (DubboListener listener : this.listeners) { + if (listener.support(eventType)) { + listeners.add(listener); + } + } + return listeners; + }); + } + + /** + * Remove a listener from the notification list. + * + * @param listener the listener to remove + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void publishBeforeEvent(DubboEvent event) { + for (DubboListener listener : getListeners(event.getClass())) { + if (listener instanceof DubboLifecycleListener) { + ((DubboLifecycleListener) listener).onEventBefore(event); + } + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void publishErrorEvent(DubboEvent event) { + for (DubboListener listener : getListeners(event.getClass())) { + if (listener instanceof DubboLifecycleListener) { + ((DubboLifecycleListener) listener).onEventError(event); + } + } + } +} diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java similarity index 53% rename from dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java index 01e174ad0b3..b6a549fc39e 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java @@ -14,26 +14,52 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics; +package org.apache.dubbo.common.event; -import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; +import org.apache.dubbo.rpc.model.ScopeModelDestroyListener; import org.apache.dubbo.rpc.model.ScopeModelInitializer; -public class MetricsScopeModelInitializer implements ScopeModelInitializer { +import java.util.concurrent.ConcurrentHashMap; + +/** + * Initialize {@link DubboLifecycleEventMulticaster} for {@link ApplicationModel} + * + * @see DubboEventBus + * @see DubboLifecycleEventMulticaster + * @since 3.3.0 + */ +public class DubboApplicationMulticasterRegistry + implements ScopeModelInitializer, ScopeModelDestroyListener { + + private static final ConcurrentHashMap multicasterMap = + new ConcurrentHashMap<>(); @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { - ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); - beanFactory.registerBean(MetricsDispatcher.class); + multicasterMap.computeIfAbsent(applicationModel, t -> new DefaultDubboEventMulticaster()); + applicationModel.addDestroyListener(this); } @Override public void initializeModuleModel(ModuleModel moduleModel) {} + + @Override + public void onDestroy(ApplicationModel scopeModel) { + multicasterMap.remove(scopeModel); + } + + @Override + public boolean isProtocol() { + return true; + } + + public static DubboLifecycleEventMulticaster getMulticaster(ApplicationModel applicationModel) { + return multicasterMap.get(applicationModel); + } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEvent.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEvent.java new file mode 100644 index 00000000000..3d3d0ff0902 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEvent.java @@ -0,0 +1,43 @@ +/* + * 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.common.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.EventObject; + +/** + * Dubbo Event Object + * + * @since 3.3.0 + */ +public class DubboEvent extends EventObject { + + /** + * Constructs a prototypical Event. + * + * @param source The object on which the Event initially occurred. + * @throws IllegalArgumentException if source is null. + */ + public DubboEvent(ApplicationModel source) { + super(source); + } + + public ApplicationModel getApplicationModel() { + return (ApplicationModel) getSource(); + } +} diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java similarity index 53% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java index 7654c2d9020..bbace72f192 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java @@ -14,12 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.event; +package org.apache.dubbo.common.event; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.rpc.model.ApplicationModel; -import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; @@ -27,24 +27,47 @@ /** * Dispatches events to listeners, and provides ways for listeners to register themselves. + * + * @see DubboEvent + * @see DubboListener + * @see DubboLifecycleEventMulticaster + * @since 3.3.0 */ -public class MetricsEventBus { +public class DubboEventBus { + + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboEventBus.class); - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MetricsEventBus.class); + private DubboEventBus() {} + + /** + * Registers all subscriber methods on {@code object} to receive events. + * + * @param listener object whose subscriber methods should be registered. + */ + public static void addListener(ApplicationModel applicationModel, DubboListener listener) { + getMulticaster(applicationModel).addListener(listener); + } + + /** + * Unregisters all subscriber methods on a registered {@code object}. + * + * @param listener object whose subscriber methods should be unregistered. + * @throws IllegalArgumentException if the object was not previously registered. + */ + public static void removeListener(ApplicationModel applicationModel, DubboListener listener) { + getMulticaster(applicationModel).removeListener(listener); + } /** * Posts an event to all registered subscribers and only once. * * @param event event to post. */ - public static void publish(MetricsEvent event) { + public static void publish(DubboEvent event) { if (event.getSource() == null) { return; } - MetricsEventMulticaster dispatcher = event.getMetricsEventMulticaster(); - Optional.ofNullable(dispatcher).ifPresent(d -> { - tryInvoke(() -> d.publishEvent(event)); - }); + tryInvoke(() -> getMulticaster(event.getApplicationModel()).publishEvent(event)); } /** @@ -55,7 +78,7 @@ public static void publish(MetricsEvent event) { * @param event event to post. * @param targetSupplier original processing result targetSupplier */ - public static T post(MetricsEvent event, Supplier targetSupplier) { + public static T post(DubboEvent event, Supplier targetSupplier) { return post(event, targetSupplier, null); } @@ -68,30 +91,29 @@ public static T post(MetricsEvent event, Supplier targetSupplier) { * @param Biz result type * @return Biz result */ - public static T post(MetricsEvent event, Supplier targetSupplier, Function trFunction) { + public static T post(DubboEvent event, Supplier targetSupplier, Function trFunction) { T result; tryInvoke(() -> before(event)); + try { + result = targetSupplier.get(); + } catch (Throwable e) { + tryInvoke(() -> error(event)); + throw e; + } if (trFunction == null) { - try { - result = targetSupplier.get(); - } catch (Throwable e) { - tryInvoke(() -> error(event)); - throw e; - } + tryInvoke(() -> after(event, result)); + return result; + } + // Custom failure status + if (trFunction.apply(result)) { tryInvoke(() -> after(event, result)); } else { - // Custom failure status - result = targetSupplier.get(); - if (trFunction.apply(result)) { - tryInvoke(() -> after(event, result)); - } else { - tryInvoke(() -> error(event)); - } + tryInvoke(() -> error(event)); } return result; } - public static void tryInvoke(Runnable runnable) { + private static void tryInvoke(Runnable runnable) { try { runnable.run(); } catch (Throwable e) { @@ -103,36 +125,25 @@ public static void tryInvoke(Runnable runnable) { * Applicable to the scene where execution and return are separated, * eventSaveRunner saves the event, so that the calculation rt is introverted */ - public static void before(MetricsEvent event) { - MetricsEventMulticaster dispatcher = validate(event); - - if (dispatcher == null) return; - tryInvoke(() -> dispatcher.publishEvent(event)); + public static void before(DubboEvent event) { + tryInvoke(() -> getMulticaster(event.getApplicationModel()).publishBeforeEvent(event)); } - public static void after(MetricsEvent event, Object result) { - MetricsEventMulticaster dispatcher = validate(event); - if (dispatcher == null) return; + @SuppressWarnings({"unchecked", "rawtypes"}) + public static void after(DubboEvent event, Object result) { tryInvoke(() -> { - event.customAfterPost(result); - dispatcher.publishFinishEvent((TimeCounterEvent) event); + if (event instanceof CustomAfterPost) { + ((CustomAfterPost) event).customAfterPost(result); + } + getMulticaster(event.getApplicationModel()).publishEvent(event); }); } - public static void error(MetricsEvent event) { - MetricsEventMulticaster dispatcher = validate(event); - if (dispatcher == null) return; - tryInvoke(() -> dispatcher.publishErrorEvent((TimeCounterEvent) event)); + public static void error(DubboEvent event) { + tryInvoke(() -> getMulticaster(event.getApplicationModel()).publishErrorEvent(event)); } - private static MetricsEventMulticaster validate(MetricsEvent event) { - MetricsEventMulticaster dispatcher = event.getMetricsEventMulticaster(); - if (dispatcher == null) { - return null; - } - if (!(event instanceof TimeCounterEvent)) { - return null; - } - return dispatcher; + private static DubboLifecycleEventMulticaster getMulticaster(ApplicationModel applicationModel) { + return DubboApplicationMulticasterRegistry.getMulticaster(applicationModel); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java new file mode 100644 index 00000000000..ecfae62a689 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java @@ -0,0 +1,48 @@ +/* + * 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.common.event; + +/** + * Dispatches events to listeners, and provides ways for listeners to register themselves. + * + * @since 3.3.0 + * @see DubboEvent + * @see DubboListener + */ +public interface DubboEventMulticaster { + + /** + * Add a listener to be notified of all events. + * + * @param listener the listener to add + */ + void addListener(DubboListener listener); + + /** + * Add a listener to be notified of all events. + * + * @param listener the listener to add + */ + void removeListener(DubboListener listener); + + /** + * Publish the given event to all listeners. + * + * @param event the event to publish + */ + void publishEvent(DubboEvent event); +} diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleEventMulticaster.java similarity index 73% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleEventMulticaster.java index 67dd2ad8fd6..836844a9745 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleEventMulticaster.java @@ -14,16 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.listener; - -import org.apache.dubbo.metrics.event.TimeCounterEvent; +package org.apache.dubbo.common.event; /** - * Metrics Listener. + * Support publish before event and error event */ -public interface MetricsLifeListener extends MetricsListener { +public interface DubboLifecycleEventMulticaster extends DubboEventMulticaster { - default void onEventFinish(E event) {} + void publishBeforeEvent(DubboEvent event); - default void onEventError(E event) {} + void publishErrorEvent(DubboEvent event); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleListener.java new file mode 100644 index 00000000000..39b95df6bff --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleListener.java @@ -0,0 +1,52 @@ +/* + * 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.common.event; + +/** + * Dubbo Lifecycle Listener. + */ +public interface DubboLifecycleListener extends DubboListener { + + @Override + default void onEvent(E event) { + this.onEventFinish(event); + } + + /** + * notify event. + * + * @param event BaseMetricsEvent + */ + default void onEventBefore(E event) {} + ; + + /** + * notify event. + * + * @param event BaseMetricsEvent + */ + default void onEventFinish(E event) {} + ; + + /** + * notify event. + * + * @param event BaseMetricsEvent + */ + default void onEventError(E event) {} + ; +} diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboListener.java similarity index 72% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboListener.java index 048625fb02f..80279a74c74 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboListener.java @@ -14,16 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.listener; +package org.apache.dubbo.common.event; -import org.apache.dubbo.metrics.event.MetricsEvent; +import java.util.EventListener; /** - * Metrics Listener. + * Dubbo Listener. */ -public interface MetricsListener { +public interface DubboListener extends EventListener { - boolean isSupport(MetricsEvent event); + /** + * if support event. + * + * @param eventClass the event to respond to + * @return if support + */ + boolean support(Class eventClass); /** * notify event. diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/TimePair.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimePair.java similarity index 97% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/TimePair.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimePair.java index c00e96bbb74..32b75a45d35 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/TimePair.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimePair.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.model; +package org.apache.dubbo.common.utils; public class TimePair { diff --git a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer index fdd8f8be8a4..956665085f0 100644 --- a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer +++ b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer @@ -1 +1,2 @@ dubbo-common=org.apache.dubbo.common.CommonScopeModelInitializer +application-multicaster-registry=org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry \ No newline at end of file diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/event/DubboEventTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/event/DubboEventTest.java new file mode 100644 index 00000000000..bdceba3fdf1 --- /dev/null +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/event/DubboEventTest.java @@ -0,0 +1,210 @@ +/* + * 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.common.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.model.FrameworkModel; +import org.apache.dubbo.rpc.model.ModuleModel; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class DubboEventTest { + + private FrameworkModel frameworkModel; + private ApplicationModel applicationModel; + private ModuleModel moduleModel; + + @BeforeEach + public void setUp() { + frameworkModel = new FrameworkModel(); + applicationModel = frameworkModel.newApplication(); + moduleModel = applicationModel.newModule(); + } + + @AfterEach + public void reset() { + frameworkModel.destroy(); + } + + @Test + public void testDubboListener() { + AtomicInteger num = new AtomicInteger(0); + List> classes = new ArrayList<>(); + DubboListener dubboListener = new DubboListener() { + @Override + public boolean support(Class eventClass) { + classes.add(eventClass); + return true; + } + + @Override + public void onEvent(DubboEvent event) { + num.incrementAndGet(); + } + }; + DubboEventBus.addListener(applicationModel, dubboListener); + + FirstDubboEvent firstDubboEvent = new FirstDubboEvent(applicationModel); + SecondDubboEvent secondDubboEvent = new SecondDubboEvent(applicationModel); + DubboEventBus.publish(firstDubboEvent); + DubboEventBus.publish(secondDubboEvent); + + Assertions.assertEquals(num.get(), 2); + Assertions.assertEquals(classes.size(), 2); + Assertions.assertTrue(classes.contains(FirstDubboEvent.class)); + Assertions.assertTrue(classes.contains(SecondDubboEvent.class)); + } + + @Test + public void testAbstractDubboListener() { + List eventList = new ArrayList<>(); + AbstractDubboListener dubboListener = new AbstractDubboListener() { + @Override + public void onEvent(FirstDubboEvent event) { + eventList.add(event); + } + }; + DubboEventBus.addListener(applicationModel, dubboListener); + + FirstDubboEvent firstDubboEvent = new FirstDubboEvent(applicationModel); + SecondDubboEvent secondDubboEvent = new SecondDubboEvent(applicationModel); + DubboEventBus.publish(firstDubboEvent); + DubboEventBus.publish(secondDubboEvent); + + Assertions.assertEquals(eventList.size(), 1); + Assertions.assertTrue(eventList.contains(firstDubboEvent)); + Assertions.assertFalse(eventList.contains(secondDubboEvent)); + } + + @Test + public void testAbstractDubboLifecycleListener() { + List beforeEventList = new ArrayList<>(); + List afterEventList = new ArrayList<>(); + List errorEventList = new ArrayList<>(); + AbstractDubboLifecycleListener dubboListener = + new AbstractDubboLifecycleListener() { + + @Override + public void onEventBefore(FirstDubboEvent event) { + beforeEventList.add(event); + } + + @Override + public void onEventFinish(FirstDubboEvent event) { + afterEventList.add(event); + } + + @Override + public void onEventError(FirstDubboEvent event) { + errorEventList.add(event); + } + }; + DubboEventBus.addListener(applicationModel, dubboListener); + + FirstDubboEvent firstDubboEvent = new FirstDubboEvent(applicationModel); + SecondDubboEvent secondDubboEvent = new SecondDubboEvent(applicationModel); + + DubboEventBus.post(firstDubboEvent, FirstDubboEvent.class::getName); + DubboEventBus.post(secondDubboEvent, SecondDubboEvent.class::getName); + + Assertions.assertEquals(beforeEventList.size(), 1); + Assertions.assertEquals(beforeEventList.get(0), firstDubboEvent); + Assertions.assertEquals(afterEventList.size(), 1); + Assertions.assertEquals(afterEventList.get(0), firstDubboEvent); + Assertions.assertEquals(errorEventList.size(), 0); + + beforeEventList.clear(); + afterEventList.clear(); + errorEventList.clear(); + + try { + DubboEventBus.post(firstDubboEvent, () -> { + throw new RuntimeException(); + }); + } catch (RuntimeException e) { + } + try { + DubboEventBus.post(secondDubboEvent, () -> { + throw new RuntimeException(); + }); + } catch (RuntimeException e) { + } + + Assertions.assertEquals(beforeEventList.size(), 1); + Assertions.assertEquals(beforeEventList.get(0), firstDubboEvent); + Assertions.assertEquals(afterEventList.size(), 0); + Assertions.assertEquals(errorEventList.size(), 1); + Assertions.assertEquals(errorEventList.get(0), firstDubboEvent); + + beforeEventList.clear(); + afterEventList.clear(); + errorEventList.clear(); + + DubboEventBus.post(firstDubboEvent, FirstDubboEvent.class::getName, result -> false); + DubboEventBus.post(secondDubboEvent, SecondDubboEvent.class::getName, result -> false); + + Assertions.assertEquals(beforeEventList.size(), 1); + Assertions.assertEquals(beforeEventList.get(0), firstDubboEvent); + Assertions.assertEquals(afterEventList.size(), 0); + Assertions.assertEquals(errorEventList.size(), 1); + Assertions.assertEquals(errorEventList.get(0), firstDubboEvent); + } + + @Test + public void testCustomAfterPostEventListener() { + SecondDubboEvent secondDubboEvent = new SecondDubboEvent(applicationModel); + + DubboEventBus.post(secondDubboEvent, SecondDubboEvent.class::getName); + List resultList = secondDubboEvent.getResultList(); + + Assertions.assertEquals(resultList.size(), 1); + Assertions.assertEquals(resultList.get(0), SecondDubboEvent.class.getName()); + } + + public static class FirstDubboEvent extends DubboEvent { + + public FirstDubboEvent(ApplicationModel source) { + super(source); + } + } + + public static class SecondDubboEvent extends DubboEvent implements CustomAfterPost { + + private final List resultList; + + public SecondDubboEvent(ApplicationModel source) { + super(source); + resultList = new ArrayList<>(); + } + + @Override + public void customAfterPost(String postResult) { + resultList.add(postResult); + } + + public List getResultList() { + return resultList; + } + } +} diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index d6610da8b6c..c3f663a5393 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -38,43 +38,7 @@ org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - - org.apache.dubbo - dubbo-metrics-registry - ${project.parent.version} - - - - org.apache.dubbo - dubbo-metrics-metadata - ${project.parent.version} - - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - - - - org.apache.dubbo - dubbo-tracing + dubbo-metrics-annotation ${project.parent.version} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/InitServiceMethodEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/InitServiceMethodEvent.java new file mode 100644 index 00000000000..8055da3fe89 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/InitServiceMethodEvent.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.rpc.Invocation; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class InitServiceMethodEvent extends DubboEvent { + + private final Invocation invocation; + + public InitServiceMethodEvent(ApplicationModel source, Invocation invocation) { + super(source); + this.invocation = invocation; + } + + public Invocation getInvocation() { + return invocation; + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 53bf3c84e95..73a857b9db3 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -22,6 +22,7 @@ import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.constants.RegisterTypeEnum; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -38,9 +39,6 @@ import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.config.utils.ConfigValidationUtils; import org.apache.dubbo.metadata.ServiceNameMapping; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.event.MetricsInitEvent; -import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.registry.client.metadata.MetadataUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; @@ -628,7 +626,6 @@ private void initServiceMethodMetrics(URL url) { String[] methods = Optional.ofNullable(url.getParameter(METHODS_KEY)) .map(i -> i.split(",")) .orElse(new String[] {}); - boolean serviceLevel = MethodMetric.isServiceLevel(application.getApplicationModel()); Arrays.stream(methods).forEach(method -> { RpcInvocation invocation = new RpcInvocation( url.getServiceKey(), @@ -642,8 +639,7 @@ private void initServiceMethodMetrics(URL url) { null, null, null); - MetricsEventBus.publish( - MetricsInitEvent.toMetricsInitEvent(application.getApplicationModel(), invocation, serviceLevel)); + DubboEventBus.publish(new InitServiceMethodEvent(application.getApplicationModel(), invocation)); }); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java index 5d7a0c5b997..5d88e8db4d3 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.config.ReferenceCache; +import org.apache.dubbo.common.config.configcenter.ConfigCenterChangeEvent; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; @@ -31,6 +32,7 @@ import org.apache.dubbo.common.deploy.DeployListener; import org.apache.dubbo.common.deploy.DeployState; import org.apache.dubbo.common.deploy.ModuleDeployer; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.lang.ShutdownHookCallbacks; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -46,20 +48,14 @@ import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.RegistryConfig; -import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.config.context.ConfigManager; +import org.apache.dubbo.config.deploy.event.ApplicationLoadedEvent; +import org.apache.dubbo.config.deploy.event.ApplicationStartedEvent; import org.apache.dubbo.config.utils.CompositeReferenceCache; import org.apache.dubbo.config.utils.ConfigValidationUtils; import org.apache.dubbo.metadata.report.MetadataReportFactory; import org.apache.dubbo.metadata.report.MetadataReportInstance; -import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; -import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.report.DefaultMetricsReporterFactory; -import org.apache.dubbo.metrics.report.MetricsReporter; -import org.apache.dubbo.metrics.report.MetricsReporterFactory; import org.apache.dubbo.metrics.service.MetricsServiceExporter; -import org.apache.dubbo.metrics.utils.MetricsSupportUtil; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils; @@ -70,8 +66,6 @@ import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; -import org.apache.dubbo.tracing.DubboObservationRegistry; -import org.apache.dubbo.tracing.utils.ObservationSupportUtil; import java.io.IOException; import java.util.ArrayList; @@ -95,14 +89,11 @@ import static org.apache.dubbo.common.config.ConfigurationUtils.parseProperties; import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_EXECUTE_DESTROY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_INIT_CONFIG_CENTER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_START_MODEL; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_REFRESH_INSTANCE_ERROR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_REGISTER_INSTANCE_ERROR; -import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_DEFAULT; -import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; import static org.apache.dubbo.common.utils.StringUtils.isEmpty; import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty; import static org.apache.dubbo.config.Constants.DEFAULT_APP_NAME; @@ -136,8 +127,6 @@ public class DefaultApplicationDeployer extends AbstractDeployer startFuture; private final DubboShutdownHook dubboShutdownHook; - private volatile MetricsServiceExporter metricsServiceExporter; - private final Object stateLock = new Object(); private final Object startLock = new Object(); private final Object destroyLock = new Object(); @@ -227,12 +216,7 @@ public void initialize() { initModuleDeployers(); - initMetricsReporter(); - - initMetricsService(); - - // @since 3.2.3 - initObservationRegistry(); + DubboEventBus.publish(new ApplicationLoadedEvent(applicationModel)); // @since 2.7.8 startMetadataCenter(); @@ -375,83 +359,6 @@ private void useRegistryAsConfigCenterIfNecessary() { } } - private void initMetricsService() { - this.metricsServiceExporter = - getExtensionLoader(MetricsServiceExporter.class).getDefaultExtension(); - metricsServiceExporter.init(); - } - - private void initMetricsReporter() { - if (!MetricsSupportUtil.isSupportMetrics()) { - return; - } - DefaultMetricsCollector collector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); - Optional configOptional = configManager.getMetrics(); - // If no specific metrics type is configured and there is no Prometheus dependency in the dependencies. - MetricsConfig metricsConfig = configOptional.orElse(new MetricsConfig(applicationModel)); - if (StringUtils.isBlank(metricsConfig.getProtocol())) { - metricsConfig.setProtocol( - MetricsSupportUtil.isSupportPrometheus() ? PROTOCOL_PROMETHEUS : PROTOCOL_DEFAULT); - } - collector.setCollectEnabled(true); - collector.collectApplication(); - collector.setThreadpoolCollectEnabled( - Optional.ofNullable(metricsConfig.getEnableThreadpool()).orElse(true)); - collector.setMetricsInitEnabled( - Optional.ofNullable(metricsConfig.getEnableMetricsInit()).orElse(true)); - MetricsReporterFactory metricsReporterFactory = - getExtensionLoader(MetricsReporterFactory.class).getAdaptiveExtension(); - MetricsReporter metricsReporter = null; - try { - metricsReporter = metricsReporterFactory.createMetricsReporter(metricsConfig.toUrl()); - } catch (IllegalStateException e) { - if (e.getMessage().startsWith("No such extension org.apache.dubbo.metrics.report.MetricsReporterFactory")) { - logger.warn(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", e.getMessage()); - return; - } else { - throw e; - } - } - metricsReporter.init(); - applicationModel.getBeanFactory().registerBean(metricsReporter); - // If the protocol is not the default protocol, the default protocol is also initialized. - if (!PROTOCOL_DEFAULT.equals(metricsConfig.getProtocol())) { - DefaultMetricsReporterFactory defaultMetricsReporterFactory = - new DefaultMetricsReporterFactory(applicationModel); - MetricsReporter defaultMetricsReporter = - defaultMetricsReporterFactory.createMetricsReporter(metricsConfig.toUrl()); - defaultMetricsReporter.init(); - applicationModel.getBeanFactory().registerBean(defaultMetricsReporter); - } - } - - /** - * init ObservationRegistry(Micrometer) - */ - private void initObservationRegistry() { - if (!ObservationSupportUtil.isSupportObservation()) { - if (logger.isDebugEnabled()) { - logger.debug( - "Not found micrometer-observation or plz check the version of micrometer-observation version if already introduced, need > 1.10.0"); - } - return; - } - if (!ObservationSupportUtil.isSupportTracing()) { - if (logger.isDebugEnabled()) { - logger.debug("Not found micrometer-tracing dependency, skip init ObservationRegistry."); - } - return; - } - Optional configOptional = configManager.getTracing(); - if (!configOptional.isPresent() || !configOptional.get().getEnabled()) { - return; - } - - DubboObservationRegistry dubboObservationRegistry = - new DubboObservationRegistry(applicationModel, configOptional.get()); - dubboObservationRegistry.initObservationRegistry(); - } - private boolean isUsedRegistryAsConfigCenter(RegistryConfig registryConfig) { return isUsedRegistryAsCenter( registryConfig, registryConfig::getUseAsConfigCenter, "config", DynamicConfigurationFactory.class); @@ -830,6 +737,8 @@ public void prepareInternalModule() { } private void exportMetricsService() { + MetricsServiceExporter metricsServiceExporter = + applicationModel.getBeanFactory().getBean(MetricsServiceExporter.class); boolean exportMetrics = applicationModel .getApplicationConfigManager() .getMetrics() @@ -850,6 +759,8 @@ private void exportMetricsService() { } private void unexportMetricsService() { + MetricsServiceExporter metricsServiceExporter = + applicationModel.getBeanFactory().getBean(MetricsServiceExporter.class); if (metricsServiceExporter != null) { try { metricsServiceExporter.unexport(); @@ -937,7 +848,7 @@ private DynamicConfiguration prepareEnvironment(ConfigCenterConfig configCenter) environment.updateAppExternalConfigMap(appConfigMap); // Add metrics - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + DubboEventBus.publish(new ConfigCenterChangeEvent( applicationModel, configCenter.getConfigFile(), configCenter.getGroup(), @@ -945,7 +856,7 @@ private DynamicConfiguration prepareEnvironment(ConfigCenterConfig configCenter) ConfigChangeType.ADDED.name(), configMap.size())); if (isNotEmpty(appGroup)) { - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + DubboEventBus.publish(new ConfigCenterChangeEvent( applicationModel, appConfigFile, appGroup, @@ -1332,7 +1243,7 @@ private void onStarted() { return; } setStarted(); - startMetricsCollector(); + DubboEventBus.publish(new ApplicationStartedEvent(applicationModel)); if (logger.isInfoEnabled()) { logger.info(getIdentifier() + " is ready."); } @@ -1362,13 +1273,6 @@ private void onCompletion() { } } - private void startMetricsCollector() { - DefaultMetricsCollector collector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); - if (Objects.nonNull(collector) && collector.isThreadpoolCollectEnabled()) { - collector.registryDefaultSample(); - } - } - private void completeStartFuture(boolean success) { if (startFuture != null) { startFuture.complete(success); diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationLoadedEvent.java similarity index 70% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java rename to dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationLoadedEvent.java index 2f1381a7265..3c1468f71ae 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationLoadedEvent.java @@ -14,17 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.event; +package org.apache.dubbo.config.deploy.event; -import org.apache.dubbo.metrics.listener.MetricsListener; +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; -public interface MetricsEventMulticaster { +public class ApplicationLoadedEvent extends DubboEvent { - void addListener(MetricsListener listener); - - void publishEvent(MetricsEvent event); - - void publishFinishEvent(TimeCounterEvent event); - - void publishErrorEvent(TimeCounterEvent event); + public ApplicationLoadedEvent(ApplicationModel source) { + super(source); + } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationStartedEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationStartedEvent.java new file mode 100644 index 00000000000..298d5ef2a8f --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationStartedEvent.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.deploy.event; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class ApplicationStartedEvent extends DubboEvent { + + public ApplicationStartedEvent(ApplicationModel source) { + super(source); + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter deleted file mode 100644 index 7edea936d57..00000000000 --- a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter +++ /dev/null @@ -1 +0,0 @@ -default=org.apache.dubbo.config.deploy.DefaultMetricsServiceExporter diff --git a/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.metrics.service.MetricsServiceExporter b/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.metrics.service.MetricsServiceExporter index 7edea936d57..6d6fd48ad3f 100644 --- a/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.metrics.service.MetricsServiceExporter +++ b/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.metrics.service.MetricsServiceExporter @@ -1 +1 @@ -default=org.apache.dubbo.config.deploy.DefaultMetricsServiceExporter +default=org.apache.dubbo.metrics.DefaultMetricsServiceExporter diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml index 5a709b40e8f..6c1e0a0e370 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml @@ -39,21 +39,6 @@ dubbo-common ${project.parent.version} - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - com.ctrip.framework.apollo apollo-client @@ -64,10 +49,5 @@ ${apollo_mock_server_version} test - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloConstants.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloConstants.java new file mode 100644 index 00000000000..58f7fa9b54e --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloConstants.java @@ -0,0 +1,22 @@ +/* + * 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.configcenter.support.apollo; + +public interface ApolloConstants { + + String APOLLO_PROTOCOL = "apollo"; +} diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java index e355bb22da5..517286cbc7d 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java @@ -17,16 +17,16 @@ package org.apache.dubbo.configcenter.support.apollo; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.ConfigCenterChangeEvent; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.event.DubboEventBus; 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.common.utils.SystemPropertyConfigUtils; -import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; -import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Arrays; @@ -58,7 +58,6 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CLOSE_CONNECT_APOLLO; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NOT_EFFECT_EMPTY_RULE_APOLLO; -import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; /** * Apollo implementation, https://github.com/ctripcorp/apollo @@ -269,13 +268,12 @@ public void onChange(com.ctrip.framework.apollo.model.ConfigChangeEvent changeEv new ConfigChangedEvent(key, change.getNamespace(), change.getNewValue(), getChangeType(change)); listeners.forEach(listener -> listener.process(event)); - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + DubboEventBus.publish(new ConfigCenterChangeEvent( applicationModel, event.getKey(), event.getGroup(), - ConfigCenterEvent.APOLLO_PROTOCOL, - ConfigChangeType.ADDED.name(), - SELF_INCREMENT_SIZE)); + ApolloConstants.APOLLO_PROTOCOL, + ConfigChangeType.ADDED.name())); } } diff --git a/dubbo-configcenter/dubbo-configcenter-file/pom.xml b/dubbo-configcenter/dubbo-configcenter-file/pom.xml index c6c403fcfac..e7b6626bdbd 100644 --- a/dubbo-configcenter/dubbo-configcenter-file/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-file/pom.xml @@ -38,25 +38,5 @@ dubbo-common ${project.parent.version} - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml index 991a961c5ff..def322c935a 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml @@ -38,26 +38,6 @@ com.alibaba.nacos nacos-client - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - org.apache.logging.log4j log4j-slf4j-impl diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosConstants.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosConstants.java new file mode 100644 index 00000000000..0af21280242 --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosConstants.java @@ -0,0 +1,22 @@ +/* + * 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.configcenter.support.nacos; + +public interface NacosConstants { + + String NACOS_PROTOCOL = "nacos"; +} diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java index 74c530e2b07..a6e9a7e4a1b 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java @@ -17,19 +17,19 @@ package org.apache.dubbo.configcenter.support.nacos; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.ConfigCenterChangeEvent; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.LoggerCodeConstants; +import org.apache.dubbo.common.event.DubboEventBus; 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.MD5Utils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; -import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; @@ -55,7 +55,6 @@ import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of; import static org.apache.dubbo.common.utils.StringUtils.HYPHEN_CHAR; -import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; /** * The nacos implementation of {@link DynamicConfiguration} @@ -362,13 +361,12 @@ public void innerReceive(String dataId, String group, String configInfo) { } listeners.forEach(listener -> listener.process(event)); - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + DubboEventBus.publish(new ConfigCenterChangeEvent( applicationModel, event.getKey(), event.getGroup(), - ConfigCenterEvent.NACOS_PROTOCOL, - ConfigChangeType.ADDED.name(), - SELF_INCREMENT_SIZE)); + NacosConstants.NACOS_PROTOCOL, + ConfigChangeType.ADDED.name())); } void addListener(ConfigurationListener configurationListener) { diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml b/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml index c1deb8c3e5b..1596c474eb4 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml @@ -61,26 +61,6 @@ org.apache.zookeeper zookeeper - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperConstants.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperConstants.java new file mode 100644 index 00000000000..6cfffd767cc --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperConstants.java @@ -0,0 +1,22 @@ +/* + * 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.configcenter.support.zookeeper; + +public interface ZookeeperConstants { + + String ZK_PROTOCOL = "zookeeper"; +} diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java index 508b9430a87..3bb8478588f 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java @@ -16,12 +16,12 @@ */ package org.apache.dubbo.configcenter.support.zookeeper; +import org.apache.dubbo.common.config.configcenter.ConfigCenterChangeEvent; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; -import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.remoting.zookeeper.curator5.DataListener; import org.apache.dubbo.remoting.zookeeper.curator5.EventType; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -29,8 +29,6 @@ import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; -import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; - /** * one path has multi configurationListeners */ @@ -80,12 +78,11 @@ public void dataChanged(String path, Object value, EventType eventType) { listeners.forEach(listener -> listener.process(configChangeEvent)); } - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + DubboEventBus.publish(new ConfigCenterChangeEvent( applicationModel, configChangeEvent.getKey(), configChangeEvent.getGroup(), - ConfigCenterEvent.ZK_PROTOCOL, - ConfigChangeType.ADDED.name(), - SELF_INCREMENT_SIZE)); + ZookeeperConstants.ZK_PROTOCOL, + ConfigChangeType.ADDED.name())); } } diff --git a/dubbo-distribution/dubbo-all-shaded/pom.xml b/dubbo-distribution/dubbo-all-shaded/pom.xml index f9207588e36..fb107b165a1 100644 --- a/dubbo-distribution/dubbo-all-shaded/pom.xml +++ b/dubbo-distribution/dubbo-all-shaded/pom.xml @@ -172,6 +172,13 @@ + + org.apache.dubbo + dubbo-metrics-annotation + ${project.version} + compile + true + org.apache.dubbo dubbo-metrics-api @@ -186,6 +193,13 @@ compile true + + org.apache.dubbo + dubbo-metrics-starter + ${project.version} + compile + true + org.apache.dubbo dubbo-metrics-registry @@ -468,8 +482,10 @@ org.apache.dubbo:dubbo-metadata-report-nacos org.apache.dubbo:dubbo-metadata-report-redis org.apache.dubbo:dubbo-metadata-report-zookeeper + org.apache.dubbo:dubbo-metrics-annotation org.apache.dubbo:dubbo-metrics-api org.apache.dubbo:dubbo-metrics-default + org.apache.dubbo:dubbo-metrics-starter org.apache.dubbo:dubbo-metrics-registry org.apache.dubbo:dubbo-metrics-metadata org.apache.dubbo:dubbo-metrics-config-center diff --git a/dubbo-distribution/dubbo-all/pom.xml b/dubbo-distribution/dubbo-all/pom.xml index dceb0307b12..34e5873f0cc 100644 --- a/dubbo-distribution/dubbo-all/pom.xml +++ b/dubbo-distribution/dubbo-all/pom.xml @@ -160,7 +160,7 @@ org.apache.dubbo - dubbo-metrics-event + dubbo-metrics-annotation ${project.version} compile true @@ -214,6 +214,13 @@ compile true + + org.apache.dubbo + dubbo-metrics-starter + ${project.version} + compile + true + @@ -497,7 +504,7 @@ org.apache.dubbo:dubbo-metadata-report-nacos org.apache.dubbo:dubbo-metadata-report-redis org.apache.dubbo:dubbo-metadata-report-zookeeper - org.apache.dubbo:dubbo-metrics-event + org.apache.dubbo:dubbo-metrics-annotation org.apache.dubbo:dubbo-metrics-api org.apache.dubbo:dubbo-metrics-default org.apache.dubbo:dubbo-metrics-registry @@ -505,6 +512,7 @@ org.apache.dubbo:dubbo-metrics-config-center org.apache.dubbo:dubbo-metrics-netty org.apache.dubbo:dubbo-metrics-prometheus + org.apache.dubbo:dubbo-metrics-starter org.apache.dubbo:dubbo-tracing org.apache.dubbo:dubbo-qos org.apache.dubbo:dubbo-qos-api diff --git a/dubbo-distribution/dubbo-bom/pom.xml b/dubbo-distribution/dubbo-bom/pom.xml index 80335d6743b..70d11795b33 100644 --- a/dubbo-distribution/dubbo-bom/pom.xml +++ b/dubbo-distribution/dubbo-bom/pom.xml @@ -237,7 +237,7 @@ org.apache.dubbo - dubbo-metrics-event + dubbo-metrics-annotation ${project.version} @@ -270,6 +270,11 @@ dubbo-metrics-netty ${project.version} + + org.apache.dubbo + dubbo-metrics-starter + ${project.version} + diff --git a/dubbo-distribution/dubbo-core-spi/pom.xml b/dubbo-distribution/dubbo-core-spi/pom.xml index c9661590f2d..63c068cc0a6 100644 --- a/dubbo-distribution/dubbo-core-spi/pom.xml +++ b/dubbo-distribution/dubbo-core-spi/pom.xml @@ -125,8 +125,10 @@ org.apache.dubbo:dubbo-common org.apache.dubbo:dubbo-config-api org.apache.dubbo:dubbo-metadata-api + org.apache.dubbo:dubbo-metrics-annotation org.apache.dubbo:dubbo-metrics-api org.apache.dubbo:dubbo-metrics-default + org.apache.dubbo:dubbo-metrics-starter org.apache.dubbo:dubbo-tracing org.apache.dubbo:dubbo-registry-api org.apache.dubbo:dubbo-remoting-api diff --git a/dubbo-metadata/dubbo-metadata-api/pom.xml b/dubbo-metadata/dubbo-metadata-api/pom.xml index 8fc6af86eae..c9352c930bb 100644 --- a/dubbo-metadata/dubbo-metadata-api/pom.xml +++ b/dubbo-metadata/dubbo-metadata-api/pom.xml @@ -44,25 +44,6 @@ ${project.parent.version} - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-metadata - ${project.parent.version} - compile - - org.apache.dubbo dubbo-native diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataEvent.java new file mode 100644 index 00000000000..6ef9b4c608f --- /dev/null +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataEvent.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.event; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public abstract class MetaDataEvent extends DubboEvent { + + private final TimePair timePair; + + public MetaDataEvent(ApplicationModel source) { + super(source); + this.timePair = TimePair.start(); + } + + public TimePair getTimePair() { + return timePair; + } +} diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataPushEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataPushEvent.java new file mode 100644 index 00000000000..12a97d817ec --- /dev/null +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataPushEvent.java @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class MetaDataPushEvent extends MetaDataEvent { + + public MetaDataPushEvent(ApplicationModel source) { + super(source); + } +} diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataServiceSubscribeEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataServiceSubscribeEvent.java new file mode 100644 index 00000000000..0e6db8092f1 --- /dev/null +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataServiceSubscribeEvent.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class MetaDataServiceSubscribeEvent extends MetaDataEvent { + + private final String serviceKey; + + public MetaDataServiceSubscribeEvent(ApplicationModel source, String serviceKey) { + super(source); + this.serviceKey = serviceKey; + } + + public String getServiceKey() { + return serviceKey; + } +} diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataSubscribeEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataSubscribeEvent.java new file mode 100644 index 00000000000..c3746c9221d --- /dev/null +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataSubscribeEvent.java @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class MetaDataSubscribeEvent extends MetaDataEvent { + + public MetaDataSubscribeEvent(ApplicationModel source) { + super(source); + } +} diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java index 6d2dcb7a5ba..05639c9197e 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java @@ -17,6 +17,7 @@ package org.apache.dubbo.metadata.report.support; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; @@ -26,13 +27,12 @@ import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import org.apache.dubbo.metadata.definition.model.ServiceDefinition; +import org.apache.dubbo.metadata.event.MetaDataServiceSubscribeEvent; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.metadata.event.MetadataEvent; import org.apache.dubbo.rpc.model.ApplicationModel; import java.io.File; @@ -298,9 +298,9 @@ public void storeProviderMetadata( private void storeProviderMetadataTask( MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { - MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent( - applicationModel, providerMetadataIdentifier.getUniqueServiceName()); - MetricsEventBus.post( + MetaDataServiceSubscribeEvent metadataEvent = + new MetaDataServiceSubscribeEvent(applicationModel, providerMetadataIdentifier.getUniqueServiceName()); + DubboEventBus.post( metadataEvent, () -> { boolean result = true; @@ -329,7 +329,7 @@ private void storeProviderMetadataTask( } return result; }, - aBoolean -> aBoolean); + result -> result); } @Override diff --git a/dubbo-metrics/dubbo-metrics-event/pom.xml b/dubbo-metrics/dubbo-metrics-annotation/pom.xml similarity index 92% rename from dubbo-metrics/dubbo-metrics-event/pom.xml rename to dubbo-metrics/dubbo-metrics-annotation/pom.xml index abdaf820d5f..1fe6d1d1d73 100644 --- a/dubbo-metrics/dubbo-metrics-event/pom.xml +++ b/dubbo-metrics/dubbo-metrics-annotation/pom.xml @@ -23,14 +23,13 @@ ${revision} ../pom.xml - dubbo-metrics-event + dubbo-metrics-annotation jar ${project.artifactId} - The metrics event-related api module of dubbo project + The metrics module of dubbo project false - org.apache.dubbo @@ -38,5 +37,4 @@ ${project.parent.version} - diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java b/dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java rename to dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/Constants.java b/dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/Constants.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/Constants.java rename to dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/Constants.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/Monitor.java b/dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/Monitor.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/Monitor.java rename to dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/Monitor.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java b/dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java rename to dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java b/dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/MonitorService.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java rename to dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/MonitorService.java diff --git a/dubbo-metrics/dubbo-metrics-api/pom.xml b/dubbo-metrics/dubbo-metrics-api/pom.xml index da9570a5d07..4d9a6486ff3 100644 --- a/dubbo-metrics/dubbo-metrics-api/pom.xml +++ b/dubbo-metrics/dubbo-metrics-api/pom.xml @@ -38,7 +38,7 @@ org.apache.dubbo - dubbo-metrics-event + dubbo-metrics-annotation ${project.parent.version} diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java index 63c996d0c2a..02489cc3356 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metrics.collector; -import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.key.MetricsKey; /** @@ -25,7 +24,7 @@ * * @Params metrics type */ -public interface ApplicationMetricsCollector extends MetricsCollector { +public interface ApplicationMetricsCollector extends MetricsCollector { void increment(MetricsKey metricsKey); diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java index becf811e9f8..8b7c8bf5aeb 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java @@ -17,9 +17,6 @@ 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; @@ -31,20 +28,15 @@ import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; -public abstract class CombMetricsCollector extends AbstractMetricsListener - implements ApplicationMetricsCollector, ServiceMetricsCollector, MethodMetricsCollector { +public abstract class CombMetricsCollector + implements ApplicationMetricsCollector, ServiceMetricsCollector, MethodMetricsCollector { 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); @@ -97,25 +89,6 @@ protected List 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; } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java index 03f1becd04c..74d4e266bf5 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java @@ -16,7 +16,6 @@ */ 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; @@ -24,7 +23,7 @@ /** * Method-level metrics collection for rpc invocation scenarios */ -public interface MethodMetricsCollector extends MetricsCollector { +public interface MethodMetricsCollector extends MetricsCollector { void increment(MethodMetric methodMetric, MetricsKeyWrapper wrapper, int size); diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java index 0d61468f045..3bc2bc458d2 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java @@ -17,9 +17,6 @@ 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; @@ -29,7 +26,7 @@ * An interface of collector to collect framework internal metrics. */ @SPI -public interface MetricsCollector extends MetricsLifeListener { +public interface MetricsCollector { default boolean isCollectEnabled() { return false; @@ -49,7 +46,4 @@ default boolean isCollectEnabled() { * @return true if samples have been changed */ boolean calSamplesChanged(); - - default void initMetrics(MetricsEvent event) {} - ; } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java index 699236f3fb0..06020d72766 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java @@ -16,7 +16,6 @@ */ 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; @@ -24,7 +23,7 @@ * Service-level collector. * registration center, configuration center and other scenarios */ -public interface ServiceMetricsCollector extends MetricsCollector { +public interface ServiceMetricsCollector extends MetricsCollector { void increment(String serviceKey, MetricsKeyWrapper wrapper, int size); diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java similarity index 77% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java index 25a040d8588..51a89e1f7f1 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.metrics.event; -import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.event.DubboEvent; import org.apache.dubbo.metrics.exception.MetricsNeverHappenException; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -28,7 +28,7 @@ /** * BaseMetricsEvent. */ -public abstract class MetricsEvent { +public abstract class MetricsEvent extends DubboEvent { /** * Metric object. (eg. MethodMetric) @@ -38,19 +38,15 @@ public abstract class MetricsEvent { private boolean available = true; private final TypeWrapper typeWrapper; private final String appName; - private final MetricsEventMulticaster metricsEventMulticaster; private final Map attachments = new IdentityHashMap<>(8); public MetricsEvent(ApplicationModel source, TypeWrapper typeWrapper) { - this(source, null, null, typeWrapper); + this(source, null, typeWrapper); } - public MetricsEvent( - ApplicationModel source, - String appName, - MetricsEventMulticaster metricsEventMulticaster, - TypeWrapper typeWrapper) { + public MetricsEvent(ApplicationModel source, String appName, TypeWrapper typeWrapper) { + super(source); this.typeWrapper = typeWrapper; if (source == null) { this.source = ApplicationModel.defaultModel(); @@ -59,21 +55,6 @@ public MetricsEvent( } else { this.source = source; } - if (metricsEventMulticaster == null) { - if (this.source.isDestroyed()) { - this.metricsEventMulticaster = null; - } else { - ScopeBeanFactory beanFactory = this.source.getBeanFactory(); - if (beanFactory.isDestroyed()) { - this.metricsEventMulticaster = null; - } else { - MetricsEventMulticaster dispatcher = beanFactory.getBean(MetricsEventMulticaster.class); - this.metricsEventMulticaster = dispatcher; - } - } - } else { - this.metricsEventMulticaster = metricsEventMulticaster; - } if (appName == null) { this.appName = this.source.tryGetApplicationName(); } else { @@ -115,10 +96,6 @@ public ApplicationModel getSource() { return source; } - public MetricsEventMulticaster getMetricsEventMulticaster() { - return metricsEventMulticaster; - } - public String appName() { return appName; } diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java similarity index 77% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java index 7cfb2c607f8..a29f6e904e9 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.metrics.event; -import org.apache.dubbo.metrics.model.TimePair; +import org.apache.dubbo.common.utils.TimePair; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -27,18 +27,14 @@ public abstract class TimeCounterEvent extends MetricsEvent { private final TimePair timePair; - public TimeCounterEvent(ApplicationModel source, TypeWrapper typeWrapper) { + public TimeCounterEvent(ApplicationModel source, TypeWrapper typeWrapper, TimePair timePair) { super(source, typeWrapper); - this.timePair = TimePair.start(); + this.timePair = timePair; } - public TimeCounterEvent( - ApplicationModel source, - String appName, - MetricsEventMulticaster metricsDispatcher, - TypeWrapper typeWrapper) { - super(source, appName, metricsDispatcher, typeWrapper); - this.timePair = TimePair.start(); + public TimeCounterEvent(ApplicationModel source, String appName, TypeWrapper typeWrapper, TimePair timePair) { + super(source, appName, typeWrapper); + this.timePair = timePair; } public TimePair getTimePair() { diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEventMulticaster.java similarity index 58% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEventMulticaster.java index bfc8ae2b91e..40a2bc92213 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEventMulticaster.java @@ -17,8 +17,7 @@ package org.apache.dubbo.metrics.event; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metrics.listener.MetricsLifeListener; -import org.apache.dubbo.metrics.listener.MetricsListener; +import org.apache.dubbo.metrics.listener.AbstractMetricsKeyListener; import java.util.ArrayList; import java.util.Collections; @@ -28,26 +27,23 @@ /** * A simple event publisher that defines lifecycle events and supports rt events */ -public class SimpleMetricsEventMulticaster implements MetricsEventMulticaster { - private final List> listeners = Collections.synchronizedList(new ArrayList<>()); +public class TimeCounterEventMulticaster { + private final List listeners = Collections.synchronizedList(new ArrayList<>()); - @Override - public void addListener(MetricsListener listener) { + public void addListener(AbstractMetricsKeyListener listener) { listeners.add(listener); } - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) - public void publishEvent(MetricsEvent event) { + public void publishEvent(TimeCounterEvent event) { if (validateIfApplicationConfigExist(event)) return; - for (MetricsListener listener : listeners) { - if (listener.isSupport(event)) { + for (AbstractMetricsKeyListener listener : listeners) { + if (listener.support(event)) { listener.onEvent(event); } } } - private boolean validateIfApplicationConfigExist(MetricsEvent event) { + private boolean validateIfApplicationConfigExist(TimeCounterEvent event) { if (event.getSource() != null) { // Check if exist application config return StringUtils.isEmpty(event.appName()); @@ -55,27 +51,22 @@ private boolean validateIfApplicationConfigExist(MetricsEvent event) { return false; } - @Override - @SuppressWarnings({"unchecked"}) public void publishFinishEvent(TimeCounterEvent event) { publishTimeEvent(event, metricsLifeListener -> metricsLifeListener.onEventFinish(event)); } - @Override - @SuppressWarnings({"unchecked"}) public void publishErrorEvent(TimeCounterEvent event) { publishTimeEvent(event, metricsLifeListener -> metricsLifeListener.onEventError(event)); } - @SuppressWarnings({"rawtypes"}) - private void publishTimeEvent(MetricsEvent event, Consumer consumer) { - if (validateIfApplicationConfigExist(event)) return; - if (event instanceof TimeCounterEvent) { - ((TimeCounterEvent) event).getTimePair().end(); + private void publishTimeEvent(TimeCounterEvent event, Consumer consumer) { + if (validateIfApplicationConfigExist(event)) { + return; } - for (MetricsListener listener : listeners) { - if (listener instanceof MetricsLifeListener && listener.isSupport(event)) { - consumer.accept(((MetricsLifeListener) listener)); + event.getTimePair().end(); + for (AbstractMetricsKeyListener listener : listeners) { + if (listener.support(event)) { + consumer.accept(listener); } } } diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java index 516ce04ae4c..34c90cc2ff8 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java @@ -16,20 +16,17 @@ */ package org.apache.dubbo.metrics.listener; -import org.apache.dubbo.metrics.event.MetricsEvent; -import org.apache.dubbo.metrics.event.MetricsEventBus; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.key.MetricsKey; import java.util.function.Consumer; /** - * According to the event template of {@link MetricsEventBus}, + * According to the event template of {@link DubboEventBus}, * build a consistent static method for general and custom monitoring consume methods - * */ -public abstract class AbstractMetricsKeyListener extends AbstractMetricsListener - implements MetricsLifeListener { +public abstract class AbstractMetricsKeyListener { private final MetricsKey metricsKey; @@ -40,14 +37,16 @@ public AbstractMetricsKeyListener(MetricsKey metricsKey) { /** * The MetricsKey type determines whether events are supported */ - @Override - public boolean isSupport(MetricsEvent event) { - return super.isSupport(event) && event.isAssignableFrom(metricsKey); + public boolean support(TimeCounterEvent event) { + return event.isAssignableFrom(metricsKey); } - @Override public void onEvent(TimeCounterEvent event) {} + public void onEventFinish(TimeCounterEvent event) {} + + public void onEventError(TimeCounterEvent event) {} + public static AbstractMetricsKeyListener onEvent(MetricsKey metricsKey, Consumer postFunc) { return new AbstractMetricsKeyListener(metricsKey) { diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java index 018889ec2a8..2e9f4d8bbae 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.metrics.listener; -import org.apache.dubbo.metrics.collector.CombMetricsCollector; +import org.apache.dubbo.metrics.collector.ApplicationMetricsCollector; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; @@ -24,11 +24,7 @@ * App-level listener type, in most cases, can use the static method * to produce an anonymous listener for general monitoring */ -public class MetricsApplicationListener extends AbstractMetricsKeyListener { - - public MetricsApplicationListener(MetricsKey metricsKey) { - super(metricsKey); - } +public class MetricsApplicationListener { /** * Perform auto-increment on the monitored key, @@ -38,7 +34,7 @@ public MetricsApplicationListener(MetricsKey metricsKey) { * @param collector Corresponding collector */ public static AbstractMetricsKeyListener onPostEventBuild( - MetricsKey metricsKey, CombMetricsCollector collector) { + MetricsKey metricsKey, ApplicationMetricsCollector collector) { return AbstractMetricsKeyListener.onEvent(metricsKey, event -> collector.increment(metricsKey)); } @@ -50,7 +46,7 @@ public static AbstractMetricsKeyListener onPostEventBuild( * @param collector Corresponding collector */ public static AbstractMetricsKeyListener onFinishEventBuild( - MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, ApplicationMetricsCollector collector) { return AbstractMetricsKeyListener.onFinish(metricsKey, event -> { collector.increment(metricsKey); collector.addApplicationRt(placeType.getType(), event.getTimePair().calc()); @@ -61,7 +57,7 @@ public static AbstractMetricsKeyListener onFinishEventBuild( * Similar to onFinishEventBuild */ public static AbstractMetricsKeyListener onErrorEventBuild( - MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, ApplicationMetricsCollector collector) { return AbstractMetricsKeyListener.onError(metricsKey, event -> { collector.increment(metricsKey); collector.addApplicationRt(placeType.getType(), event.getTimePair().calc()); diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java index 49fa8c783f1..ec1215c0d83 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java @@ -17,7 +17,6 @@ package org.apache.dubbo.metrics.listener; import org.apache.dubbo.metrics.collector.ServiceMetricsCollector; -import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; @@ -27,26 +26,22 @@ * to produce an anonymous listener for general monitoring. * Similar to App-level */ -public class MetricsServiceListener extends AbstractMetricsKeyListener { - - public MetricsServiceListener(MetricsKey metricsKey) { - super(metricsKey); - } +public class MetricsServiceListener { public static AbstractMetricsKeyListener onPostEventBuild( - MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { return AbstractMetricsKeyListener.onEvent( metricsKey, event -> MetricsSupport.increment(metricsKey, placeType, collector, event)); } public static AbstractMetricsKeyListener onFinishEventBuild( - MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { return AbstractMetricsKeyListener.onFinish( metricsKey, event -> MetricsSupport.incrAndAddRt(metricsKey, placeType, collector, event)); } public static AbstractMetricsKeyListener onErrorEventBuild( - MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { return AbstractMetricsKeyListener.onError( metricsKey, event -> MetricsSupport.incrAndAddRt(metricsKey, placeType, collector, event)); } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java index dc7b9e5aa28..219198d1924 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java @@ -213,10 +213,7 @@ public static String getVersion(Invocation invocation) { * Incr service num */ public static void increment( - MetricsKey metricsKey, - MetricsPlaceValue placeType, - ServiceMetricsCollector collector, - MetricsEvent event) { + MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector, MetricsEvent event) { collector.increment( event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), new MetricsKeyWrapper(metricsKey, placeType), @@ -229,7 +226,7 @@ public static void increment( public static void incrAndAddRt( MetricsKey metricsKey, MetricsPlaceValue placeType, - ServiceMetricsCollector collector, + ServiceMetricsCollector collector, TimeCounterEvent event) { collector.increment( event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), @@ -251,10 +248,7 @@ public static void incrAndAddRt( * Incr method num */ public static void increment( - MetricsKey metricsKey, - MetricsPlaceValue placeType, - MethodMetricsCollector collector, - MetricsEvent event) { + MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector collector, MetricsEvent event) { collector.increment( event.getAttachmentValue(METHOD_METRICS), new MetricsKeyWrapper(metricsKey, placeType), @@ -262,10 +256,7 @@ public static void increment( } public static void init( - MetricsKey metricsKey, - MetricsPlaceValue placeType, - MethodMetricsCollector collector, - MetricsEvent event) { + MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector collector, MetricsEvent event) { collector.init(event.getAttachmentValue(INVOCATION), new MetricsKeyWrapper(metricsKey, placeType)); } @@ -273,10 +264,7 @@ public static void init( * Dec method num */ public static void dec( - MetricsKey metricsKey, - MetricsPlaceValue placeType, - MethodMetricsCollector collector, - MetricsEvent event) { + MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector collector, MetricsEvent event) { collector.increment( event.getAttachmentValue(METHOD_METRICS), new MetricsKeyWrapper(metricsKey, placeType), @@ -289,7 +277,7 @@ public static void dec( public static void incrAndAddRt( MetricsKey metricsKey, MetricsPlaceValue placeType, - MethodMetricsCollector collector, + MethodMetricsCollector collector, TimeCounterEvent event) { collector.increment( event.getAttachmentValue(METHOD_METRICS), diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java index 5ea95fdff7b..c3e0b07c831 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java @@ -17,12 +17,14 @@ package org.apache.dubbo.metrics; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.utils.Assert; 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.metrics.utils.MetricsSupportUtil; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -60,4 +62,10 @@ void testFillZero() { Assertions.assertEquals( 4, data.values().stream().mapToLong(map -> map.values().size()).sum()); } + + @Test + void isSupportPrometheus() { + boolean supportPrometheus = MetricsSupportUtil.isSupportPrometheus(); + Assert.assertTrue(!supportPrometheus, "MetricsSupportUtil.isSupportPrometheus() should return false"); + } } diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleDubboEventMulticasterTest.java similarity index 79% rename from dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.java rename to dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleDubboEventMulticasterTest.java index b101d944e43..9adf276a77b 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleDubboEventMulticasterTest.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.metrics.event; +import org.apache.dubbo.common.utils.TimePair; 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.metrics.listener.AbstractMetricsKeyListener; import org.apache.dubbo.rpc.model.ApplicationModel; import org.junit.jupiter.api.Assertions; @@ -28,20 +28,26 @@ import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; -public class SimpleMetricsEventMulticasterTest { +public class SimpleDubboEventMulticasterTest { - private SimpleMetricsEventMulticaster eventMulticaster; + private TimeCounterEventMulticaster eventMulticaster; private Object[] objects; private final Object obj = new Object(); private TimeCounterEvent requestEvent; @BeforeEach public void setup() { - eventMulticaster = new SimpleMetricsEventMulticaster(); + eventMulticaster = new TimeCounterEventMulticaster(); objects = new Object[] {obj}; - eventMulticaster.addListener(new AbstractMetricsListener() { + eventMulticaster.addListener(new AbstractMetricsKeyListener(null) { + @Override - public void onEvent(MetricsEvent event) { + public boolean support(TimeCounterEvent event) { + return true; + } + + @Override + public void onEvent(TimeCounterEvent event) { objects[0] = new Object(); } }); @@ -52,7 +58,7 @@ public void onEvent(MetricsEvent event) { ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); applicationModel.setConfigManager(configManager); - requestEvent = new TimeCounterEvent(applicationModel, null) {}; + requestEvent = new TimeCounterEvent(applicationModel, null, TimePair.start()) {}; } @Test @@ -63,11 +69,11 @@ void testPublishFinishEvent() { Assertions.assertSame(obj, objects[0]); // do onEventFinish with MetricsLifeListener - eventMulticaster.addListener((new MetricsLifeListener() { + eventMulticaster.addListener(new AbstractMetricsKeyListener(null) { @Override - public boolean isSupport(MetricsEvent event) { - return event instanceof TimeCounterEvent; + public boolean support(TimeCounterEvent event) { + return true; } @Override @@ -80,7 +86,7 @@ public void onEventFinish(TimeCounterEvent event) { @Override public void onEventError(TimeCounterEvent event) {} - })); + }); eventMulticaster.publishFinishEvent(requestEvent); Assertions.assertNotSame(obj, objects[0]); } diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java index 3840862f68e..2aab5615412 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java @@ -16,11 +16,10 @@ */ package org.apache.dubbo.metrics.config.collector; +import org.apache.dubbo.common.event.DubboEventBus; 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.config.event.ConfigCenterEvent; import org.apache.dubbo.metrics.config.event.ConfigCenterSubDispatcher; import org.apache.dubbo.metrics.model.ConfigCenterMetric; import org.apache.dubbo.metrics.model.key.MetricsKey; @@ -42,7 +41,7 @@ * Config center implementation of {@link MetricsCollector} */ @Activate -public class ConfigCenterMetricsCollector extends CombMetricsCollector { +public class ConfigCenterMetricsCollector implements MetricsCollector { private Boolean collectEnabled = null; private final ApplicationModel applicationModel; @@ -51,9 +50,9 @@ public class ConfigCenterMetricsCollector extends CombMetricsCollector updatedMetrics = new ConcurrentHashMap<>(); public ConfigCenterMetricsCollector(ApplicationModel applicationModel) { - super(null); this.applicationModel = applicationModel; - super.setEventMulticaster(new ConfigCenterSubDispatcher(this)); + // bind dispatcher + DubboEventBus.addListener(applicationModel, new ConfigCenterSubDispatcher(this)); } public void setCollectEnabled(Boolean collectEnabled) { diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java deleted file mode 100644 index 58e9979f70b..00000000000 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metrics.config.event; - -import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; -import org.apache.dubbo.metrics.config.collector.ConfigCenterMetricsCollector; -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.rpc.model.ApplicationModel; - -import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SIZE; -import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CHANGE_TYPE; -import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_FILE; -import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_GROUP; -import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_PROTOCOL; -import static org.apache.dubbo.metrics.model.key.MetricsKey.CONFIGCENTER_METRIC_TOTAL; - -/** - * Registry related events - * Triggered in three types of configuration centers (apollo, zk, nacos) - */ -public class ConfigCenterEvent extends TimeCounterEvent { - - public static final String NACOS_PROTOCOL = "nacos"; - public static final String APOLLO_PROTOCOL = "apollo"; - public static final String ZK_PROTOCOL = "zookeeper"; - - public ConfigCenterEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { - super(applicationModel, typeWrapper); - ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); - ConfigCenterMetricsCollector collector; - if (!beanFactory.isDestroyed()) { - collector = beanFactory.getBean(ConfigCenterMetricsCollector.class); - super.setAvailable(collector != null && collector.isCollectEnabled()); - } - } - - public static ConfigCenterEvent toChangeEvent( - ApplicationModel applicationModel, - String key, - String group, - String protocol, - String changeType, - int count) { - ConfigCenterEvent configCenterEvent = new ConfigCenterEvent( - applicationModel, new TypeWrapper(MetricsLevel.CONFIG, CONFIGCENTER_METRIC_TOTAL)); - configCenterEvent.putAttachment(ATTACHMENT_KEY_CONFIG_FILE, key); - configCenterEvent.putAttachment(ATTACHMENT_KEY_CONFIG_GROUP, group); - configCenterEvent.putAttachment(ATTACHMENT_KEY_CONFIG_PROTOCOL, protocol); - configCenterEvent.putAttachment(ATTACHMENT_KEY_CHANGE_TYPE, changeType); - configCenterEvent.putAttachment(ATTACHMENT_KEY_SIZE, count); - return configCenterEvent; - } -} diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java index 49eab005783..8da92393776 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java @@ -16,38 +16,21 @@ */ package org.apache.dubbo.metrics.config.event; +import org.apache.dubbo.common.config.configcenter.ConfigCenterChangeEvent; +import org.apache.dubbo.common.event.AbstractDubboListener; import org.apache.dubbo.metrics.config.collector.ConfigCenterMetricsCollector; -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 static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SIZE; -import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CHANGE_TYPE; -import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_FILE; -import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_GROUP; -import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_PROTOCOL; +public final class ConfigCenterSubDispatcher extends AbstractDubboListener { -public final class ConfigCenterSubDispatcher extends SimpleMetricsEventMulticaster { + private ConfigCenterMetricsCollector collector; public ConfigCenterSubDispatcher(ConfigCenterMetricsCollector collector) { + this.collector = collector; + } - super.addListener(new AbstractMetricsKeyListener(MetricsKey.CONFIGCENTER_METRIC_TOTAL) { - @Override - public boolean isSupport(MetricsEvent event) { - return event instanceof ConfigCenterEvent; - } - - @Override - public void onEvent(TimeCounterEvent event) { - collector.increase( - event.getAttachmentValue(ATTACHMENT_KEY_CONFIG_FILE), - event.getAttachmentValue(ATTACHMENT_KEY_CONFIG_GROUP), - event.getAttachmentValue(ATTACHMENT_KEY_CONFIG_PROTOCOL), - event.getAttachmentValue(ATTACHMENT_KEY_CHANGE_TYPE), - event.getAttachmentValue(ATTACHMENT_KEY_SIZE)); - } - }); + @Override + public void onEvent(ConfigCenterChangeEvent event) { + collector.increase( + event.getKey(), event.getGroup(), event.getProtocol(), event.getChangeType(), event.getCount()); } } diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java index 35c44a94cad..9033b57f85a 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java @@ -16,8 +16,10 @@ */ package org.apache.dubbo.metrics.collector; +import org.apache.dubbo.common.config.configcenter.ConfigCenterChangeEvent; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.config.collector.ConfigCenterMetricsCollector; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; @@ -34,7 +36,6 @@ import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; -import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; class ConfigCenterMetricsCollectorTest { @@ -61,8 +62,12 @@ void increase4Initialized() { ConfigCenterMetricsCollector collector = new ConfigCenterMetricsCollector(applicationModel); collector.setCollectEnabled(true); String applicationName = applicationModel.getApplicationName(); - collector.increase("key", "group", "nacos", ConfigChangeType.ADDED.name(), 1); - collector.increase("key", "group", "nacos", ConfigChangeType.ADDED.name(), 1); + // collector.increase("key", "group", "nacos", ConfigChangeType.ADDED.name(), 1); + // collector.increase("key", "group", "nacos", ConfigChangeType.ADDED.name(), 1); + ConfigCenterChangeEvent configCenterChangeEvent = new ConfigCenterChangeEvent( + applicationModel, "key", "group", "nacos", ConfigChangeType.ADDED.name(), 1); + DubboEventBus.publish(configCenterChangeEvent); + DubboEventBus.publish(configCenterChangeEvent); List samples = collector.collect(); for (MetricSample sample : samples) { @@ -83,11 +88,18 @@ void increaseUpdated() { ConfigChangedEvent event = new ConfigChangedEvent("key", "group", null, ConfigChangeType.ADDED); - collector.increase( - event.getKey(), event.getGroup(), "apollo", ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE); - - collector.increase( - event.getKey(), event.getGroup(), "apollo", ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE); + // collector.increase( + // event.getKey(), event.getGroup(), "apollo", ConfigChangeType.ADDED.name(), + // SELF_INCREMENT_SIZE); + // + // collector.increase( + // event.getKey(), event.getGroup(), "apollo", ConfigChangeType.ADDED.name(), + // SELF_INCREMENT_SIZE); + + ConfigCenterChangeEvent configCenterChangeEvent = new ConfigCenterChangeEvent( + applicationModel, event.getKey(), event.getGroup(), "apollo", ConfigChangeType.ADDED.name()); + DubboEventBus.publish(configCenterChangeEvent); + DubboEventBus.publish(configCenterChangeEvent); List samples = collector.collect(); for (MetricSample sample : samples) { diff --git a/dubbo-metrics/dubbo-metrics-default/pom.xml b/dubbo-metrics/dubbo-metrics-default/pom.xml index 98fb0890137..35d5026a340 100644 --- a/dubbo-metrics/dubbo-metrics-default/pom.xml +++ b/dubbo-metrics/dubbo-metrics-default/pom.xml @@ -36,6 +36,11 @@ dubbo-metrics-api ${project.parent.version} + + org.apache.dubbo + dubbo-config-api + ${project.parent.version} + org.apache.dubbo diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DefaultMetricsServiceExporter.java similarity index 99% rename from dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java rename to dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DefaultMetricsServiceExporter.java index a3501102447..841e4cd8406 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DefaultMetricsServiceExporter.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.config.deploy; +package org.apache.dubbo.metrics; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java index 25ad926a6cc..3ddfa19e897 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java @@ -16,7 +16,11 @@ */ package org.apache.dubbo.metrics.collector; +import org.apache.dubbo.common.event.AbstractDubboLifecycleListener; +import org.apache.dubbo.common.event.AbstractDubboListener; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; +import org.apache.dubbo.config.InitServiceMethodEvent; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.nested.AggregationConfig; @@ -25,7 +29,8 @@ import org.apache.dubbo.metrics.aggregate.TimeWindowCounter; import org.apache.dubbo.metrics.aggregate.TimeWindowQuantile; import org.apache.dubbo.metrics.event.MetricsEvent; -import org.apache.dubbo.metrics.event.RequestEvent; +import org.apache.dubbo.metrics.event.MetricsInitEvent; +import org.apache.dubbo.metrics.event.RequestMetricsEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.key.MetricsKey; @@ -57,7 +62,7 @@ * Aggregation metrics collector implementation of {@link MetricsCollector}. * This collector only enabled when metrics aggregation config is enabled. */ -public class AggregateMetricsCollector implements MetricsCollector { +public class AggregateMetricsCollector implements MetricsCollector { private int bucketNum = DEFAULT_BUCKET_NUM; private int timeWindowSeconds = DEFAULT_TIME_WINDOW_SECONDS; private int qpsTimeWindowMillSeconds = DEFAULT_QPS_TIME_WINDOW_MILL_SECONDS; @@ -88,7 +93,16 @@ public AggregateMetricsCollector(ApplicationModel applicationModel) { // only registered when aggregation is enabled. Optional optional = configManager.getMetrics(); if (optional.isPresent()) { - registerListener(); + // register listener for init metrics + DubboEventBus.addListener(applicationModel, new AbstractDubboListener() { + @Override + public void onEvent(InitServiceMethodEvent event) { + MetricsInitEvent metricsInitEvent = MetricsInitEvent.toMetricsInitEvent(event); + initMetrics(metricsInitEvent); + } + }); + DubboEventBus.addListener(applicationModel, new AggregateMetricsEventListener(this)); + // init collector AggregationConfig aggregation = optional.get().getAggregation(); this.bucketNum = Optional.ofNullable(aggregation.getBucketNum()).orElse(DEFAULT_BUCKET_NUM); this.timeWindowSeconds = @@ -124,97 +138,113 @@ public boolean isCollectEnabled() { return Optional.ofNullable(collectEnabled).orElse(true); } - @Override - public boolean isSupport(MetricsEvent event) { - return event instanceof RequestEvent; - } + public static class AggregateMetricsEventListener extends AbstractDubboLifecycleListener { - @Override - public void onEvent(RequestEvent event) { - if (enableQps) { - MethodMetric metric = calcWindowCounter(event, MetricsKey.METRIC_REQUESTS); - TimeWindowCounter qpsCounter = qps.get(metric); - if (qpsCounter == null) { - qpsCounter = ConcurrentHashMapUtils.computeIfAbsent( - qps, - metric, - methodMetric -> new TimeWindowCounter( - bucketNum, TimeUnit.MILLISECONDS.toSeconds(qpsTimeWindowMillSeconds))); - samplesChanged.set(true); - } - qpsCounter.increment(); + private final AggregateMetricsCollector collector; + + public AggregateMetricsEventListener(AggregateMetricsCollector collector) { + this.collector = collector; } - } - @Override - public void onEventFinish(RequestEvent event) { - MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_SUCCEED; - Object throwableObj = event.getAttachmentValue(METRIC_THROWABLE); - if (throwableObj != null) { - targetKey = MetricsSupport.getAggMetricsKey((Throwable) throwableObj); + @Override + public void onEventBefore(RequestMetricsEvent event) { + if (collector.enableQps) { + MethodMetric metric = calcWindowCounter(event, MetricsKey.METRIC_REQUESTS); + TimeWindowCounter qpsCounter = collector.qps.get(metric); + if (qpsCounter == null) { + qpsCounter = ConcurrentHashMapUtils.computeIfAbsent( + collector.qps, + metric, + methodMetric -> new TimeWindowCounter( + collector.bucketNum, + TimeUnit.MILLISECONDS.toSeconds(collector.qpsTimeWindowMillSeconds))); + collector.samplesChanged.set(true); + } + qpsCounter.increment(); + } } - calcWindowCounter(event, targetKey); - onRTEvent(event); - } - @Override - public void onEventError(RequestEvent event) { - if (enableRequest) { - MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_FAILED; + @Override + public void onEventFinish(RequestMetricsEvent event) { + MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_SUCCEED; Object throwableObj = event.getAttachmentValue(METRIC_THROWABLE); if (throwableObj != null) { targetKey = MetricsSupport.getAggMetricsKey((Throwable) throwableObj); } calcWindowCounter(event, targetKey); - } - if (enableRt || enableRtPxx) { onRTEvent(event); } - } - private void onRTEvent(RequestEvent event) { - MethodMetric metric = - new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); - long responseTime = event.getTimePair().calc(); - if (enableRt) { - TimeWindowQuantile quantile = rt.get(metric); - if (quantile == null) { - quantile = ConcurrentHashMapUtils.computeIfAbsent( - rt, metric, k -> new TimeWindowQuantile(DEFAULT_COMPRESSION, bucketNum, timeWindowSeconds)); - samplesChanged.set(true); + @Override + public void onEventError(RequestMetricsEvent event) { + if (collector.enableRequest) { + MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_FAILED; + Object throwableObj = event.getAttachmentValue(METRIC_THROWABLE); + if (throwableObj != null) { + targetKey = MetricsSupport.getAggMetricsKey((Throwable) throwableObj); + } + calcWindowCounter(event, targetKey); } - quantile.add(responseTime); - } - - if (enableRtPxx) { - TimeWindowAggregator timeWindowAggregator = rtAgr.get(metric); - if (timeWindowAggregator == null) { - timeWindowAggregator = ConcurrentHashMapUtils.computeIfAbsent( - rtAgr, metric, methodMetric -> new TimeWindowAggregator(bucketNum, timeWindowSeconds)); - samplesChanged.set(true); + if (collector.enableRt || collector.enableRtPxx) { + onRTEvent(event); } - timeWindowAggregator.add(responseTime); } - } - private MethodMetric calcWindowCounter(RequestEvent event, MetricsKey targetKey) { - MetricsPlaceValue placeType = - MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.SERVICE); - MetricsKeyWrapper metricsKeyWrapper = new MetricsKeyWrapper(targetKey, placeType); - MethodMetric metric = - new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); + private void onRTEvent(RequestMetricsEvent event) { + MethodMetric metric = new MethodMetric( + event.getApplicationModel(), + event.getAttachmentValue(MetricsConstants.INVOCATION), + collector.serviceLevel); + long responseTime = event.getTimePair().calc(); + if (collector.enableRt) { + TimeWindowQuantile quantile = collector.rt.get(metric); + if (quantile == null) { + quantile = ConcurrentHashMapUtils.computeIfAbsent( + collector.rt, + metric, + k -> new TimeWindowQuantile( + DEFAULT_COMPRESSION, collector.bucketNum, collector.timeWindowSeconds)); + collector.samplesChanged.set(true); + } + quantile.add(responseTime); + } - ConcurrentMap counter = - methodTypeCounter.computeIfAbsent(metricsKeyWrapper, k -> new ConcurrentHashMap<>()); + if (collector.enableRtPxx) { + TimeWindowAggregator timeWindowAggregator = collector.rtAgr.get(metric); + if (timeWindowAggregator == null) { + timeWindowAggregator = ConcurrentHashMapUtils.computeIfAbsent( + collector.rtAgr, + metric, + methodMetric -> new TimeWindowAggregator(collector.bucketNum, collector.timeWindowSeconds)); + collector.samplesChanged.set(true); + } + timeWindowAggregator.add(responseTime); + } + } - TimeWindowCounter windowCounter = counter.get(metric); - if (windowCounter == null) { - windowCounter = ConcurrentHashMapUtils.computeIfAbsent( - counter, metric, methodMetric -> new TimeWindowCounter(bucketNum, timeWindowSeconds)); - samplesChanged.set(true); + private MethodMetric calcWindowCounter(RequestMetricsEvent event, MetricsKey targetKey) { + MetricsPlaceValue placeType = MetricsPlaceValue.of( + event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.SERVICE); + MetricsKeyWrapper metricsKeyWrapper = new MetricsKeyWrapper(targetKey, placeType); + MethodMetric metric = new MethodMetric( + event.getApplicationModel(), + event.getAttachmentValue(MetricsConstants.INVOCATION), + collector.serviceLevel); + + ConcurrentMap counter = + collector.methodTypeCounter.computeIfAbsent(metricsKeyWrapper, k -> new ConcurrentHashMap<>()); + + TimeWindowCounter windowCounter = counter.get(metric); + if (windowCounter == null) { + windowCounter = ConcurrentHashMapUtils.computeIfAbsent( + counter, + metric, + methodMetric -> new TimeWindowCounter(collector.bucketNum, collector.timeWindowSeconds)); + collector.samplesChanged.set(true); + } + windowCounter.increment(); + return metric; } - windowCounter.increment(); - return metric; } @Override @@ -336,15 +366,6 @@ private void collectRT(List list) { }); } - private void registerListener() { - applicationModel - .getBeanFactory() - .getBean(DefaultMetricsCollector.class) - .getEventMulticaster() - .addListener(this); - } - - @Override public void initMetrics(MetricsEvent event) { MethodMetric metric = new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java index 52c182f16df..f6ee9c834e8 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java @@ -17,7 +17,11 @@ package org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.event.AbstractDubboListener; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.Activate; +import org.apache.dubbo.config.InitServiceMethodEvent; +import org.apache.dubbo.config.deploy.event.ApplicationStartedEvent; import org.apache.dubbo.metrics.DefaultConstants; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.collector.sample.ErrorCodeSampler; @@ -31,8 +35,6 @@ import org.apache.dubbo.metrics.event.DefaultSubDispatcher; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.event.MetricsInitEvent; -import org.apache.dubbo.metrics.event.RequestEvent; -import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.ApplicationMetric; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.MetricsSupport; @@ -55,7 +57,7 @@ * Default implementation of {@link MetricsCollector} */ @Activate -public class DefaultMetricsCollector extends CombMetricsCollector { +public class DefaultMetricsCollector extends CombMetricsCollector { private boolean collectEnabled = false; @@ -73,12 +75,10 @@ public class DefaultMetricsCollector extends CombMetricsCollector private final List samplers = new ArrayList<>(); - private final List collectors = new ArrayList<>(); - - private final AtomicBoolean initialized = new AtomicBoolean(); - private final AtomicBoolean samplesChanged = new AtomicBoolean(); + public final DefaultSubDispatcher listener; + public DefaultMetricsCollector(ApplicationModel applicationModel) { super(new BaseStatComposite(applicationModel) { @Override @@ -95,7 +95,27 @@ protected void init(RtStatComposite rtStatComposite) { MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)); } }); - super.setEventMulticaster(new DefaultSubDispatcher(this)); + + // add listener for init + DubboEventBus.addListener(applicationModel, new AbstractDubboListener() { + @Override + public void onEvent(InitServiceMethodEvent event) { + MetricsInitEvent metricsInitEvent = MetricsInitEvent.toMetricsInitEvent(event); + initMetrics(metricsInitEvent); + } + }); + DubboEventBus.addListener(applicationModel, new AbstractDubboListener() { + @Override + public void onEvent(ApplicationStartedEvent event) { + if (isThreadpoolCollectEnabled()) { + registryDefaultSample(); + } + } + }); + // add listener for metrics + listener = new DefaultSubDispatcher(this); + DubboEventBus.addListener(applicationModel, listener); + this.samplers.add(applicationSampler); this.samplers.add(threadPoolSampler); this.samplesChanged.set(true); @@ -169,28 +189,7 @@ public List collect() { return list; } - @Override - public boolean isSupport(MetricsEvent event) { - return event instanceof RequestEvent || event instanceof MetricsInitEvent; - } - - @Override - public void onEvent(TimeCounterEvent event) { - if (event instanceof MetricsInitEvent) { - if (!metricsInitEnabled) { - return; - } - if (initialized.compareAndSet(false, true)) { - collectors.addAll(applicationModel.getBeanFactory().getBeansOfType(MetricsCollector.class)); - } - collectors.stream().forEach(collector -> collector.initMetrics(event)); - return; - } - super.onEvent(event); - } - - @Override - public void initMetrics(MetricsEvent event) { + public void initMetrics(MetricsInitEvent event) { MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); INIT_DEFAULT_METHOD_KEYS.stream() diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java index 807e31b2515..7ac47364d03 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java @@ -16,14 +16,15 @@ */ package org.apache.dubbo.metrics.collector; +import org.apache.dubbo.common.event.AbstractDubboLifecycleListener; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.nested.HistogramConfig; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.MetricsGlobalRegistry; -import org.apache.dubbo.metrics.event.RequestEvent; -import org.apache.dubbo.metrics.listener.AbstractMetricsListener; +import org.apache.dubbo.metrics.event.RequestMetricsEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.MetricSample; @@ -40,8 +41,7 @@ import static org.apache.dubbo.metrics.model.MetricsCategory.RT; -public class HistogramMetricsCollector extends AbstractMetricsListener - implements MetricsCollector { +public class HistogramMetricsCollector implements MetricsCollector { private final ConcurrentHashMap rt = new ConcurrentHashMap<>(); private HistogramMetricRegister metricRegister; @@ -60,7 +60,7 @@ public HistogramMetricsCollector(ApplicationModel applicationModel) { || config.getHistogram() == null || config.getHistogram().getEnabled() == null || Boolean.TRUE.equals(config.getHistogram().getEnabled())) { - registerListener(); + DubboEventBus.addListener(applicationModel, new HistogramMetricsEventListener(this)); HistogramConfig histogram; if (config == null || config.getHistogram() == null) { @@ -79,41 +79,42 @@ public HistogramMetricsCollector(ApplicationModel applicationModel) { } } - private void registerListener() { - applicationModel - .getBeanFactory() - .getBean(DefaultMetricsCollector.class) - .getEventMulticaster() - .addListener(this); - } - - @Override - public void onEvent(RequestEvent event) {} + public static class HistogramMetricsEventListener extends AbstractDubboLifecycleListener { - @Override - public void onEventFinish(RequestEvent event) { - onRTEvent(event); - } + private final HistogramMetricsCollector collector; - @Override - public void onEventError(RequestEvent event) { - onRTEvent(event); - } + public HistogramMetricsEventListener(HistogramMetricsCollector collector) { + this.collector = collector; + } - private void onRTEvent(RequestEvent event) { - if (metricRegister != null) { - MethodMetric metric = new MethodMetric( - applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); - long responseTime = event.getTimePair().calc(); + @Override + public void onEventFinish(RequestMetricsEvent event) { + onRTEvent(event); + } - HistogramMetricSample sample = new HistogramMetricSample( - MetricsKey.METRIC_RT_HISTOGRAM.getNameByType(metric.getSide()), - MetricsKey.METRIC_RT_HISTOGRAM.getDescription(), - metric.getTags(), - RT); + @Override + public void onEventError(RequestMetricsEvent event) { + onRTEvent(event); + } - Timer timer = ConcurrentHashMapUtils.computeIfAbsent(rt, metric, k -> metricRegister.register(sample)); - timer.record(responseTime, TimeUnit.MILLISECONDS); + private void onRTEvent(RequestMetricsEvent event) { + if (collector.metricRegister != null) { + MethodMetric metric = new MethodMetric( + collector.applicationModel, + event.getAttachmentValue(MetricsConstants.INVOCATION), + collector.serviceLevel); + long responseTime = event.getTimePair().calc(); + + HistogramMetricSample sample = new HistogramMetricSample( + MetricsKey.METRIC_RT_HISTOGRAM.getNameByType(metric.getSide()), + MetricsKey.METRIC_RT_HISTOGRAM.getDescription(), + metric.getTags(), + RT); + + Timer timer = ConcurrentHashMapUtils.computeIfAbsent( + collector.rt, metric, k -> collector.metricRegister.register(sample)); + timer.record(responseTime, TimeUnit.MILLISECONDS); + } } } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java index ca84829f9ef..03b6872bce9 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java @@ -17,11 +17,11 @@ package org.apache.dubbo.metrics.event; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.event.AbstractDubboLifecycleListener; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.collector.MethodMetricsCollector; import org.apache.dubbo.metrics.listener.AbstractMetricsKeyListener; -import org.apache.dubbo.metrics.listener.MetricsListener; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.key.CategoryOverall; import org.apache.dubbo.metrics.model.key.MetricsCat; @@ -32,35 +32,44 @@ import static org.apache.dubbo.metrics.DefaultConstants.METRIC_THROWABLE; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED; -@SuppressWarnings({"unchecked", "rawtypes"}) -public final class DefaultSubDispatcher extends SimpleMetricsEventMulticaster { +public final class DefaultSubDispatcher extends AbstractDubboLifecycleListener { - public DefaultSubDispatcher(DefaultMetricsCollector collector) { + private final TimeCounterEventMulticaster multicaster; + + private final DefaultMetricsCollector collector; + public DefaultSubDispatcher(DefaultMetricsCollector collector) { + this.collector = collector; + multicaster = new TimeCounterEventMulticaster(); CategoryOverall categoryOverall = initMethodRequest(); - super.addListener(categoryOverall.getPost().getEventFunc().apply(collector)); - super.addListener(categoryOverall.getFinish().getEventFunc().apply(collector)); - super.addListener(categoryOverall.getError().getEventFunc().apply(collector)); + multicaster.addListener(categoryOverall.getPost().getEventFunc().apply(collector)); + multicaster.addListener(categoryOverall.getFinish().getEventFunc().apply(collector)); + multicaster.addListener(categoryOverall.getError().getEventFunc().apply(collector)); + } - super.addListener(new MetricsListener() { + @Override + public void onEventBefore(RequestMetricsEvent event) { + this.multicaster.publishEvent(event); + } - @Override - public boolean isSupport(MetricsEvent event) { - return event instanceof RequestEvent && ((RequestEvent) event).isRequestErrorEvent(); - } + private final MetricsPlaceValue dynamicPlaceType = + MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD); - private final MetricsPlaceValue dynamicPlaceType = - MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD); + @Override + public void onEventFinish(RequestMetricsEvent event) { + this.multicaster.publishFinishEvent(event); + if (event.isRequestErrorEvent()) { + MetricsSupport.increment( + METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, + dynamicPlaceType, + (MethodMetricsCollector) collector, + event); + } + } - @Override - public void onEvent(RequestEvent event) { - MetricsSupport.increment( - METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, - dynamicPlaceType, - (MethodMetricsCollector) collector, - event); - } - }); + @Override + public void onEventError(RequestMetricsEvent event) { + this.multicaster.publishErrorEvent(event); } private CategoryOverall initMethodRequest() { diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java similarity index 82% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java rename to dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java index 864cc3c1740..d898cbe53cc 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java @@ -16,6 +16,8 @@ */ package org.apache.dubbo.metrics.event; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.config.InitServiceMethodEvent; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; @@ -32,11 +34,14 @@ public class MetricsInitEvent extends TimeCounterEvent { private static final TypeWrapper METRIC_EVENT = new TypeWrapper(MetricsLevel.SERVICE, METRIC_REQUESTS); public MetricsInitEvent(ApplicationModel source, TypeWrapper typeWrapper) { - super(source, typeWrapper); + super(source, typeWrapper, TimePair.start()); } - public static MetricsInitEvent toMetricsInitEvent( - ApplicationModel applicationModel, Invocation invocation, boolean serviceLevel) { + public static MetricsInitEvent toMetricsInitEvent(InitServiceMethodEvent event) { + ApplicationModel applicationModel = event.getApplicationModel(); + Invocation invocation = event.getInvocation(); + boolean serviceLevel = MethodMetric.isServiceLevel(event.getApplicationModel()); + MethodMetric methodMetric = new MethodMetric(applicationModel, invocation, serviceLevel); MetricsInitEvent initEvent = new MetricsInitEvent(applicationModel, METRIC_EVENT); initEvent.putAttachment(MetricsConstants.INVOCATION, invocation); diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestEvent.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestMetricsEvent.java similarity index 80% rename from dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestEvent.java rename to dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestMetricsEvent.java index 732aab1dce4..c0645765aeb 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestEvent.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestMetricsEvent.java @@ -17,6 +17,8 @@ package org.apache.dubbo.metrics.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.event.CustomAfterPost; +import org.apache.dubbo.common.utils.TimePair; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.exception.MetricsNeverHappenException; @@ -38,19 +40,18 @@ /** * Request related events */ -public class RequestEvent extends TimeCounterEvent { +public class RequestMetricsEvent extends TimeCounterEvent implements CustomAfterPost { private static final TypeWrapper REQUEST_EVENT = new TypeWrapper( MetricsLevel.SERVICE, METRIC_REQUESTS, METRIC_REQUESTS_SUCCEED, METRIC_REQUEST_BUSINESS_FAILED); private static final TypeWrapper REQUEST_ERROR_EVENT = new TypeWrapper(MetricsLevel.METHOD, MetricsKey.METRIC_REQUESTS); - public RequestEvent( + public RequestMetricsEvent( ApplicationModel applicationModel, String appName, - MetricsDispatcher metricsDispatcher, DefaultMetricsCollector collector, TypeWrapper TYPE_WRAPPER) { - super(applicationModel, appName, metricsDispatcher, TYPE_WRAPPER); + super(applicationModel, appName, TYPE_WRAPPER, TimePair.start()); if (collector == null) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); if (!beanFactory.isDestroyed()) { @@ -60,22 +61,21 @@ public RequestEvent( super.setAvailable(collector != null && collector.isCollectEnabled()); } - public static RequestEvent toRequestEvent( + public static RequestMetricsEvent toRequestEvent( ApplicationModel applicationModel, String appName, - MetricsDispatcher metricsDispatcher, DefaultMetricsCollector collector, Invocation invocation, String side, boolean serviceLevel) { MethodMetric methodMetric = new MethodMetric(applicationModel, invocation, serviceLevel); - RequestEvent requestEvent = - new RequestEvent(applicationModel, appName, metricsDispatcher, collector, REQUEST_EVENT); - requestEvent.putAttachment(MetricsConstants.INVOCATION, invocation); - requestEvent.putAttachment(MetricsConstants.METHOD_METRICS, methodMetric); - requestEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); - requestEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, side); - return requestEvent; + RequestMetricsEvent requestMetricsEvent = + new RequestMetricsEvent(applicationModel, appName, collector, REQUEST_EVENT); + requestMetricsEvent.putAttachment(MetricsConstants.INVOCATION, invocation); + requestMetricsEvent.putAttachment(MetricsConstants.METHOD_METRICS, methodMetric); + requestMetricsEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); + requestMetricsEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, side); + return requestMetricsEvent; } @Override @@ -93,15 +93,14 @@ public void customAfterPost(Object postResult) { /** * Acts on MetricsClusterFilter to monitor exceptions that occur before request execution */ - public static RequestEvent toRequestErrorEvent( + public static RequestMetricsEvent toRequestErrorEvent( ApplicationModel applicationModel, String appName, - MetricsDispatcher metricsDispatcher, Invocation invocation, String side, int code, boolean serviceLevel) { - RequestEvent event = new RequestEvent(applicationModel, appName, metricsDispatcher, null, REQUEST_ERROR_EVENT); + RequestMetricsEvent event = new RequestMetricsEvent(applicationModel, appName, null, REQUEST_ERROR_EVENT); event.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); event.putAttachment(MetricsConstants.INVOCATION_SIDE, side); event.putAttachment(MetricsConstants.INVOCATION, invocation); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsConsumerFilter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsConsumerFilter.java similarity index 94% rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsConsumerFilter.java rename to dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsConsumerFilter.java index 7e3619094b4..5c21dc52342 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsConsumerFilter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsConsumerFilter.java @@ -14,10 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.rpc.cluster.filter.support; +package org.apache.dubbo.metrics.filter; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metrics.filter.MetricsFilter; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java index 900dc7002b9..8f43011da4e 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java @@ -16,13 +16,12 @@ */ package org.apache.dubbo.metrics.filter; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; -import org.apache.dubbo.metrics.event.MetricsDispatcher; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.event.RequestEvent; +import org.apache.dubbo.metrics.event.RequestMetricsEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.rpc.Invocation; @@ -44,7 +43,6 @@ public class MetricsFilter implements ScopeModelAware { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(MetricsFilter.class); private boolean rpcMetricsEnable; private String appName; - private MetricsDispatcher metricsDispatcher; private DefaultMetricsCollector defaultMetricsCollector; private boolean serviceLevel; @@ -57,7 +55,6 @@ public void setApplicationModel(ApplicationModel applicationModel) { .map(MetricsConfig::getEnableRpc) .orElse(true); this.appName = applicationModel.tryGetApplicationName(); - this.metricsDispatcher = applicationModel.getBeanFactory().getBean(MetricsDispatcher.class); this.defaultMetricsCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); serviceLevel = MethodMetric.isServiceLevel(applicationModel); } @@ -69,15 +66,14 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept public Result invoke(Invoker invoker, Invocation invocation, boolean isProvider) throws RpcException { if (rpcMetricsEnable) { try { - RequestEvent requestEvent = RequestEvent.toRequestEvent( + RequestMetricsEvent requestEvent = RequestMetricsEvent.toRequestEvent( applicationModel, appName, - metricsDispatcher, defaultMetricsCollector, invocation, isProvider ? PROVIDER : CONSUMER, serviceLevel); - MetricsEventBus.before(requestEvent); + DubboEventBus.before(requestEvent); invocation.put(METRIC_FILTER_EVENT, requestEvent); } catch (Throwable t) { LOGGER.warn(INTERNAL_ERROR, "", "", "Error occurred when invoke.", t); @@ -94,7 +90,7 @@ public void onResponse(Result result, Invoker invoker, Invocation invocation, Object eventObj = invocation.get(METRIC_FILTER_EVENT); if (eventObj != null) { try { - MetricsEventBus.after((RequestEvent) eventObj, result); + DubboEventBus.after((RequestMetricsEvent) eventObj, result); } catch (Throwable t) { LOGGER.warn(INTERNAL_ERROR, "", "", "Error occurred when onResponse.", t); } @@ -109,9 +105,9 @@ public void onError(Throwable t, Invoker invoker, Invocation invocation, bool Object eventObj = invocation.get(METRIC_FILTER_EVENT); if (eventObj != null) { try { - RequestEvent requestEvent = (RequestEvent) eventObj; + RequestMetricsEvent requestEvent = (RequestMetricsEvent) eventObj; requestEvent.putAttachment(METRIC_THROWABLE, t); - MetricsEventBus.error(requestEvent); + DubboEventBus.error(requestEvent); } catch (Throwable throwable) { LOGGER.warn(INTERNAL_ERROR, "", "", "Error occurred when onResponse.", throwable); } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java index 2548bb81048..67110828457 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java @@ -54,7 +54,7 @@ public Map> getMetricsByCategories( public Map> getMetricsByCategories( String serviceUniqueName, String methodName, Class[] parameterTypes, List categories) { Map> result = new HashMap<>(); - for (MetricsCollector collector : collectors) { + for (MetricsCollector collector : collectors) { List samples = collector.collect(); for (MetricSample sample : samples) { if (categories.contains(sample.getCategory())) { diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java index 35f9942fe4c..608b1c3d0ca 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java @@ -16,11 +16,10 @@ */ package org.apache.dubbo.rpc.cluster.filter.support; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; -import org.apache.dubbo.metrics.event.MetricsDispatcher; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.event.RequestEvent; +import org.apache.dubbo.metrics.event.RequestMetricsEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Invocation; @@ -40,7 +39,6 @@ public class MetricsClusterFilter implements ClusterFilter, BaseFilter.Listener, private ApplicationModel applicationModel; private DefaultMetricsCollector collector; private String appName; - private MetricsDispatcher metricsDispatcher; private boolean serviceLevel; @Override @@ -48,7 +46,6 @@ public void setApplicationModel(ApplicationModel applicationModel) { this.applicationModel = applicationModel; this.collector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); this.appName = applicationModel.tryGetApplicationName(); - this.metricsDispatcher = applicationModel.getBeanFactory().getBean(MetricsDispatcher.class); this.serviceLevel = MethodMetric.isServiceLevel(applicationModel); } @@ -74,14 +71,8 @@ private void handleMethodException(Throwable t, Invocation invocation) { if (t instanceof RpcException) { RpcException e = (RpcException) t; if (e.isForbidden()) { - MetricsEventBus.publish(RequestEvent.toRequestErrorEvent( - applicationModel, - appName, - metricsDispatcher, - invocation, - CONSUMER_SIDE, - e.getCode(), - serviceLevel)); + DubboEventBus.publish(RequestMetricsEvent.toRequestErrorEvent( + applicationModel, appName, invocation, CONSUMER_SIDE, e.getCode(), serviceLevel)); } } } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter new file mode 100644 index 00000000000..6d6fd48ad3f --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter @@ -0,0 +1 @@ +default=org.apache.dubbo.metrics.DefaultMetricsServiceExporter diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter index 3d5a3f49370..c0bcbe620b6 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter +++ b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter @@ -1,2 +1,3 @@ metricsClusterFilter=org.apache.dubbo.rpc.cluster.filter.support.MetricsClusterFilter monitor=org.apache.dubbo.monitor.support.MonitorClusterFilter +metricsConsumerFilter=org.apache.dubbo.metrics.filter.MetricsConsumerFilter diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java index c61fd486209..91d94b14870 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java @@ -17,6 +17,7 @@ package org.apache.dubbo.metrics; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; @@ -46,6 +47,8 @@ public class DefaultMetricsServiceTest { @BeforeEach public void setUp() { ApplicationModel applicationModel = Mockito.mock(ApplicationModel.class); + new DubboApplicationMulticasterRegistry().initializeApplicationModel(applicationModel); + ScopeBeanFactory beanFactory = Mockito.mock(ScopeBeanFactory.class); metricsCollector = Mockito.mock(MetricsCollector.class); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java index ef049eb49c6..b12f20b0cb9 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java @@ -19,8 +19,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry; +import org.apache.dubbo.common.event.DubboEventBus; +import org.apache.dubbo.common.event.DubboListener; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ReflectionUtils; +import org.apache.dubbo.common.utils.TimePair; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -28,14 +32,10 @@ import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.TestMetricsInvoker; import org.apache.dubbo.metrics.aggregate.TimeWindowCounter; -import org.apache.dubbo.metrics.event.MetricsDispatcher; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.event.RequestEvent; +import org.apache.dubbo.metrics.event.RequestMetricsEvent; import org.apache.dubbo.metrics.filter.MetricsFilter; -import org.apache.dubbo.metrics.listener.MetricsListener; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; -import org.apache.dubbo.metrics.model.TimePair; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; @@ -82,7 +82,6 @@ class AggregateMetricsCollectorTest { private String version; private RpcInvocation invocation; private String side; - private MetricsDispatcher metricsDispatcher; private AggregateMetricsCollector collector; private MetricsFilter metricsFilter; @@ -111,7 +110,6 @@ public void setup() { aggregationConfig.setTimeWindowSeconds(120); metricsConfig.setAggregation(aggregationConfig); applicationModel.getApplicationConfigManager().setMetrics(metricsConfig); - metricsDispatcher = applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); collector = applicationModel.getBeanFactory().getOrRegisterBean(AggregateMetricsCollector.class); collector.setCollectEnabled(true); @@ -139,26 +137,25 @@ public void setup() { @Test void testListener() { - AggregateMetricsCollector metricsCollector = new AggregateMetricsCollector(applicationModel); - RequestEvent event = RequestEvent.toRequestEvent( + AggregateMetricsCollector.AggregateMetricsEventListener metricscollector = + new AggregateMetricsCollector.AggregateMetricsEventListener(collector); + RequestMetricsEvent event = RequestMetricsEvent.toRequestEvent( applicationModel, null, null, - null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); - RequestEvent beforeEvent = RequestEvent.toRequestErrorEvent( + RequestMetricsEvent beforeEvent = RequestMetricsEvent.toRequestErrorEvent( applicationModel, null, - null, invocation, MetricsSupport.getSide(invocation), RpcException.FORBIDDEN_EXCEPTION, MethodMetric.isServiceLevel(applicationModel)); - Assertions.assertTrue(metricsCollector.isSupport(event)); - Assertions.assertTrue(metricsCollector.isSupport(beforeEvent)); + Assertions.assertTrue(metricscollector.support(event.getClass())); + Assertions.assertTrue(metricscollector.support(beforeEvent.getClass())); } @AfterEach @@ -206,6 +203,8 @@ void testRequestsMetrics() { @Test public void testQPS() { ApplicationModel applicationModel = mock(ApplicationModel.class); + new DubboApplicationMulticasterRegistry().initializeApplicationModel(applicationModel); + ConfigManager configManager = mock(ConfigManager.class); MetricsConfig metricsConfig = mock(MetricsConfig.class); ScopeBeanFactory beanFactory = mock(ScopeBeanFactory.class); @@ -250,7 +249,6 @@ public void testQPS() { @Test public void testRtAggregation() { - metricsDispatcher.addListener(collector); ConfigManager configManager = applicationModel.getApplicationConfigManager(); MetricsConfig config = configManager.getMetrics().orElse(null); AggregationConfig aggregationConfig = new AggregationConfig(); @@ -263,21 +261,20 @@ public void testRtAggregation() { rtList.add(30L); for (Long requestTime : rtList) { - RequestEvent requestEvent = RequestEvent.toRequestEvent( + RequestMetricsEvent requestMetricsEvent = RequestMetricsEvent.toRequestEvent( applicationModel, null, null, - null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); - TestRequestEvent testRequestEvent = - new TestRequestEvent(requestEvent.getSource(), requestEvent.getTypeWrapper()); + TestRequestMetricsEvent testRequestEvent = + new TestRequestMetricsEvent(requestMetricsEvent.getSource(), requestMetricsEvent.getTypeWrapper()); testRequestEvent.putAttachment(MetricsConstants.INVOCATION, invocation); testRequestEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); testRequestEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, MetricsSupport.getSide(invocation)); testRequestEvent.setRt(requestTime); - MetricsEventBus.post(testRequestEvent, () -> null); + DubboEventBus.post(testRequestEvent, () -> null); } List samples = collector.collect(); @@ -299,8 +296,6 @@ public void testRtAggregation() { @Test void testP95AndP99() throws InterruptedException { - - metricsDispatcher.addListener(collector); ConfigManager configManager = applicationModel.getApplicationConfigManager(); MetricsConfig config = configManager.getMetrics().orElse(null); AggregationConfig aggregationConfig = new AggregationConfig(); @@ -321,21 +316,20 @@ void testP95AndP99() throws InterruptedException { double manualP99 = requestTimes.get((int) Math.round(p99Index)); for (Long requestTime : requestTimes) { - RequestEvent requestEvent = RequestEvent.toRequestEvent( + RequestMetricsEvent requestMetricsEvent = RequestMetricsEvent.toRequestEvent( applicationModel, null, null, - null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); - TestRequestEvent testRequestEvent = - new TestRequestEvent(requestEvent.getSource(), requestEvent.getTypeWrapper()); + TestRequestMetricsEvent testRequestEvent = + new TestRequestMetricsEvent(requestMetricsEvent.getSource(), requestMetricsEvent.getTypeWrapper()); testRequestEvent.putAttachment(MetricsConstants.INVOCATION, invocation); testRequestEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); testRequestEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, MetricsSupport.getSide(invocation)); testRequestEvent.setRt(requestTime); - MetricsEventBus.post(testRequestEvent, () -> null); + DubboEventBus.post(testRequestEvent, () -> null); } Thread.sleep(4000L); @@ -367,17 +361,17 @@ void testP95AndP99() throws InterruptedException { @Test void testGenericCache() { - List> classGenerics = - ReflectionUtils.getClassGenerics(AggregateMetricsCollector.class, MetricsListener.class); + List> classGenerics = ReflectionUtils.getClassGenerics( + AggregateMetricsCollector.AggregateMetricsEventListener.class, DubboListener.class); Assertions.assertTrue(CollectionUtils.isNotEmpty(classGenerics)); - Assertions.assertEquals(RequestEvent.class, classGenerics.get(0)); + Assertions.assertEquals(RequestMetricsEvent.class, classGenerics.get(0)); } - public static class TestRequestEvent extends RequestEvent { + public static class TestRequestMetricsEvent extends RequestMetricsEvent { private long rt; - public TestRequestEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { - super(applicationModel, null, null, null, typeWrapper); + public TestRequestMetricsEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { + super(applicationModel, null, null, typeWrapper); } public void setRt(long rt) { diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java index 9105d1b518a..74c8502012f 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java @@ -22,8 +22,7 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.TestMetricsInvoker; -import org.apache.dubbo.metrics.event.MetricsDispatcher; -import org.apache.dubbo.metrics.event.RequestEvent; +import org.apache.dubbo.metrics.event.RequestMetricsEvent; import org.apache.dubbo.metrics.filter.MetricsFilter; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; @@ -75,9 +74,6 @@ class DefaultCollectorTest { private RpcInvocation invocation; private String side; - MetricsDispatcher metricsDispatcher; - DefaultMetricsCollector defaultCollector; - MetricsFilter metricsFilter; @BeforeEach @@ -88,9 +84,6 @@ public void setup() { config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); - metricsDispatcher = applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); - defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); - defaultCollector.setCollectEnabled(true); interfaceName = "org.apache.dubbo.MockInterface"; methodName = "mockMethod"; @@ -113,25 +106,23 @@ public void setup() { @Test void testListener() { DefaultMetricsCollector metricsCollector = new DefaultMetricsCollector(applicationModel); - RequestEvent event = RequestEvent.toRequestEvent( + RequestMetricsEvent event = RequestMetricsEvent.toRequestEvent( applicationModel, null, null, - null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); - RequestEvent beforeEvent = RequestEvent.toRequestErrorEvent( + RequestMetricsEvent beforeEvent = RequestMetricsEvent.toRequestErrorEvent( applicationModel, null, - null, invocation, MetricsSupport.getSide(invocation), RpcException.FORBIDDEN_EXCEPTION, MethodMetric.isServiceLevel(applicationModel)); - Assertions.assertTrue(metricsCollector.isSupport(event)); - Assertions.assertTrue(metricsCollector.isSupport(beforeEvent)); + Assertions.assertTrue(metricsCollector.listener.support(event.getClass())); + Assertions.assertTrue(metricsCollector.listener.support(beforeEvent.getClass())); } @AfterEach @@ -145,7 +136,6 @@ public void teardown() { @Test void testRequestEventNoRt() { - applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); DefaultMetricsCollector collector = applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); collector.setCollectEnabled(true); @@ -164,7 +154,7 @@ void testRequestEventNoRt() { Result result = AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation); metricsFilter.onResponse(result, new TestMetricsInvoker(side), invocation); - RequestEvent eventObj = (RequestEvent) invocation.get(METRIC_FILTER_EVENT); + RequestMetricsEvent eventObj = (RequestMetricsEvent) invocation.get(METRIC_FILTER_EVENT); long c1 = eventObj.getTimePair().calc(); // push finish rt +1 @@ -216,7 +206,7 @@ void testRequestEventNoRt() { } metricsFilter.onError( new RpcException(RpcException.TIMEOUT_EXCEPTION, "timeout"), new TestMetricsInvoker(side), invocation); - eventObj = (RequestEvent) invocation.get(METRIC_FILTER_EVENT); + eventObj = (RequestMetricsEvent) invocation.get(METRIC_FILTER_EVENT); long c2 = eventObj.getTimePair().calc(); metricSamples = collector.collect(); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java index f036eb7dfa2..b9dcb8c52d7 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java @@ -17,13 +17,12 @@ package org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.InitServiceMethodEvent; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.nested.AggregationConfig; import org.apache.dubbo.metrics.aggregate.TimeWindowCounter; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.event.MetricsInitEvent; -import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.ServiceKeyMetric; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsLevel; @@ -82,7 +81,7 @@ public void setup() { applicationModel.getApplicationConfigManager().setMetrics(metricsConfig); applicationModel.getApplicationConfigManager().setApplication(config); - defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); + defaultCollector = new DefaultMetricsCollector(applicationModel); defaultCollector.setCollectEnabled(true); aggregateMetricsCollector = @@ -101,8 +100,7 @@ public void setup() { RpcInvocation invocation = new RpcInvocation( serviceKey, null, methodName, interfaceName, protocolServiceKey, null, null, null, null, null, null); - MetricsEventBus.publish(MetricsInitEvent.toMetricsInitEvent( - applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel))); + DubboEventBus.publish(new InitServiceMethodEvent(applicationModel, invocation)); } @AfterEach diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java index d33fcc1070b..c31c06970e6 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java @@ -17,6 +17,7 @@ package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; @@ -34,6 +35,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -49,12 +51,20 @@ public class ThreadPoolMetricsSamplerTest { ThreadPoolMetricsSampler sampler; + private DubboApplicationMulticasterRegistry multicasterRegistry = new DubboApplicationMulticasterRegistry(); + @BeforeEach void setUp() { + multicasterRegistry.initializeApplicationModel(applicationModel); DefaultMetricsCollector collector = new DefaultMetricsCollector(applicationModel); sampler = new ThreadPoolMetricsSampler(collector); } + @AfterEach + void tearDown() { + multicasterRegistry.onDestroy(applicationModel); + } + @Test void testSample() { @@ -135,6 +145,7 @@ void testSample() { @BeforeEach public void setUp2() { MockitoAnnotations.openMocks(this); + new DubboApplicationMulticasterRegistry().initializeApplicationModel(applicationModel); collector = new DefaultMetricsCollector(applicationModel); sampler2 = new ThreadPoolMetricsSampler(collector); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java index b668c770245..57d488cd16a 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java @@ -18,11 +18,11 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.TestMetricsInvoker; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.event.RequestEvent; +import org.apache.dubbo.metrics.event.RequestMetricsEvent; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsLevel; @@ -406,7 +406,7 @@ void testThrowable() { result.setException(new RuntimeException("failed")); Object eventObj = invocation.get(METRIC_FILTER_EVENT); if (eventObj != null) { - Assertions.assertDoesNotThrow(() -> MetricsEventBus.after((RequestEvent) eventObj, result)); + Assertions.assertDoesNotThrow(() -> DubboEventBus.after((RequestMetricsEvent) eventObj, result)); } } } diff --git a/dubbo-metrics/dubbo-metrics-metadata/pom.xml b/dubbo-metrics/dubbo-metrics-metadata/pom.xml index 1de43cac944..373586537fd 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/pom.xml +++ b/dubbo-metrics/dubbo-metrics-metadata/pom.xml @@ -36,6 +36,11 @@ dubbo-metrics-api ${project.parent.version} + + org.apache.dubbo + dubbo-registry-api + ${project.parent.version} + org.apache.logging.log4j log4j-slf4j-impl diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java index 82dcc7cd97d..d71a2792b66 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.metrics.metadata.collector; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.collector.CombMetricsCollector; @@ -25,7 +26,6 @@ import org.apache.dubbo.metrics.data.RtStatComposite; import org.apache.dubbo.metrics.data.ServiceStatComposite; import org.apache.dubbo.metrics.metadata.MetadataMetricsConstants; -import org.apache.dubbo.metrics.metadata.event.MetadataEvent; import org.apache.dubbo.metrics.metadata.event.MetadataSubDispatcher; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.MetricSample; @@ -43,7 +43,7 @@ * Registry implementation of {@link MetricsCollector} */ @Activate -public class MetadataMetricsCollector extends CombMetricsCollector { +public class MetadataMetricsCollector extends CombMetricsCollector { private Boolean collectEnabled = null; private final ApplicationModel applicationModel; @@ -68,8 +68,9 @@ protected void init(RtStatComposite rtStatComposite) { rtStatComposite.init(OP_TYPE_PUSH, OP_TYPE_SUBSCRIBE, OP_TYPE_STORE_PROVIDER_INTERFACE); } }); - super.setEventMulticaster(new MetadataSubDispatcher(this)); this.applicationModel = applicationModel; + + DubboEventBus.addListener(applicationModel, new MetadataSubDispatcher(this)); } public void setCollectEnabled(Boolean collectEnabled) { diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataEvent.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEvent.java similarity index 57% rename from dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataEvent.java rename to dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEvent.java index a14c6690526..2e8ad3e751d 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataEvent.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEvent.java @@ -17,6 +17,11 @@ package org.apache.dubbo.metrics.metadata.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.metadata.event.MetaDataEvent; +import org.apache.dubbo.metadata.event.MetaDataPushEvent; +import org.apache.dubbo.metadata.event.MetaDataServiceSubscribeEvent; +import org.apache.dubbo.metadata.event.MetaDataSubscribeEvent; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.metadata.collector.MetadataMetricsCollector; import org.apache.dubbo.metrics.model.key.MetricsLevel; @@ -37,9 +42,9 @@ /** * Registry related events */ -public class MetadataEvent extends TimeCounterEvent { - public MetadataEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { - super(applicationModel, typeWrapper); +public class MetadataMetricsEvent extends TimeCounterEvent { + public MetadataMetricsEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper, TimePair timePair) { + super(applicationModel, typeWrapper, timePair); ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); MetadataMetricsCollector collector; if (!beanFactory.isDestroyed()) { @@ -48,35 +53,56 @@ public MetadataEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) } } - public static MetadataEvent toPushEvent(ApplicationModel applicationModel) { - return new MetadataEvent( + public static MetadataMetricsEvent toPushEvent(ApplicationModel applicationModel, TimePair timePair) { + return new MetadataMetricsEvent( applicationModel, new TypeWrapper( MetricsLevel.APP, METADATA_PUSH_METRIC_NUM, METADATA_PUSH_METRIC_NUM_SUCCEED, - METADATA_PUSH_METRIC_NUM_FAILED)); + METADATA_PUSH_METRIC_NUM_FAILED), + timePair); } - public static MetadataEvent toSubscribeEvent(ApplicationModel applicationModel) { - return new MetadataEvent( + public static MetadataMetricsEvent toSubscribeEvent(ApplicationModel applicationModel, TimePair timePair) { + return new MetadataMetricsEvent( applicationModel, new TypeWrapper( MetricsLevel.APP, METADATA_SUBSCRIBE_METRIC_NUM, METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED, - METADATA_SUBSCRIBE_METRIC_NUM_FAILED)); + METADATA_SUBSCRIBE_METRIC_NUM_FAILED), + timePair); } - public static MetadataEvent toServiceSubscribeEvent(ApplicationModel applicationModel, String serviceKey) { - MetadataEvent metadataEvent = new MetadataEvent( + public static MetadataMetricsEvent toServiceSubscribeEvent( + ApplicationModel applicationModel, String serviceKey, TimePair timePair) { + MetadataMetricsEvent metadataMetricsEvent = new MetadataMetricsEvent( applicationModel, new TypeWrapper( MetricsLevel.APP, STORE_PROVIDER_METADATA, STORE_PROVIDER_METADATA_SUCCEED, - STORE_PROVIDER_METADATA_FAILED)); - metadataEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); - return metadataEvent; + STORE_PROVIDER_METADATA_FAILED), + timePair); + metadataMetricsEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); + return metadataMetricsEvent; + } + + public static MetadataMetricsEvent convertEvent(MetaDataEvent event) { + MetadataMetricsEvent metadataMetricsEvent; + if (event instanceof MetaDataPushEvent) { + metadataMetricsEvent = MetadataMetricsEvent.toPushEvent(event.getApplicationModel(), event.getTimePair()); + } else if (event instanceof MetaDataSubscribeEvent) { + metadataMetricsEvent = + MetadataMetricsEvent.toSubscribeEvent(event.getApplicationModel(), event.getTimePair()); + } else if (event instanceof MetaDataServiceSubscribeEvent) { + MetaDataServiceSubscribeEvent serviceEvent = (MetaDataServiceSubscribeEvent) event; + metadataMetricsEvent = MetadataMetricsEvent.toServiceSubscribeEvent( + event.getApplicationModel(), serviceEvent.getServiceKey(), event.getTimePair()); + } else { + return null; + } + return metadataMetricsEvent; } } diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java index bc7ec7fa0f1..de7caa9db45 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java @@ -16,7 +16,11 @@ */ package org.apache.dubbo.metrics.metadata.event; -import org.apache.dubbo.metrics.event.SimpleMetricsEventMulticaster; +import org.apache.dubbo.common.event.AbstractDubboLifecycleListener; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.metadata.event.MetaDataEvent; +import org.apache.dubbo.metrics.event.TimeCounterEventMulticaster; import org.apache.dubbo.metrics.listener.MetricsApplicationListener; import org.apache.dubbo.metrics.listener.MetricsServiceListener; import org.apache.dubbo.metrics.metadata.collector.MetadataMetricsCollector; @@ -31,21 +35,57 @@ import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_STORE_PROVIDER_INTERFACE; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_SUBSCRIBE; -public final class MetadataSubDispatcher extends SimpleMetricsEventMulticaster { +public final class MetadataSubDispatcher extends AbstractDubboLifecycleListener { - public MetadataSubDispatcher(MetadataMetricsCollector collector) { + ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MetadataSubDispatcher.class); + + private final TimeCounterEventMulticaster multicaster; + public MetadataSubDispatcher(MetadataMetricsCollector collector) { + this.multicaster = new TimeCounterEventMulticaster(); CategorySet.ALL.forEach(categorySet -> { - super.addListener(categorySet.getPost().getEventFunc().apply(collector)); + this.multicaster.addListener(categorySet.getPost().getEventFunc().apply(collector)); if (categorySet.getFinish() != null) { - super.addListener(categorySet.getFinish().getEventFunc().apply(collector)); + this.multicaster.addListener( + categorySet.getFinish().getEventFunc().apply(collector)); } if (categorySet.getError() != null) { - super.addListener(categorySet.getError().getEventFunc().apply(collector)); + this.multicaster.addListener( + categorySet.getError().getEventFunc().apply(collector)); } }); } + @Override + public void onEventBefore(MetaDataEvent event) { + MetadataMetricsEvent metadataMetricsEvent = MetadataMetricsEvent.convertEvent(event); + if (metadataMetricsEvent == null) { + logger.debug("Unsupported event type: {}", event.getClass().getName()); + return; + } + this.multicaster.publishEvent(metadataMetricsEvent); + } + + @Override + public void onEventFinish(MetaDataEvent event) { + MetadataMetricsEvent metadataMetricsEvent = MetadataMetricsEvent.convertEvent(event); + if (metadataMetricsEvent == null) { + logger.debug("Unsupported event type: {}", event.getClass().getName()); + return; + } + this.multicaster.publishFinishEvent(metadataMetricsEvent); + } + + @Override + public void onEventError(MetaDataEvent event) { + MetadataMetricsEvent metadataMetricsEvent = MetadataMetricsEvent.convertEvent(event); + if (metadataMetricsEvent == null) { + logger.debug("Unsupported event type: {}", event.getClass().getName()); + return; + } + this.multicaster.publishErrorEvent(metadataMetricsEvent); + } + /** * A closer aggregation of MetricsCat, a summary collection of certain types of events */ diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java index 8ee31a9e795..4050b592a63 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java @@ -16,13 +16,15 @@ */ package org.apache.dubbo.metrics.metadata; +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.common.event.DubboEventBus; +import org.apache.dubbo.common.utils.TimePair; import org.apache.dubbo.config.ApplicationConfig; -import org.apache.dubbo.metrics.event.MetricsDispatcher; -import org.apache.dubbo.metrics.event.MetricsEvent; -import org.apache.dubbo.metrics.event.MetricsEventBus; +import org.apache.dubbo.metadata.event.MetaDataPushEvent; +import org.apache.dubbo.metadata.event.MetaDataServiceSubscribeEvent; +import org.apache.dubbo.metadata.event.MetaDataSubscribeEvent; import org.apache.dubbo.metrics.metadata.collector.MetadataMetricsCollector; -import org.apache.dubbo.metrics.metadata.event.MetadataEvent; -import org.apache.dubbo.metrics.model.TimePair; +import org.apache.dubbo.metrics.metadata.event.MetadataSubDispatcher; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; @@ -60,7 +62,6 @@ public void setup() { config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); - applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); collector = applicationModel.getBeanFactory().getOrRegisterBean(MetadataMetricsCollector.class); collector.setCollectEnabled(true); @@ -68,10 +69,17 @@ public void setup() { @Test void testListener() { - MetadataEvent event = MetadataEvent.toPushEvent(applicationModel); - MetricsEvent otherEvent = new MetricsEvent(applicationModel, null, null, null) {}; - Assertions.assertTrue(collector.isSupport(event)); - Assertions.assertFalse(collector.isSupport(otherEvent)); + MetadataSubDispatcher dispatcher = new MetadataSubDispatcher(collector); + MetaDataPushEvent event = new MetaDataPushEvent(applicationModel); + MetaDataSubscribeEvent subscribeEvent = new MetaDataSubscribeEvent(applicationModel); + MetaDataServiceSubscribeEvent serviceSubscribeEvent = + new MetaDataServiceSubscribeEvent(applicationModel, "serviceKey"); + + DubboEvent otherEvent = new DubboEvent(applicationModel); + Assertions.assertTrue(dispatcher.support(event.getClass())); + Assertions.assertTrue(dispatcher.support(subscribeEvent.getClass())); + Assertions.assertTrue(dispatcher.support(serviceSubscribeEvent.getClass())); + Assertions.assertFalse(dispatcher.support(otherEvent.getClass())); } @AfterEach @@ -81,10 +89,8 @@ public void teardown() { @Test void testPushMetrics() { - // MetadataMetricsCollector collector = getCollector(); - - MetadataEvent pushEvent = MetadataEvent.toPushEvent(applicationModel); - MetricsEventBus.post(pushEvent, () -> { + MetaDataPushEvent pushEvent = new MetaDataPushEvent(applicationModel); + DubboEventBus.post(pushEvent, () -> { List metricSamples = collector.collect(); // push success +1 @@ -102,9 +108,9 @@ void testPushMetrics() { Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size()); long c1 = pushEvent.getTimePair().calc(); - pushEvent = MetadataEvent.toPushEvent(applicationModel); + pushEvent = new MetaDataPushEvent(applicationModel); TimePair lastTimePair = pushEvent.getTimePair(); - MetricsEventBus.post( + DubboEventBus.post( pushEvent, () -> { try { @@ -152,8 +158,8 @@ void testPushMetrics() { void testSubscribeMetrics() { // MetadataMetricsCollector collector = getCollector(); - MetadataEvent subscribeEvent = MetadataEvent.toSubscribeEvent(applicationModel); - MetricsEventBus.post(subscribeEvent, () -> { + MetaDataSubscribeEvent subscribeEvent = new MetaDataSubscribeEvent(applicationModel); + DubboEventBus.post(subscribeEvent, () -> { List metricSamples = collector.collect(); // push success +1 @@ -171,9 +177,9 @@ void testSubscribeMetrics() { // App(6) + rt(5) = 7 Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size()); - subscribeEvent = MetadataEvent.toSubscribeEvent(applicationModel); + subscribeEvent = new MetaDataSubscribeEvent(applicationModel); TimePair lastTimePair = subscribeEvent.getTimePair(); - MetricsEventBus.post( + DubboEventBus.post( subscribeEvent, () -> { try { @@ -223,8 +229,8 @@ void testStoreProviderMetadataMetrics() { // MetadataMetricsCollector collector = getCollector(); String serviceKey = "store.provider.test"; - MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, serviceKey); - MetricsEventBus.post(metadataEvent, () -> { + MetaDataServiceSubscribeEvent metadataEvent = new MetaDataServiceSubscribeEvent(applicationModel, serviceKey); + DubboEventBus.post(metadataEvent, () -> { List metricSamples = collector.collect(); // App(6) + service success(1) @@ -242,9 +248,9 @@ void testStoreProviderMetadataMetrics() { Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 2 + 5, metricSamples.size()); long c1 = metadataEvent.getTimePair().calc(); - metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, serviceKey); + metadataEvent = new MetaDataServiceSubscribeEvent(applicationModel, serviceKey); TimePair lastTimePair = metadataEvent.getTimePair(); - MetricsEventBus.post( + DubboEventBus.post( metadataEvent, () -> { try { @@ -299,11 +305,11 @@ void testStoreProviderMetadataMetrics() { void testMetadataPushNum() { for (int i = 0; i < 10; i++) { - MetadataEvent event = MetadataEvent.toPushEvent(applicationModel); + MetaDataPushEvent event = new MetaDataPushEvent(applicationModel); if (i % 2 == 0) { - MetricsEventBus.post(event, () -> true, r -> r); + DubboEventBus.post(event, () -> true, r -> r); } else { - MetricsEventBus.post(event, () -> false, r -> r); + DubboEventBus.post(event, () -> false, r -> r); } } @@ -322,11 +328,11 @@ void testMetadataPushNum() { void testSubscribeSum() { for (int i = 0; i < 10; i++) { - MetadataEvent event = MetadataEvent.toSubscribeEvent(applicationModel); + MetaDataSubscribeEvent event = new MetaDataSubscribeEvent(applicationModel); if (i % 2 == 0) { - MetricsEventBus.post(event, () -> true, r -> r); + DubboEventBus.post(event, () -> true, r -> r); } else { - MetricsEventBus.post(event, () -> false, r -> r); + DubboEventBus.post(event, () -> false, r -> r); } } diff --git a/dubbo-metrics/dubbo-metrics-netty/pom.xml b/dubbo-metrics/dubbo-metrics-netty/pom.xml index e3d1c50f97a..f66c44d15df 100644 --- a/dubbo-metrics/dubbo-metrics-netty/pom.xml +++ b/dubbo-metrics/dubbo-metrics-netty/pom.xml @@ -36,5 +36,10 @@ dubbo-metrics-api ${project.parent.version} + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.parent.version} + diff --git a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java index 0a30e63fe42..7e18c5f4d5e 100644 --- a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.metrics.registry.collector; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.collector.CombMetricsCollector; @@ -27,7 +28,6 @@ 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; @@ -39,7 +39,7 @@ * Netty implementation of {@link MetricsCollector} */ @Activate -public class NettyMetricsCollector extends CombMetricsCollector { +public class NettyMetricsCollector extends CombMetricsCollector { private Boolean collectEnabled = null; private final ApplicationModel applicationModel; @@ -62,8 +62,8 @@ protected void init(RtStatComposite rtStatComposite) { super.init(rtStatComposite); } }); - super.setEventMulticaster(new NettySubDispatcher(this)); this.applicationModel = applicationModel; + DubboEventBus.addListener(applicationModel, new NettySubDispatcher(this)); } public void setCollectEnabled(Boolean collectEnabled) { diff --git a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.java b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.java deleted file mode 100644 index 9af8812b82a..00000000000 --- a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.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); - } - }; - } -} diff --git a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyMetricsEvent.java b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyMetricsEvent.java new file mode 100644 index 00000000000..0d96030b200 --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyMetricsEvent.java @@ -0,0 +1,68 @@ +/* + * 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.common.utils.TimePair; +import org.apache.dubbo.metrics.event.TimeCounterEvent; +import org.apache.dubbo.metrics.model.key.MetricsKey; +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.remoting.transport.netty4.NettyEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.HashMap; +import java.util.Map; + +import static org.apache.dubbo.metrics.MetricsConstants.NETTY_METRICS_MAP; + +/** + * Netty related events + */ +public class NettyMetricsEvent extends TimeCounterEvent { + public NettyMetricsEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { + super(applicationModel, typeWrapper, TimePair.start()); + ScopeBeanFactory beanFactory = getSource().getBeanFactory(); + NettyMetricsCollector collector; + if (!beanFactory.isDestroyed()) { + collector = beanFactory.getBean(NettyMetricsCollector.class); + super.setAvailable(collector != null && collector.isCollectEnabled()); + } + } + + public static NettyMetricsEvent toNettyEvent(NettyEvent event) { + ApplicationModel applicationModel = event.getApplicationModel(); + NettyEvent.MetricsData postResult = event.getPostResult(); + + NettyMetricsEvent nettyMetricsEvent = + new NettyMetricsEvent(applicationModel, new TypeWrapper(MetricsLevel.APP, null, null, null)); + + Map dataMap = new HashMap<>(); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_HEAP_MEMORY_USED.getName(), postResult.usedHeapMemory); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_DIRECT_MEMORY_USED.getName(), postResult.usedDirectMemory); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_HEAP_ARENAS_NUM.getName(), postResult.numHeapArenas); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_DIRECT_ARENAS_NUM.getName(), postResult.numDirectArenas); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_NORMAL_CACHE_SIZE.getName(), postResult.normalCacheSize); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_SMALL_CACHE_SIZE.getName(), postResult.smallCacheSize); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM.getName(), postResult.numThreadLocalCaches); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_CHUNK_SIZE.getName(), postResult.chunkSize); + nettyMetricsEvent.putAttachment(NETTY_METRICS_MAP, dataMap); + + return nettyMetricsEvent; + } +} diff --git a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java index 5dfacadf299..90c08ab29ac 100644 --- a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java @@ -16,24 +16,28 @@ */ 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.common.event.AbstractDubboLifecycleListener; import org.apache.dubbo.metrics.event.TimeCounterEvent; +import org.apache.dubbo.metrics.event.TimeCounterEventMulticaster; import org.apache.dubbo.metrics.listener.AbstractMetricsKeyListener; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.registry.collector.NettyMetricsCollector; +import org.apache.dubbo.remoting.transport.netty4.NettyEvent; 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 final class NettySubDispatcher extends AbstractDubboLifecycleListener { + + private final TimeCounterEventMulticaster multicaster; public NettySubDispatcher(NettyMetricsCollector collector) { - super.addListener(new AbstractMetricsKeyListener(null) { + this.multicaster = new TimeCounterEventMulticaster(); + this.multicaster.addListener(new AbstractMetricsKeyListener(null) { @Override - public boolean isSupport(MetricsEvent event) { + public boolean support(TimeCounterEvent event) { return true; } @@ -47,4 +51,22 @@ public void onEventFinish(TimeCounterEvent event) { } }); } + + @Override + public void onEventBefore(NettyEvent event) { + NettyMetricsEvent nettyMetricsEvent = NettyMetricsEvent.toNettyEvent(event); + multicaster.publishEvent(nettyMetricsEvent); + } + + @Override + public void onEventFinish(NettyEvent event) { + NettyMetricsEvent nettyMetricsEvent = NettyMetricsEvent.toNettyEvent(event); + multicaster.publishFinishEvent(nettyMetricsEvent); + } + + @Override + public void onEventError(NettyEvent event) { + NettyMetricsEvent nettyMetricsEvent = NettyMetricsEvent.toNettyEvent(event); + multicaster.publishErrorEvent(nettyMetricsEvent); + } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployerTest.java b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/MetricsSupportPrometheusTest.java similarity index 92% rename from dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployerTest.java rename to dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/MetricsSupportPrometheusTest.java index a4ac9c59d82..dbadebfcc94 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployerTest.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/MetricsSupportPrometheusTest.java @@ -14,14 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.config.deploy; +package org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.metrics.utils.MetricsSupportUtil; import org.junit.jupiter.api.Test; -class DefaultApplicationDeployerTest { +public class MetricsSupportPrometheusTest { @Test void isSupportPrometheus() { diff --git a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java index e8198a3d05f..746bd472abd 100644 --- a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java @@ -59,7 +59,8 @@ public void setup() { applicationModel = ApplicationModel.defaultModel(); metricsConfig.setProtocol(PROTOCOL_PROMETHEUS); frameworkModel = FrameworkModel.defaultModel(); - frameworkModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); + DefaultMetricsCollector defaultMetricsCollector = new DefaultMetricsCollector(applicationModel); + frameworkModel.getBeanFactory().registerBean(defaultMetricsCollector); } @AfterEach diff --git a/dubbo-metrics/dubbo-metrics-registry/pom.xml b/dubbo-metrics/dubbo-metrics-registry/pom.xml index b1287adfee5..2de15833695 100644 --- a/dubbo-metrics/dubbo-metrics-registry/pom.xml +++ b/dubbo-metrics/dubbo-metrics-registry/pom.xml @@ -36,6 +36,11 @@ dubbo-metrics-api ${project.parent.version} + + org.apache.dubbo + dubbo-registry-api + ${project.parent.version} + org.apache.logging.log4j log4j-slf4j-impl diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java index c10bca41ddd..91561f7cc54 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java @@ -17,6 +17,7 @@ package org.apache.dubbo.metrics.registry.collector; import org.apache.dubbo.common.constants.RegistryConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.collector.CombMetricsCollector; @@ -32,7 +33,6 @@ import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.registry.RegistryMetricsConstants; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.metrics.registry.event.RegistrySubDispatcher; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -52,12 +52,14 @@ * Registry implementation of {@link MetricsCollector} */ @Activate -public class RegistryMetricsCollector extends CombMetricsCollector { +public class RegistryMetricsCollector extends CombMetricsCollector { private Boolean collectEnabled = null; private final ApplicationModel applicationModel; private final RegistryStatComposite internalStat; + public final RegistrySubDispatcher dispatcher; + public RegistryMetricsCollector(ApplicationModel applicationModel) { super(new BaseStatComposite(applicationModel) { @Override @@ -83,7 +85,8 @@ protected void init(RtStatComposite rtStatComposite) { OP_TYPE_SUBSCRIBE_SERVICE); } }); - super.setEventMulticaster(new RegistrySubDispatcher(this)); + dispatcher = new RegistrySubDispatcher(this); + DubboEventBus.addListener(applicationModel, dispatcher); internalStat = new RegistryStatComposite(applicationModel); this.applicationModel = applicationModel; } diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java deleted file mode 100644 index d122ecabc38..00000000000 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.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.MetricsKey; -import org.apache.dubbo.metrics.model.key.MetricsLevel; -import org.apache.dubbo.metrics.model.key.TypeWrapper; -import org.apache.dubbo.metrics.registry.RegistryMetricsConstants; -import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_DIRECTORY_MAP; -import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_LAST_NUM_MAP; -import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE; -import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SIZE; - -/** - * Registry related events - */ -public class RegistryEvent extends TimeCounterEvent { - public RegistryEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { - super(applicationModel, typeWrapper); - ScopeBeanFactory beanFactory = getSource().getBeanFactory(); - RegistryMetricsCollector collector; - if (!beanFactory.isDestroyed()) { - collector = beanFactory.getBean(RegistryMetricsCollector.class); - super.setAvailable(collector != null && collector.isCollectEnabled()); - } - } - - private static final TypeWrapper REGISTER_EVENT = new TypeWrapper( - MetricsLevel.APP, - MetricsKey.REGISTER_METRIC_REQUESTS, - MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED, - MetricsKey.REGISTER_METRIC_REQUESTS_FAILED); - - public static RegistryEvent toRegisterEvent(ApplicationModel applicationModel, List registryClusterNames) { - RegistryEvent registryEvent = new RegistryEvent(applicationModel, REGISTER_EVENT); - registryEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, registryClusterNames); - return registryEvent; - } - - private static final TypeWrapper SUBSCRIBE_EVENT = new TypeWrapper( - MetricsLevel.APP, - MetricsKey.SUBSCRIBE_METRIC_NUM, - MetricsKey.SUBSCRIBE_METRIC_NUM_SUCCEED, - MetricsKey.SUBSCRIBE_METRIC_NUM_FAILED); - - public static RegistryEvent toSubscribeEvent(ApplicationModel applicationModel, String registryClusterName) { - RegistryEvent ddEvent = new RegistryEvent(applicationModel, SUBSCRIBE_EVENT); - ddEvent.putAttachment( - RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, Collections.singletonList(registryClusterName)); - return ddEvent; - } - - private static final TypeWrapper NOTIFY_EVENT = new TypeWrapper( - MetricsLevel.APP, MetricsKey.NOTIFY_METRIC_REQUESTS, MetricsKey.NOTIFY_METRIC_NUM_LAST, (MetricsKey) null); - - public static RegistryEvent toNotifyEvent(ApplicationModel applicationModel) { - return new RegistryEvent(applicationModel, NOTIFY_EVENT) { - @Override - public void customAfterPost(Object postResult) { - super.putAttachment(ATTACHMENT_KEY_LAST_NUM_MAP, postResult); - } - }; - } - - private static final TypeWrapper RS_EVENT = new TypeWrapper( - MetricsLevel.SERVICE, - MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS, - MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, - MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED); - - public static RegistryEvent toRsEvent( - ApplicationModel applicationModel, String serviceKey, int size, List serviceDiscoveryNames) { - RegistryEvent ddEvent = new RegistryEvent(applicationModel, RS_EVENT); - ddEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); - ddEvent.putAttachment(ATTACHMENT_KEY_SIZE, size); - ddEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, serviceDiscoveryNames); - return ddEvent; - } - - private static final TypeWrapper SS_EVENT = new TypeWrapper( - MetricsLevel.SERVICE, - MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM, - MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, - MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_FAILED); - - public static RegistryEvent toSsEvent( - ApplicationModel applicationModel, String serviceKey, List serviceDiscoveryNames) { - RegistryEvent ddEvent = new RegistryEvent(applicationModel, SS_EVENT); - ddEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); - ddEvent.putAttachment(ATTACHMENT_KEY_SIZE, 1); - ddEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, serviceDiscoveryNames); - return ddEvent; - } - - private static final TypeWrapper DIRECTORY_EVENT = - new TypeWrapper(MetricsLevel.APP, MetricsKey.DIRECTORY_METRIC_NUM_VALID, null, null); - - public static RegistryEvent refreshDirectoryEvent( - ApplicationModel applicationModel, - Map> summaryMap, - Map attachments) { - RegistryEvent registryEvent = new RegistryEvent(applicationModel, DIRECTORY_EVENT); - registryEvent.putAttachment(ATTACHMENT_DIRECTORY_MAP, summaryMap); - registryEvent.putAttachments(attachments); - return registryEvent; - } -} diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryMetricsEvent.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryMetricsEvent.java new file mode 100644 index 00000000000..22ed82ecb3c --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryMetricsEvent.java @@ -0,0 +1,198 @@ +/* + * 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.common.event.DubboEvent; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.metrics.event.TimeCounterEvent; +import org.apache.dubbo.metrics.model.key.MetricsKey; +import org.apache.dubbo.metrics.model.key.MetricsLevel; +import org.apache.dubbo.metrics.model.key.TypeWrapper; +import org.apache.dubbo.metrics.registry.RegistryMetricsConstants; +import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; +import org.apache.dubbo.registry.client.event.RegistryNotifyEvent; +import org.apache.dubbo.registry.client.event.RegistryRegisterEvent; +import org.apache.dubbo.registry.client.event.RegistryRsEvent; +import org.apache.dubbo.registry.client.event.RegistrySsEvent; +import org.apache.dubbo.registry.client.event.RegistrySubscribeEvent; +import org.apache.dubbo.rpc.cluster.directory.DirectoryRefreshEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_DIRECTORY_MAP; +import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_LAST_NUM_MAP; +import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE; +import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SIZE; + +/** + * Registry related events + */ +public class RegistryMetricsEvent extends TimeCounterEvent { + public RegistryMetricsEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper, TimePair timePair) { + super(applicationModel, typeWrapper, timePair); + ScopeBeanFactory beanFactory = getSource().getBeanFactory(); + RegistryMetricsCollector collector; + if (!beanFactory.isDestroyed()) { + collector = beanFactory.getBean(RegistryMetricsCollector.class); + super.setAvailable(collector != null && collector.isCollectEnabled()); + } + } + + private static final TypeWrapper REGISTER_EVENT = new TypeWrapper( + MetricsLevel.APP, + MetricsKey.REGISTER_METRIC_REQUESTS, + MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED, + MetricsKey.REGISTER_METRIC_REQUESTS_FAILED); + + public static RegistryMetricsEvent toRegisterEvent( + ApplicationModel applicationModel, List registryClusterNames, TimePair timePair) { + RegistryMetricsEvent registryMetricsEvent = + new RegistryMetricsEvent(applicationModel, REGISTER_EVENT, timePair); + registryMetricsEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, registryClusterNames); + return registryMetricsEvent; + } + + private static final TypeWrapper SUBSCRIBE_EVENT = new TypeWrapper( + MetricsLevel.APP, + MetricsKey.SUBSCRIBE_METRIC_NUM, + MetricsKey.SUBSCRIBE_METRIC_NUM_SUCCEED, + MetricsKey.SUBSCRIBE_METRIC_NUM_FAILED); + + public static RegistryMetricsEvent toSubscribeEvent( + ApplicationModel applicationModel, String registryClusterName, TimePair timePair) { + RegistryMetricsEvent ddEvent = new RegistryMetricsEvent(applicationModel, SUBSCRIBE_EVENT, timePair); + ddEvent.putAttachment( + RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, Collections.singletonList(registryClusterName)); + return ddEvent; + } + + private static final TypeWrapper NOTIFY_EVENT = new TypeWrapper( + MetricsLevel.APP, MetricsKey.NOTIFY_METRIC_REQUESTS, MetricsKey.NOTIFY_METRIC_NUM_LAST, (MetricsKey) null); + + public static RegistryMetricsEvent toNotifyEvent( + ApplicationModel applicationModel, Map postResult, TimePair timePair) { + RegistryMetricsEvent registryMetricsEvent = new RegistryMetricsEvent(applicationModel, NOTIFY_EVENT, timePair); + registryMetricsEvent.putAttachment(ATTACHMENT_KEY_LAST_NUM_MAP, postResult); + return registryMetricsEvent; + } + + private static final TypeWrapper RS_EVENT = new TypeWrapper( + MetricsLevel.SERVICE, + MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS, + MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, + MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED); + + public static RegistryMetricsEvent toRsEvent( + ApplicationModel applicationModel, + String serviceKey, + int size, + List serviceDiscoveryNames, + TimePair timePair) { + RegistryMetricsEvent ddEvent = new RegistryMetricsEvent(applicationModel, RS_EVENT, timePair); + ddEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); + ddEvent.putAttachment(ATTACHMENT_KEY_SIZE, size); + ddEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, serviceDiscoveryNames); + return ddEvent; + } + + private static final TypeWrapper SS_EVENT = new TypeWrapper( + MetricsLevel.SERVICE, + MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM, + MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, + MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_FAILED); + + public static RegistryMetricsEvent toSsEvent( + ApplicationModel applicationModel, + String serviceKey, + List serviceDiscoveryNames, + TimePair timePair) { + RegistryMetricsEvent ddEvent = new RegistryMetricsEvent(applicationModel, SS_EVENT, timePair); + ddEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); + ddEvent.putAttachment(ATTACHMENT_KEY_SIZE, 1); + ddEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, serviceDiscoveryNames); + return ddEvent; + } + + private static final TypeWrapper DIRECTORY_EVENT = + new TypeWrapper(MetricsLevel.APP, MetricsKey.DIRECTORY_METRIC_NUM_VALID, null, null); + + public static RegistryMetricsEvent refreshDirectoryEvent( + ApplicationModel applicationModel, + DirectoryRefreshEvent.Summary summary, + Map attachments, + TimePair timePair) { + Map> summaryMap = new HashMap<>(); + summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_VALID, summary.directoryNumValidMap); + summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_DISABLE, summary.directoryNumDisableMap); + summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_TO_RECONNECT, summary.directoryNumToReConnectMap); + summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_ALL, summary.directoryNumAllMap); + + RegistryMetricsEvent registryMetricsEvent = + new RegistryMetricsEvent(applicationModel, DIRECTORY_EVENT, timePair); + registryMetricsEvent.putAttachment(ATTACHMENT_DIRECTORY_MAP, summaryMap); + registryMetricsEvent.putAttachments(attachments); + return registryMetricsEvent; + } + + public static RegistryMetricsEvent convertEvent(DubboEvent event) { + if (event instanceof RegistryRegisterEvent) { + RegistryRegisterEvent registerEvent = (RegistryRegisterEvent) event; + return RegistryMetricsEvent.toRegisterEvent( + registerEvent.getApplicationModel(), + registerEvent.getRegistryClusterNames(), + registerEvent.getTimePair()); + } else if (event instanceof RegistrySubscribeEvent) { + RegistrySubscribeEvent subscribeEvent = (RegistrySubscribeEvent) event; + return RegistryMetricsEvent.toSubscribeEvent( + subscribeEvent.getApplicationModel(), + subscribeEvent.getRegistryClusterName(), + subscribeEvent.getTimePair()); + } else if (event instanceof RegistryNotifyEvent) { + RegistryNotifyEvent notifyEvent = (RegistryNotifyEvent) event; + return RegistryMetricsEvent.toNotifyEvent( + notifyEvent.getApplicationModel(), notifyEvent.getPostResult(), notifyEvent.getTimePair()); + } else if (event instanceof RegistryRsEvent) { + RegistryRsEvent rsEvent = (RegistryRsEvent) event; + return RegistryMetricsEvent.toRsEvent( + rsEvent.getApplicationModel(), + rsEvent.getServiceKey(), + rsEvent.getSize(), + rsEvent.getRegistryClusterNames(), + rsEvent.getTimePair()); + } else if (event instanceof RegistrySsEvent) { + RegistrySsEvent ssEvent = (RegistrySsEvent) event; + return RegistryMetricsEvent.toSsEvent( + ssEvent.getApplicationModel(), + ssEvent.getServiceKey(), + ssEvent.getRegistryClusterNames(), + ssEvent.getTimePair()); + } else if (event instanceof DirectoryRefreshEvent) { + DirectoryRefreshEvent refreshEvent = (DirectoryRefreshEvent) event; + return RegistryMetricsEvent.refreshDirectoryEvent( + refreshEvent.getApplicationModel(), + refreshEvent.getSummary(), + refreshEvent.getAttachments(), + refreshEvent.getTimePair()); + } + return null; + } +} diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java index a28ec570f18..d45bda3de49 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java @@ -51,12 +51,12 @@ public class RegistrySpecListener { * Perform auto-increment on the monitored key, * Can use a custom listener instead of this generic operation */ - public static AbstractMetricsKeyListener onPost(MetricsKey metricsKey, CombMetricsCollector collector) { + public static AbstractMetricsKeyListener onPost(MetricsKey metricsKey, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onEvent( metricsKey, event -> ((RegistryMetricsCollector) collector).incrMetricsNum(metricsKey, getRgs(event))); } - public static AbstractMetricsKeyListener onFinish(MetricsKey metricsKey, CombMetricsCollector collector) { + public static AbstractMetricsKeyListener onFinish(MetricsKey metricsKey, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onFinish(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrRegisterFinishNum( metricsKey, @@ -65,7 +65,7 @@ public static AbstractMetricsKeyListener onFinish(MetricsKey metricsKey, CombMet event.getTimePair().calc())); } - public static AbstractMetricsKeyListener onError(MetricsKey metricsKey, CombMetricsCollector collector) { + public static AbstractMetricsKeyListener onError(MetricsKey metricsKey, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onError(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrRegisterFinishNum( metricsKey, @@ -75,7 +75,7 @@ public static AbstractMetricsKeyListener onError(MetricsKey metricsKey, CombMetr } public static AbstractMetricsKeyListener onPostOfService( - MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onEvent(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrServiceRegisterNum( new MetricsKeyWrapper(metricsKey, placeType), @@ -85,7 +85,7 @@ public static AbstractMetricsKeyListener onPostOfService( } public static AbstractMetricsKeyListener onFinishOfService( - MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onFinish(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrServiceRegisterFinishNum( new MetricsKeyWrapper(metricsKey, placeType), @@ -96,7 +96,7 @@ public static AbstractMetricsKeyListener onFinishOfService( } public static AbstractMetricsKeyListener onErrorOfService( - MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onError(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrServiceRegisterFinishNum( new MetricsKeyWrapper(metricsKey, placeType), @@ -110,7 +110,7 @@ public static AbstractMetricsKeyListener onErrorOfService( * Every time an event is triggered, multiple serviceKey related to notify are increment */ public static AbstractMetricsKeyListener onFinishOfNotify( - MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onFinish(metricsKey, event -> { collector.addServiceRt( event.appName(), placeType.getType(), event.getTimePair().calc()); @@ -123,8 +123,7 @@ public static AbstractMetricsKeyListener onFinishOfNotify( /** * Every time an event is triggered, multiple fixed key related to directory are increment, which has nothing to do with the monitored key */ - public static AbstractMetricsKeyListener onPostOfDirectory( - MetricsKey metricsKey, CombMetricsCollector collector) { + public static AbstractMetricsKeyListener onPostOfDirectory(MetricsKey metricsKey, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onEvent(metricsKey, event -> { Map> summaryMap = event.getAttachmentValue(ATTACHMENT_DIRECTORY_MAP); Map otherAttachments = new HashMap<>(); diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java index 458ed9d7afc..00ed7e0567c 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java @@ -16,15 +16,23 @@ */ package org.apache.dubbo.metrics.registry.event; -import org.apache.dubbo.metrics.event.SimpleMetricsEventMulticaster; +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.common.event.DubboLifecycleListener; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.metrics.event.TimeCounterEventMulticaster; import org.apache.dubbo.metrics.listener.MetricsApplicationListener; import org.apache.dubbo.metrics.model.key.CategoryOverall; import org.apache.dubbo.metrics.model.key.MetricsCat; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; +import org.apache.dubbo.registry.client.event.RegistryEvent; +import org.apache.dubbo.rpc.cluster.directory.DirectoryRefreshEvent; import java.util.Arrays; import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_DIRECTORY; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_NOTIFY; @@ -33,21 +41,70 @@ import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE_SERVICE; -public final class RegistrySubDispatcher extends SimpleMetricsEventMulticaster { +public final class RegistrySubDispatcher implements DubboLifecycleListener { - public RegistrySubDispatcher(RegistryMetricsCollector collector) { + ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RegistrySubDispatcher.class); + + private final RegistryMetricsCollector collector; + + private final TimeCounterEventMulticaster multicaster; + + private final Map, Boolean> eventMatchCache = new ConcurrentHashMap<>(); + public RegistrySubDispatcher(RegistryMetricsCollector collector) { + this.multicaster = new TimeCounterEventMulticaster(); + this.collector = collector; CategorySet.ALL.forEach(categorySet -> { - super.addListener(categorySet.getPost().getEventFunc().apply(collector)); + this.multicaster.addListener(categorySet.getPost().getEventFunc().apply(collector)); if (categorySet.getFinish() != null) { - super.addListener(categorySet.getFinish().getEventFunc().apply(collector)); + this.multicaster.addListener( + categorySet.getFinish().getEventFunc().apply(collector)); } if (categorySet.getError() != null) { - super.addListener(categorySet.getError().getEventFunc().apply(collector)); + this.multicaster.addListener( + categorySet.getError().getEventFunc().apply(collector)); } }); } + @Override + public boolean support(Class eventClass) { + return eventMatchCache.computeIfAbsent( + eventClass, + clazz -> RegistryEvent.class.isAssignableFrom(eventClass) + || DirectoryRefreshEvent.class.isAssignableFrom(eventClass)); + } + + @Override + public void onEventBefore(DubboEvent event) { + RegistryMetricsEvent metricsEvent = RegistryMetricsEvent.convertEvent(event); + if (metricsEvent == null) { + logger.debug("Unsupported event type: {}", event.getClass().getName()); + return; + } + this.multicaster.publishEvent(metricsEvent); + } + + @Override + public void onEventFinish(DubboEvent event) { + RegistryMetricsEvent metricsEvent = RegistryMetricsEvent.convertEvent(event); + if (metricsEvent == null) { + logger.debug("Unsupported event type: {}", event.getClass().getName()); + return; + } + this.multicaster.publishFinishEvent(metricsEvent); + } + + @Override + public void onEventError(DubboEvent event) { + RegistryMetricsEvent metricsEvent = RegistryMetricsEvent.convertEvent(event); + if (metricsEvent == null) { + logger.debug("Unsupported event type: {}", event.getClass().getName()); + return; + } + this.multicaster.publishErrorEvent(metricsEvent); + } + /** * A closer aggregation of MetricsCat, a summary collection of certain types of events */ diff --git a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java index 442b9a7142c..a7ddee01960 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java @@ -16,17 +16,19 @@ */ package org.apache.dubbo.metrics.registry.metrics.collector; +import org.apache.dubbo.common.event.DubboEventBus; +import org.apache.dubbo.common.utils.TimePair; import org.apache.dubbo.config.ApplicationConfig; -import org.apache.dubbo.metrics.event.MetricsDispatcher; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.model.TimePair; 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 org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.registry.RegistryMetricsConstants; import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; +import org.apache.dubbo.registry.client.event.RegistryNotifyEvent; +import org.apache.dubbo.registry.client.event.RegistryRegisterEvent; +import org.apache.dubbo.registry.client.event.RegistryRsEvent; +import org.apache.dubbo.registry.client.event.RegistrySsEvent; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -63,7 +65,6 @@ public void setup() { config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); - applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); collector = applicationModel.getBeanFactory().getOrRegisterBean(RegistryMetricsCollector.class); collector.setCollectEnabled(true); } @@ -76,8 +77,8 @@ public void teardown() { @Test void testRegisterMetrics() { - RegistryEvent registryEvent = RegistryEvent.toRegisterEvent(applicationModel, Lists.newArrayList("reg1")); - MetricsEventBus.post(registryEvent, () -> { + RegistryRegisterEvent registryEvent = new RegistryRegisterEvent(applicationModel, Lists.newArrayList("reg1")); + DubboEventBus.post(registryEvent, () -> { List metricSamples = collector.collect(); // push success +1 -> other default 0 = APP_LEVEL_KEYS.size() Assertions.assertEquals(APP_LEVEL_KEYS.size() + REGISTER_LEVEL_KEYS.size(), metricSamples.size()); @@ -94,9 +95,9 @@ void testRegisterMetrics() { Assertions.assertEquals(APP_LEVEL_KEYS.size() + REGISTER_LEVEL_KEYS.size() + 5, metricSamples.size()); long c1 = registryEvent.getTimePair().calc(); - registryEvent = RegistryEvent.toRegisterEvent(applicationModel, Lists.newArrayList("reg1")); + registryEvent = new RegistryRegisterEvent(applicationModel, Lists.newArrayList("reg1")); TimePair lastTimePair = registryEvent.getTimePair(); - MetricsEventBus.post( + DubboEventBus.post( registryEvent, () -> { try { @@ -147,8 +148,8 @@ void testServicePushMetrics() { String serviceName = "demo.gameService"; List rcNames = Lists.newArrayList("demo1"); - RegistryEvent registryEvent = RegistryEvent.toRsEvent(applicationModel, serviceName, 2, rcNames); - MetricsEventBus.post(registryEvent, () -> { + RegistryRsEvent registryEvent = new RegistryRsEvent(applicationModel, serviceName, 2, rcNames); + DubboEventBus.post(registryEvent, () -> { List metricSamples = collector.collect(); // push success +1 @@ -169,9 +170,9 @@ void testServicePushMetrics() { Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 5 + 2, metricSamples.size()); long c1 = registryEvent.getTimePair().calc(); - registryEvent = RegistryEvent.toRsEvent(applicationModel, serviceName, 2, rcNames); + registryEvent = new RegistryRsEvent(applicationModel, serviceName, 2, rcNames); TimePair lastTimePair = registryEvent.getTimePair(); - MetricsEventBus.post( + DubboEventBus.post( registryEvent, () -> { try { @@ -222,9 +223,9 @@ void testServiceSubscribeMetrics() { String serviceName = "demo.gameService"; - RegistryEvent subscribeEvent = - RegistryEvent.toSsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); - MetricsEventBus.post(subscribeEvent, () -> { + RegistrySsEvent subscribeEvent = + new RegistrySsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); + DubboEventBus.post(subscribeEvent, () -> { List metricSamples = collector.collect(); Assertions.assertTrue( metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); @@ -248,9 +249,9 @@ void testServiceSubscribeMetrics() { Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 5 + 2, metricSamples.size()); long c1 = subscribeEvent.getTimePair().calc(); - subscribeEvent = RegistryEvent.toSsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); + subscribeEvent = new RegistrySsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); TimePair lastTimePair = subscribeEvent.getTimePair(); - MetricsEventBus.post( + DubboEventBus.post( subscribeEvent, () -> { try { @@ -299,7 +300,7 @@ void testServiceSubscribeMetrics() { @Test public void testNotify() { Map lastNumMap = new HashMap<>(); - MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), () -> { + DubboEventBus.post(new RegistryNotifyEvent(applicationModel), () -> { try { Thread.sleep(50L); } catch (InterruptedException e) { diff --git a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java index db06191028c..fc2dbe1b23b 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.metrics.registry.metrics.collector; +import org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -24,7 +25,10 @@ import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; +import org.apache.dubbo.registry.client.event.RegistryEvent; +import org.apache.dubbo.registry.client.event.RegistryRegisterEvent; +import org.apache.dubbo.registry.client.event.RegistryRsEvent; +import org.apache.dubbo.registry.client.event.RegistrySubscribeEvent; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -38,6 +42,7 @@ import java.util.concurrent.TimeUnit; import com.google.common.collect.Lists; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -53,13 +58,21 @@ public class RegistryMetricsTest { String REGISTER = "register"; + DubboApplicationMulticasterRegistry registry = new DubboApplicationMulticasterRegistry(); + @BeforeEach void setUp() { this.applicationModel = getApplicationModel(); + registry.initializeApplicationModel(applicationModel); this.collector = getTestCollector(this.applicationModel); this.collector.setCollectEnabled(true); } + @AfterEach + void tearDown() { + registry.onDestroy(applicationModel); + } + @Test void testRegisterRequestsCount() { @@ -263,19 +276,19 @@ GaugeMetricSample getSample(String name, List samples) { RegistryEvent applicationRegister() { RegistryEvent event = registerEvent(); - collector.onEvent(event); + collector.dispatcher.onEventBefore(event); return event; } RegistryEvent serviceRegister() { RegistryEvent event = rsEvent(); - collector.onEvent(event); + collector.dispatcher.onEventBefore(event); return event; } RegistryEvent serviceSubscribe() { RegistryEvent event = subscribeEvent(); - collector.onEvent(event); + collector.dispatcher.onEventBefore(event); return event; } @@ -284,30 +297,24 @@ boolean considerEquals(double expected, double trueValue, double allowedErrorRat } void eventSuccess(RegistryEvent event) { - collector.onEventFinish(event); + collector.dispatcher.onEventFinish(event); } void eventFailed(RegistryEvent event) { - collector.onEventError(event); + collector.dispatcher.onEventError(event); } RegistryEvent registerEvent() { - RegistryEvent event = RegistryEvent.toRegisterEvent(applicationModel, Lists.newArrayList("reg1")); - event.setAvailable(true); - return event; + return new RegistryRegisterEvent(applicationModel, Lists.newArrayList("reg1")); } RegistryEvent rsEvent() { List rcNames = Lists.newArrayList("demo1"); - RegistryEvent event = RegistryEvent.toRsEvent(applicationModel, "TestServiceInterface1", 1, rcNames); - event.setAvailable(true); - return event; + return new RegistryRsEvent(applicationModel, "TestServiceInterface1", 1, rcNames); } - RegistryEvent subscribeEvent() { - RegistryEvent event = RegistryEvent.toSubscribeEvent(applicationModel, "registryClusterName_test"); - event.setAvailable(true); - return event; + RegistrySubscribeEvent subscribeEvent() { + return new RegistrySubscribeEvent(applicationModel, "registryClusterName_test"); } ApplicationModel getApplicationModel() { diff --git a/dubbo-metrics/dubbo-metrics-starter/pom.xml b/dubbo-metrics/dubbo-metrics-starter/pom.xml new file mode 100644 index 00000000000..cebb1fdcf44 --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-starter/pom.xml @@ -0,0 +1,62 @@ + + + + 4.0.0 + + org.apache.dubbo + dubbo-metrics + ${revision} + ../pom.xml + + dubbo-metrics-starter + jar + ${project.artifactId} + The metrics module of dubbo project + + false + + + + org.apache.dubbo + dubbo-metrics-default + ${project.parent.version} + + + org.apache.dubbo + dubbo-tracing + ${project.parent.version} + + + + org.apache.dubbo + dubbo-native + ${project.parent.version} + + + + io.micrometer + micrometer-test + test + + + org.apache.logging.log4j + log4j-slf4j-impl + test + + + diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java b/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java similarity index 62% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java rename to dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java index 1a976cf8753..d977ee102c2 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java @@ -14,22 +14,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.event; +package org.apache.dubbo.metrics; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.event.DubboEventBus; +import org.apache.dubbo.common.event.DubboListener; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.model.FrameworkModel; +import org.apache.dubbo.rpc.model.ModuleModel; +import org.apache.dubbo.rpc.model.ScopeModelInitializer; import java.util.List; -/** - * Global spi event publisher - */ -public class MetricsDispatcher extends SimpleMetricsEventMulticaster { +public class MetricsScopeModelInitializer implements ScopeModelInitializer { + + @Override + public void initializeFrameworkModel(FrameworkModel frameworkModel) {} - @SuppressWarnings({"rawtypes"}) - public MetricsDispatcher(ApplicationModel applicationModel) { + @Override + public void initializeApplicationModel(ApplicationModel applicationModel) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); ExtensionLoader extensionLoader = applicationModel.getExtensionLoader(MetricsCollector.class); if (extensionLoader != null) { @@ -37,7 +42,13 @@ public MetricsDispatcher(ApplicationModel applicationModel) { for (MetricsCollector customizeCollector : customizeCollectors) { beanFactory.registerBean(customizeCollector); } - customizeCollectors.forEach(this::addListener); + } + MetricsServiceInitializer metricsServiceInitializer = new MetricsServiceInitializer(applicationModel); + for (DubboListener dubboListener : metricsServiceInitializer.getDubboListeners()) { + DubboEventBus.addListener(applicationModel, dubboListener); } } + + @Override + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java b/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java new file mode 100644 index 00000000000..67f0baf07cd --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java @@ -0,0 +1,173 @@ +/* + * 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.event.AbstractDubboListener; +import org.apache.dubbo.common.event.DubboListener; +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.config.MetricsConfig; +import org.apache.dubbo.config.TracingConfig; +import org.apache.dubbo.config.deploy.event.ApplicationLoadedEvent; +import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; +import org.apache.dubbo.metrics.report.DefaultMetricsReporterFactory; +import org.apache.dubbo.metrics.report.MetricsReporter; +import org.apache.dubbo.metrics.report.MetricsReporterFactory; +import org.apache.dubbo.metrics.service.MetricsServiceExporter; +import org.apache.dubbo.metrics.utils.MetricsSupportUtil; +import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.tracing.DubboObservationRegistry; +import org.apache.dubbo.tracing.utils.ObservationSupportUtil; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION; +import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_DEFAULT; +import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; + +/** + * Initialize the metrics service. + */ +public class MetricsServiceInitializer { + + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(MetricsServiceInitializer.class); + + private final ApplicationModel applicationModel; + + private final MetricsServiceExporter metricsServiceExporter; + + private final DefaultMetricsCollector defaultCollector; + + private final List> dubboListeners; + + public MetricsServiceInitializer(ApplicationModel applicationModel) { + this.applicationModel = applicationModel; + this.defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); + this.metricsServiceExporter = applicationModel + .getExtensionLoader(MetricsServiceExporter.class) + .getDefaultExtension(); + dubboListeners = Arrays.asList(new AbstractDubboListener() { + @Override + public void onEvent(ApplicationLoadedEvent event) { + + if (MetricsSupportUtil.isSupportMetrics()) { + + MetricsConfig metricsConfig = initMetricsConfig(); + + initDefaultMetricsCollector(metricsConfig); + + initMetricsReporter(metricsConfig); + } + + initMetricsService(); + + // @since 3.2.3 + initObservationRegistry(); + } + }); + } + + public List> getDubboListeners() { + return dubboListeners; + } + + private void initMetricsService() { + this.applicationModel.getBeanFactory().registerBean(this.metricsServiceExporter); + this.metricsServiceExporter.init(); + } + + private MetricsConfig initMetricsConfig() { + Optional configOptional = + applicationModel.getApplicationConfigManager().getMetrics(); + // If no specific metrics type is configured and there is no Prometheus dependency in the dependencies. + MetricsConfig metricsConfig = configOptional.orElse(new MetricsConfig(applicationModel)); + if (StringUtils.isBlank(metricsConfig.getProtocol())) { + metricsConfig.setProtocol( + MetricsSupportUtil.isSupportPrometheus() ? PROTOCOL_PROMETHEUS : PROTOCOL_DEFAULT); + } + return metricsConfig; + } + + private void initDefaultMetricsCollector(MetricsConfig metricsConfig) { + defaultCollector.setCollectEnabled(true); + defaultCollector.collectApplication(); + defaultCollector.setThreadpoolCollectEnabled( + Optional.ofNullable(metricsConfig.getEnableThreadpool()).orElse(true)); + defaultCollector.setMetricsInitEnabled( + Optional.ofNullable(metricsConfig.getEnableMetricsInit()).orElse(true)); + } + + private void initMetricsReporter(MetricsConfig metricsConfig) { + MetricsReporterFactory metricsReporterFactory = applicationModel + .getExtensionLoader(MetricsReporterFactory.class) + .getAdaptiveExtension(); + MetricsReporter metricsReporter = null; + try { + metricsReporter = metricsReporterFactory.createMetricsReporter(metricsConfig.toUrl()); + } catch (IllegalStateException e) { + if (e.getMessage().startsWith("No such extension org.apache.dubbo.metrics.report.MetricsReporterFactory")) { + logger.warn(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", e.getMessage()); + return; + } else { + throw e; + } + } + metricsReporter.init(); + applicationModel.getBeanFactory().registerBean(metricsReporter); + // If the protocol is not the default protocol, the default protocol is also initialized. + if (!PROTOCOL_DEFAULT.equals(metricsConfig.getProtocol())) { + DefaultMetricsReporterFactory defaultMetricsReporterFactory = + new DefaultMetricsReporterFactory(applicationModel); + MetricsReporter defaultMetricsReporter = + defaultMetricsReporterFactory.createMetricsReporter(metricsConfig.toUrl()); + defaultMetricsReporter.init(); + applicationModel.getBeanFactory().registerBean(defaultMetricsReporter); + } + } + + /** + * init ObservationRegistry(Micrometer) + */ + private void initObservationRegistry() { + if (!ObservationSupportUtil.isSupportObservation()) { + if (logger.isDebugEnabled()) { + logger.debug( + "Not found micrometer-observation or plz check the version of micrometer-observation version if already introduced, need > 1.10.0"); + } + return; + } + if (!ObservationSupportUtil.isSupportTracing()) { + if (logger.isDebugEnabled()) { + logger.debug("Not found micrometer-tracing dependency, skip init ObservationRegistry."); + } + return; + } + Optional configOptional = + applicationModel.getApplicationConfigManager().getTracing(); + if (!configOptional.isPresent() || !configOptional.get().getEnabled()) { + return; + } + + DubboObservationRegistry dubboObservationRegistry = + new DubboObservationRegistry(applicationModel, configOptional.get()); + dubboObservationRegistry.initObservationRegistry(); + } +} diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer b/dubbo-metrics/dubbo-metrics-starter/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer similarity index 100% rename from dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer rename to dubbo-metrics/dubbo-metrics-starter/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer diff --git a/dubbo-metrics/dubbo-metrics-starter/src/test/java/org/apache/dubbo/metrics/collector/CollectorInitTest.java b/dubbo-metrics/dubbo-metrics-starter/src/test/java/org/apache/dubbo/metrics/collector/CollectorInitTest.java new file mode 100644 index 00000000000..9bc416dd6be --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-starter/src/test/java/org/apache/dubbo/metrics/collector/CollectorInitTest.java @@ -0,0 +1,48 @@ +/* + * 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.config.ApplicationConfig; +import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.model.FrameworkModel; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +public class CollectorInitTest { + + private ApplicationModel applicationModel; + + DefaultMetricsCollector defaultCollector; + + @BeforeEach + public void setUp() { + FrameworkModel frameworkModel = FrameworkModel.defaultModel(); + applicationModel = frameworkModel.newApplication(); + ApplicationConfig config = new ApplicationConfig(); + config.setName("MockMetrics"); + + applicationModel.getApplicationConfigManager().setApplication(config); + defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); + defaultCollector.setCollectEnabled(true); + } + + @AfterEach + public void teardown() { + applicationModel.destroy(); + } +} diff --git a/dubbo-metrics/dubbo-tracing/pom.xml b/dubbo-metrics/dubbo-tracing/pom.xml index 2979b08cd92..917881a98a3 100644 --- a/dubbo-metrics/dubbo-tracing/pom.xml +++ b/dubbo-metrics/dubbo-tracing/pom.xml @@ -51,7 +51,7 @@ org.apache.dubbo - dubbo-metrics-default + dubbo-metrics-api ${project.parent.version} diff --git a/dubbo-metrics/pom.xml b/dubbo-metrics/pom.xml index 2c2692f3f94..d67b8135098 100644 --- a/dubbo-metrics/pom.xml +++ b/dubbo-metrics/pom.xml @@ -28,9 +28,10 @@ ${project.artifactId} The metrics module of dubbo project + dubbo-metrics-annotation dubbo-metrics-api - dubbo-metrics-event dubbo-metrics-default + dubbo-metrics-starter dubbo-metrics-registry dubbo-metrics-metadata dubbo-metrics-prometheus diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 3d407872364..7338687ecec 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -65,31 +65,6 @@ zookeeper test - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-metadata - ${project.parent.version} - compile - - - - org.apache.dubbo - dubbo-metrics-registry - ${project.parent.version} - compile - org.apache.dubbo diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java index 48775813211..795e7bc3c62 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java @@ -17,17 +17,18 @@ package org.apache.dubbo.registry.client; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metadata.MetadataInfo; +import org.apache.dubbo.metadata.event.MetaDataPushEvent; +import org.apache.dubbo.metadata.event.MetaDataSubscribeEvent; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.metadata.report.MetadataReportInstance; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.metadata.event.MetadataEvent; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.registry.client.metadata.MetadataUtils; @@ -244,8 +245,8 @@ public MetadataInfo getRemoteMetadata(String revision, List ins int triedTimes = 0; while (triedTimes < 3) { - metadata = MetricsEventBus.post( - MetadataEvent.toSubscribeEvent(applicationModel), + metadata = DubboEventBus.post( + new MetaDataSubscribeEvent(applicationModel), () -> MetadataUtils.getRemoteMetadata(revision, instances, metadataReport), result -> result != MetadataInfo.EMPTY); @@ -383,7 +384,7 @@ protected void reportMetadata(MetadataInfo metadataInfo) { new SubscriberMetadataIdentifier(serviceName, metadataInfo.getRevision()); if ((DEFAULT_METADATA_STORAGE_TYPE.equals(metadataType) && metadataReport.shouldReportMetadata()) || REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) { - MetricsEventBus.post(MetadataEvent.toPushEvent(applicationModel), () -> { + DubboEventBus.post(new MetaDataPushEvent(applicationModel), () -> { metadataReport.publishAppMetadata(identifier, metadataInfo); return null; }); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java index b86afee87d4..9188bec4254 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RegistryConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; @@ -27,9 +28,8 @@ import org.apache.dubbo.metadata.MappingChangedEvent; import org.apache.dubbo.metadata.MappingListener; import org.apache.dubbo.metadata.ServiceNameMapping; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.registry.NotifyListener; +import org.apache.dubbo.registry.client.event.RegistrySsEvent; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.registry.support.FailbackRegistry; @@ -366,8 +366,8 @@ protected void subscribeURLs(URL url, NotifyListener listener, Set servi String serviceDiscoveryName = url.getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, url.getProtocol()); - MetricsEventBus.post( - RegistryEvent.toSsEvent( + DubboEventBus.post( + new RegistrySsEvent( url.getApplicationModel(), serviceKey, Collections.singletonList(serviceDiscoveryName)), () -> { serviceDiscovery.addServiceInstancesChangedListener(finalServiceInstancesChangedListener); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryEvent.java new file mode 100644 index 00000000000..e9b6b2a2d93 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryEvent.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.client.event; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class RegistryEvent extends DubboEvent { + + private final TimePair timePair; + + public RegistryEvent(ApplicationModel applicationModel) { + super(applicationModel); + this.timePair = TimePair.start(); + } + + public TimePair getTimePair() { + return timePair; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryNotifyEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryNotifyEvent.java new file mode 100644 index 00000000000..1816f7c566c --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryNotifyEvent.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.client.event; + +import org.apache.dubbo.common.event.CustomAfterPost; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.Map; + +public class RegistryNotifyEvent extends RegistryEvent implements CustomAfterPost> { + + private Map postResult; + + public RegistryNotifyEvent(ApplicationModel applicationModel) { + super(applicationModel); + } + + @Override + public void customAfterPost(Map postResult) { + this.postResult = postResult; + } + + public Map getPostResult() { + return postResult; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRegisterEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRegisterEvent.java new file mode 100644 index 00000000000..9273e627c96 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRegisterEvent.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.client.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.List; + +public class RegistryRegisterEvent extends RegistryEvent { + + private final List registryClusterNames; + + public RegistryRegisterEvent(ApplicationModel source, List registryClusterNames) { + super(source); + this.registryClusterNames = registryClusterNames; + } + + public List getRegistryClusterNames() { + return registryClusterNames; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRsEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRsEvent.java new file mode 100644 index 00000000000..d44631ec82d --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRsEvent.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.client.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.List; + +public class RegistryRsEvent extends RegistryEvent { + + private final List registryClusterNames; + + private final String serviceKey; + + private final int size; + + public RegistryRsEvent( + ApplicationModel applicationModel, String serviceKey, int size, List serviceDiscoveryNames) { + super(applicationModel); + this.registryClusterNames = serviceDiscoveryNames; + this.serviceKey = serviceKey; + this.size = size; + } + + public List getRegistryClusterNames() { + return registryClusterNames; + } + + public String getServiceKey() { + return serviceKey; + } + + public int getSize() { + return size; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySsEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySsEvent.java new file mode 100644 index 00000000000..4b61b3c95eb --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySsEvent.java @@ -0,0 +1,49 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.client.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.List; + +public class RegistrySsEvent extends RegistryEvent { + + private final List registryClusterNames; + + private final String serviceKey; + + private final int size; + + public RegistrySsEvent(ApplicationModel applicationModel, String serviceKey, List serviceDiscoveryNames) { + super(applicationModel); + this.registryClusterNames = serviceDiscoveryNames; + this.serviceKey = serviceKey; + this.size = 1; + } + + public List getRegistryClusterNames() { + return registryClusterNames; + } + + public String getServiceKey() { + return serviceKey; + } + + public int getSize() { + return size; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySubscribeEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySubscribeEvent.java new file mode 100644 index 00000000000..b2c07c8ecd8 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySubscribeEvent.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.client.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class RegistrySubscribeEvent extends RegistryEvent { + + private final String registryClusterName; + + public RegistrySubscribeEvent(ApplicationModel source, String registryClusterName) { + super(source); + this.registryClusterName = registryClusterName; + } + + public String getRegistryClusterName() { + return registryClusterName; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java index ba5e7ac8035..fc642d63b72 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; @@ -27,12 +28,11 @@ 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.RegistryNotifyEvent; import org.apache.dubbo.registry.client.event.RetryServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils; @@ -452,7 +452,7 @@ protected List getAddresses(ProtocolServiceKey protocolServiceKey, URL cons */ protected void notifyAddressChanged() { - MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), () -> { + DubboEventBus.post(new RegistryNotifyEvent(applicationModel), () -> { Map lastNumMap = new HashMap<>(); // 1 different services listeners.forEach((serviceKey, listenerSet) -> { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java index bc26aad59f8..1e31549afcc 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RegistryConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -26,13 +27,12 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metadata.MetadataInfo; import org.apache.dubbo.metadata.MetadataService; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.DefaultServiceInstance.Endpoint; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.ServiceInstanceCustomizer; +import org.apache.dubbo.registry.client.event.RegistryRegisterEvent; import org.apache.dubbo.registry.support.RegistryManager; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -211,8 +211,8 @@ public static void registerMetadataAndInstance(ApplicationModel applicationModel LOGGER.info("Start registering instance address to registry."); List serviceDiscoveries = registryManager.getServiceDiscoveries(); for (ServiceDiscovery serviceDiscovery : serviceDiscoveries) { - MetricsEventBus.post( - RegistryEvent.toRegisterEvent( + DubboEventBus.post( + new RegistryRegisterEvent( applicationModel, Collections.singletonList(getServiceDiscoveryName(serviceDiscovery))), () -> { // register service instance diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 11c9c80c100..76eb1ce8aa8 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.RegistryConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -31,10 +32,9 @@ import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.registry.AddressListener; import org.apache.dubbo.registry.Registry; +import org.apache.dubbo.registry.client.event.RegistrySubscribeEvent; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; @@ -145,7 +145,7 @@ public void subscribe(URL url) { .getParameter( RegistryConstants.REGISTRY_CLUSTER_KEY, registry.getUrl().getParameter(PROTOCOL_KEY)); - MetricsEventBus.post(RegistryEvent.toSubscribeEvent(applicationModel, registryClusterName), () -> { + DubboEventBus.post(new RegistrySubscribeEvent(applicationModel, registryClusterName), () -> { super.subscribe(url); return null; }); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index e8a6a680644..6e1d814f22f 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.RegistryConstants; import org.apache.dubbo.common.deploy.ApplicationDeployer; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -31,13 +32,12 @@ import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.RegistryService; import org.apache.dubbo.registry.client.ServiceDiscoveryRegistryDirectory; +import org.apache.dubbo.registry.client.event.RegistryRsEvent; import org.apache.dubbo.registry.client.migration.MigrationClusterInvoker; import org.apache.dubbo.registry.client.migration.ServiceDiscoveryMigrationInvoker; import org.apache.dubbo.registry.retry.ReExportTask; @@ -220,8 +220,8 @@ private static void register(Registry registry, URL registeredProviderUrl) { UrlUtils.isServiceDiscoveryURL(u) ? u.getParameter(REGISTRY_KEY) : u.getProtocol())) .filter(StringUtils::isNotEmpty) .orElse("unknown"); - MetricsEventBus.post( - RegistryEvent.toRsEvent( + DubboEventBus.post( + new RegistryRsEvent( registeredProviderUrl.getApplicationModel(), registeredProviderUrl.getServiceKey(), 1, diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java index f1711eb3b34..6045f5bacd7 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java @@ -25,6 +25,7 @@ import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; +import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.util.ArrayList; import java.util.Collections; @@ -105,6 +106,7 @@ public void init() { doNothing().when(instanceListener).onEvent(any()); when(serviceDiscovery.createListener(any())).thenReturn(instanceListener); when(serviceDiscovery.getInstances(any())).thenReturn(Collections.emptyList()); + url = url.setScopeModel(ScopeModelUtil.getApplicationModel(null)); when(serviceDiscovery.getUrl()).thenReturn(url); ApplicationModel applicationModel = spy(ApplicationModel.defaultModel()); when(applicationModel.getDefaultExtension(ServiceNameMapping.class)).thenReturn(mapping); @@ -225,6 +227,7 @@ void testSubscribeURLs() { // different interface mapping to the same apps NotifyListener testServiceListener2 = mock(NotifyListener.class); URL url2 = URL.valueOf("tri://127.0.0.1/TestService2?interface=TestService2&check=false&protocol=tri"); + url2 = url2.setScopeModel(ScopeModelUtil.getApplicationModel(null)); when(testServiceListener2.getConsumerUrl()).thenReturn(url2); serviceDiscoveryRegistry.subscribeURLs(url2, testServiceListener2, multiApps); // check instance listeners not changed, methods not called @@ -265,6 +268,7 @@ void testUnsubscribe() { multiApps.add(APP_NAME2); NotifyListener testServiceListener2 = mock(NotifyListener.class); URL url2 = URL.valueOf("consumer://127.0.0.1/TestService2?interface=TestService1&check=false&protocol=tri"); + url2 = url2.setScopeModel(ScopeModelUtil.getApplicationModel(null)); when(testServiceListener2.getConsumerUrl()).thenReturn(url2); serviceDiscoveryRegistry.subscribeURLs(url, testServiceListener, multiApps); serviceDiscoveryRegistry.subscribeURLs(url2, testServiceListener2, multiApps); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java index 6a0739b78ca..aaf37f2b997 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; +import java.io.Serializable; import java.security.SecureRandom; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicLong; @@ -29,7 +30,7 @@ /** * Request. */ -public class Request { +public class Request implements Serializable { private static final AtomicLong INVOKE_ID; diff --git a/dubbo-remoting/dubbo-remoting-netty4/pom.xml b/dubbo-remoting/dubbo-remoting-netty4/pom.xml index 06d548d1bdf..eac2bc7510f 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty4/pom.xml @@ -41,16 +41,6 @@ dubbo-remoting-api ${project.parent.version} - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-netty - ${project.parent.version} - io.netty netty-handler-proxy diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEvent.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEvent.java new file mode 100644 index 00000000000..2c6e06e15df --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEvent.java @@ -0,0 +1,58 @@ +/* + * 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.remoting.transport.netty4; + +import org.apache.dubbo.common.event.CustomAfterPost; +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class NettyEvent extends DubboEvent implements CustomAfterPost { + + private MetricsData postResult; + + public NettyEvent(ApplicationModel source) { + super(source); + } + + @Override + public void customAfterPost(MetricsData postResult) { + this.postResult = postResult; + } + + public MetricsData getPostResult() { + return postResult; + } + + public static class MetricsData { + + public Long usedHeapMemory; + + public Long usedDirectMemory; + + public Long numHeapArenas; + + public Long numDirectArenas; + + public Long normalCacheSize; + + public Long smallCacheSize; + + public Long numThreadLocalCaches; + + public Long chunkSize; + } +} diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java index 9f5bd0a075c..46cc3f7fe61 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java @@ -18,14 +18,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.model.key.MetricsKey; -import org.apache.dubbo.metrics.registry.event.NettyEvent; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; @@ -39,7 +37,6 @@ import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; import java.util.Map; import io.netty.bootstrap.ServerBootstrap; @@ -123,27 +120,19 @@ protected void doOpen() throws Throwable { // metrics if (isSupportMetrics()) { ApplicationModel applicationModel = ApplicationModel.defaultModel(); - MetricsEventBus.post(NettyEvent.toNettyEvent(applicationModel), () -> { - Map dataMap = new HashMap<>(); - dataMap.put( - MetricsKey.NETTY_ALLOCATOR_HEAP_MEMORY_USED.getName(), - PooledByteBufAllocator.DEFAULT.metric().usedHeapMemory()); - dataMap.put( - MetricsKey.NETTY_ALLOCATOR_DIRECT_MEMORY_USED.getName(), - PooledByteBufAllocator.DEFAULT.metric().usedDirectMemory()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_HEAP_ARENAS_NUM.getName(), (long) - PooledByteBufAllocator.DEFAULT.numHeapArenas()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_DIRECT_ARENAS_NUM.getName(), (long) - PooledByteBufAllocator.DEFAULT.numDirectArenas()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_NORMAL_CACHE_SIZE.getName(), (long) - PooledByteBufAllocator.DEFAULT.normalCacheSize()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_SMALL_CACHE_SIZE.getName(), (long) - PooledByteBufAllocator.DEFAULT.smallCacheSize()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM.getName(), (long) - PooledByteBufAllocator.DEFAULT.numThreadLocalCaches()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_CHUNK_SIZE.getName(), (long) - PooledByteBufAllocator.DEFAULT.chunkSize()); - return dataMap; + DubboEventBus.post(new NettyEvent(applicationModel), () -> { + NettyEvent.MetricsData metricsData = new NettyEvent.MetricsData(); + metricsData.usedHeapMemory = + PooledByteBufAllocator.DEFAULT.metric().usedHeapMemory(); + metricsData.usedDirectMemory = + PooledByteBufAllocator.DEFAULT.metric().usedDirectMemory(); + metricsData.numHeapArenas = (long) PooledByteBufAllocator.DEFAULT.numHeapArenas(); + metricsData.numDirectArenas = (long) PooledByteBufAllocator.DEFAULT.numDirectArenas(); + metricsData.normalCacheSize = (long) PooledByteBufAllocator.DEFAULT.normalCacheSize(); + metricsData.smallCacheSize = (long) PooledByteBufAllocator.DEFAULT.smallCacheSize(); + metricsData.numThreadLocalCaches = (long) PooledByteBufAllocator.DEFAULT.numThreadLocalCaches(); + metricsData.chunkSize = (long) PooledByteBufAllocator.DEFAULT.chunkSize(); + return metricsData; }); } } diff --git a/dubbo-test/dubbo-dependencies-all/pom.xml b/dubbo-test/dubbo-dependencies-all/pom.xml index b86a36b8901..620d8b6ec16 100644 --- a/dubbo-test/dubbo-dependencies-all/pom.xml +++ b/dubbo-test/dubbo-dependencies-all/pom.xml @@ -158,7 +158,7 @@ org.apache.dubbo - dubbo-metrics-event + dubbo-metrics-annotation ${project.version} @@ -195,6 +195,11 @@ dubbo-metrics-prometheus ${project.version} + + org.apache.dubbo + dubbo-metrics-starter + ${project.version} + org.apache.dubbo dubbo-tracing From c17da8c3cad06098d96c4242833f849c797928a6 Mon Sep 17 00:00:00 2001 From: walklown Date: Sun, 19 May 2024 13:43:38 +0800 Subject: [PATCH 02/12] Adjust code based on Reviews. Change the rest protocol in unit test and demo to triple because dubbo-rpc-rest has been moved from dubbo to dubbo-spi-extensions --- .../configcenter/ConfigCenterChangeEvent.java | 13 +++++-- .../DubboApplicationMulticasterRegistry.java | 29 ++------------ .../dubbo/common/event/DubboEventBus.java | 10 ++++- .../deploy/DefaultApplicationDeployer.java | 6 +-- .../metrics/MockMetricsServiceExporter.java | 38 +++++++++++++++++++ ...mon.metrics.service.MetricsServiceExporter | 1 + .../provider/dubbo-provider.xml | 2 +- .../registryNA/provider/dubbo-provider.xml | 2 +- ...mon.metrics.service.MetricsServiceExporter | 1 - .../apollo/ApolloDynamicConfiguration.java | 2 +- .../nacos/NacosDynamicConfiguration.java | 2 +- .../zookeeper/ZookeeperDataListener.java | 2 +- .../main/resources/spring/rest-provider.xml | 2 +- .../main/resources/spring/dubbo-provider.xml | 4 +- ...{MetaDataEvent.java => MetadataEvent.java} | 4 +- ...aPushEvent.java => MetadataPushEvent.java} | 4 +- ...ava => MetadataServiceSubscribeEvent.java} | 4 +- ...Event.java => MetadataSubscribeEvent.java} | 4 +- .../support/AbstractMetadataReport.java | 6 +-- .../event/ConfigCenterSubDispatcher.java | 6 ++- .../ConfigCenterMetricsCollectorTest.java | 6 +-- .../metrics/DefaultMetricsServiceTest.java | 6 +-- .../AggregateMetricsCollectorTest.java | 5 ++- .../sample/ThreadPoolMetricsSamplerTest.java | 16 +++----- .../metrics/filter/MetricsFilterTest.java | 2 +- .../metadata/event/MetadataMetricsEvent.java | 18 ++++----- .../metadata/event/MetadataSubDispatcher.java | 10 ++--- .../MetadataMetricsCollectorTest.java | 30 +++++++-------- .../collector/RegistryMetricsTest.java | 16 +++----- .../client/AbstractServiceDiscovery.java | 8 ++-- .../dubbo-remoting-zookeeper-curator5/pom.xml | 5 --- dubbo-test/dubbo-test-spring/pom.xml | 5 +++ .../resources/spring/dubbo-demo-provider.xml | 4 +- .../src/main/resources/spring/dubbo-demo.xml | 4 +- 34 files changed, 152 insertions(+), 125 deletions(-) create mode 100644 dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metrics/MockMetricsServiceExporter.java create mode 100644 dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.common.metrics.service.MetricsServiceExporter delete mode 100644 dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.metrics.service.MetricsServiceExporter rename dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/{MetaDataEvent.java => MetadataEvent.java} (91%) rename dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/{MetaDataPushEvent.java => MetadataPushEvent.java} (89%) rename dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/{MetaDataServiceSubscribeEvent.java => MetadataServiceSubscribeEvent.java} (89%) rename dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/{MetaDataSubscribeEvent.java => MetadataSubscribeEvent.java} (88%) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigCenterChangeEvent.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigCenterChangeEvent.java index 0770ef7ccfe..f8c4658b459 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigCenterChangeEvent.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigCenterChangeEvent.java @@ -28,19 +28,24 @@ public class ConfigCenterChangeEvent extends DubboEvent { private final String protocol; - private final String changeType; + private final ConfigChangeType changeType; private final int count; private final TimePair timePair; public ConfigCenterChangeEvent( - ApplicationModel source, String key, String group, String protocol, String changeType) { + ApplicationModel source, String key, String group, String protocol, ConfigChangeType changeType) { this(source, key, group, protocol, changeType, 1); } public ConfigCenterChangeEvent( - ApplicationModel source, String key, String group, String protocol, String changeType, int count) { + ApplicationModel source, + String key, + String group, + String protocol, + ConfigChangeType changeType, + int count) { super(source); this.key = key; this.group = group; @@ -66,7 +71,7 @@ public String getProtocol() { return protocol; } - public String getChangeType() { + public ConfigChangeType getChangeType() { return changeType; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java index b6a549fc39e..de750ea7511 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java @@ -16,50 +16,29 @@ */ package org.apache.dubbo.common.event; +import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; -import org.apache.dubbo.rpc.model.ScopeModelDestroyListener; import org.apache.dubbo.rpc.model.ScopeModelInitializer; -import java.util.concurrent.ConcurrentHashMap; - /** * Initialize {@link DubboLifecycleEventMulticaster} for {@link ApplicationModel} * - * @see DubboEventBus * @see DubboLifecycleEventMulticaster * @since 3.3.0 */ -public class DubboApplicationMulticasterRegistry - implements ScopeModelInitializer, ScopeModelDestroyListener { - - private static final ConcurrentHashMap multicasterMap = - new ConcurrentHashMap<>(); +public class DubboApplicationMulticasterRegistry implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { - multicasterMap.computeIfAbsent(applicationModel, t -> new DefaultDubboEventMulticaster()); - applicationModel.addDestroyListener(this); + ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); + beanFactory.registerBean(DefaultDubboEventMulticaster.class); } @Override public void initializeModuleModel(ModuleModel moduleModel) {} - - @Override - public void onDestroy(ApplicationModel scopeModel) { - multicasterMap.remove(scopeModel); - } - - @Override - public boolean isProtocol() { - return true; - } - - public static DubboLifecycleEventMulticaster getMulticaster(ApplicationModel applicationModel) { - return multicasterMap.get(applicationModel); - } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java index bbace72f192..66890853e48 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java @@ -16,10 +16,12 @@ */ package org.apache.dubbo.common.event; +import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Supplier; @@ -37,6 +39,9 @@ public class DubboEventBus { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboEventBus.class); + private static final ConcurrentHashMap cachedMulticasterMap = + new ConcurrentHashMap<>(); + private DubboEventBus() {} /** @@ -144,6 +149,9 @@ public static void error(DubboEvent event) { } private static DubboLifecycleEventMulticaster getMulticaster(ApplicationModel applicationModel) { - return DubboApplicationMulticasterRegistry.getMulticaster(applicationModel); + return cachedMulticasterMap.computeIfAbsent(applicationModel, t -> { + ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); + return beanFactory.getBean(DubboLifecycleEventMulticaster.class); + }); } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java index 5d88e8db4d3..09b62bf00f1 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java @@ -744,7 +744,7 @@ private void exportMetricsService() { .getMetrics() .map(MetricsConfig::getExportMetricsService) .orElse(true); - if (exportMetrics) { + if (exportMetrics && metricsServiceExporter != null) { try { metricsServiceExporter.export(); } catch (Exception e) { @@ -853,7 +853,7 @@ private DynamicConfiguration prepareEnvironment(ConfigCenterConfig configCenter) configCenter.getConfigFile(), configCenter.getGroup(), configCenter.getProtocol(), - ConfigChangeType.ADDED.name(), + ConfigChangeType.ADDED, configMap.size())); if (isNotEmpty(appGroup)) { DubboEventBus.publish(new ConfigCenterChangeEvent( @@ -861,7 +861,7 @@ private DynamicConfiguration prepareEnvironment(ConfigCenterConfig configCenter) appConfigFile, appGroup, configCenter.getProtocol(), - ConfigChangeType.ADDED.name(), + ConfigChangeType.ADDED, appConfigMap.size())); } } catch (IOException e) { diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metrics/MockMetricsServiceExporter.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metrics/MockMetricsServiceExporter.java new file mode 100644 index 00000000000..91c956425f2 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metrics/MockMetricsServiceExporter.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.metrics; + +import org.apache.dubbo.metrics.service.MetricsServiceExporter; + +/** + * Export metrics service + */ +public class MockMetricsServiceExporter implements MetricsServiceExporter { + + @Override + public void init() {} + + @Override + public MetricsServiceExporter export() { + return null; + } + + @Override + public MetricsServiceExporter unexport() { + return null; + } +} diff --git a/dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.common.metrics.service.MetricsServiceExporter b/dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.common.metrics.service.MetricsServiceExporter new file mode 100644 index 00000000000..6d35362e1c0 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.common.metrics.service.MetricsServiceExporter @@ -0,0 +1 @@ +default=org.apache.dubbo.config.metrics.MockMetricsServiceExporter diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml index fca1aa5218f..e8e1c4bec4f 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml @@ -38,7 +38,7 @@ - + diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml index 09a71c3aca5..c98b7fa52b8 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml @@ -29,7 +29,7 @@ - + diff --git a/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.metrics.service.MetricsServiceExporter b/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.metrics.service.MetricsServiceExporter deleted file mode 100644 index 6d6fd48ad3f..00000000000 --- a/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.metrics.service.MetricsServiceExporter +++ /dev/null @@ -1 +0,0 @@ -default=org.apache.dubbo.metrics.DefaultMetricsServiceExporter diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java index 517286cbc7d..8079bb6e2c0 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java @@ -273,7 +273,7 @@ public void onChange(com.ctrip.framework.apollo.model.ConfigChangeEvent changeEv event.getKey(), event.getGroup(), ApolloConstants.APOLLO_PROTOCOL, - ConfigChangeType.ADDED.name())); + ConfigChangeType.ADDED)); } } diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java index a6e9a7e4a1b..c5dfde74943 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java @@ -366,7 +366,7 @@ public void innerReceive(String dataId, String group, String configInfo) { event.getKey(), event.getGroup(), NacosConstants.NACOS_PROTOCOL, - ConfigChangeType.ADDED.name())); + ConfigChangeType.ADDED)); } void addListener(ConfigurationListener configurationListener) { diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java index 3bb8478588f..5217dd93ccb 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java @@ -83,6 +83,6 @@ public void dataChanged(String path, Object value, EventType eventType) { configChangeEvent.getKey(), configChangeEvent.getGroup(), ZookeeperConstants.ZK_PROTOCOL, - ConfigChangeType.ADDED.name())); + ConfigChangeType.ADDED)); } } diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/resources/spring/rest-provider.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/resources/spring/rest-provider.xml index 8c6be976f72..78bafadd0ba 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/resources/spring/rest-provider.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/resources/spring/rest-provider.xml @@ -32,7 +32,7 @@ - + diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/resources/spring/dubbo-provider.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/resources/spring/dubbo-provider.xml index ad402bc0683..ae236a6bfe3 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/resources/spring/dubbo-provider.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/resources/spring/dubbo-provider.xml @@ -29,7 +29,7 @@ - + @@ -41,7 +41,7 @@ + ref="restDemoService" protocol="tri"/> diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataEvent.java similarity index 91% rename from dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataEvent.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataEvent.java index 6ef9b4c608f..181d1edbd54 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataEvent.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataEvent.java @@ -20,11 +20,11 @@ import org.apache.dubbo.common.utils.TimePair; import org.apache.dubbo.rpc.model.ApplicationModel; -public abstract class MetaDataEvent extends DubboEvent { +public abstract class MetadataEvent extends DubboEvent { private final TimePair timePair; - public MetaDataEvent(ApplicationModel source) { + public MetadataEvent(ApplicationModel source) { super(source); this.timePair = TimePair.start(); } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataPushEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataPushEvent.java similarity index 89% rename from dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataPushEvent.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataPushEvent.java index 12a97d817ec..2b4c2279050 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataPushEvent.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataPushEvent.java @@ -18,9 +18,9 @@ import org.apache.dubbo.rpc.model.ApplicationModel; -public class MetaDataPushEvent extends MetaDataEvent { +public class MetadataPushEvent extends MetadataEvent { - public MetaDataPushEvent(ApplicationModel source) { + public MetadataPushEvent(ApplicationModel source) { super(source); } } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataServiceSubscribeEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataServiceSubscribeEvent.java similarity index 89% rename from dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataServiceSubscribeEvent.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataServiceSubscribeEvent.java index 0e6db8092f1..bf5c7cc0781 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataServiceSubscribeEvent.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataServiceSubscribeEvent.java @@ -18,11 +18,11 @@ import org.apache.dubbo.rpc.model.ApplicationModel; -public class MetaDataServiceSubscribeEvent extends MetaDataEvent { +public class MetadataServiceSubscribeEvent extends MetadataEvent { private final String serviceKey; - public MetaDataServiceSubscribeEvent(ApplicationModel source, String serviceKey) { + public MetadataServiceSubscribeEvent(ApplicationModel source, String serviceKey) { super(source); this.serviceKey = serviceKey; } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataSubscribeEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataSubscribeEvent.java similarity index 88% rename from dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataSubscribeEvent.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataSubscribeEvent.java index c3746c9221d..f9ac4ee93fb 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetaDataSubscribeEvent.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataSubscribeEvent.java @@ -18,9 +18,9 @@ import org.apache.dubbo.rpc.model.ApplicationModel; -public class MetaDataSubscribeEvent extends MetaDataEvent { +public class MetadataSubscribeEvent extends MetadataEvent { - public MetaDataSubscribeEvent(ApplicationModel source) { + public MetadataSubscribeEvent(ApplicationModel source) { super(source); } } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java index 05639c9197e..56bf8b54e46 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java @@ -27,7 +27,7 @@ import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import org.apache.dubbo.metadata.definition.model.ServiceDefinition; -import org.apache.dubbo.metadata.event.MetaDataServiceSubscribeEvent; +import org.apache.dubbo.metadata.event.MetadataServiceSubscribeEvent; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; @@ -298,8 +298,8 @@ public void storeProviderMetadata( private void storeProviderMetadataTask( MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { - MetaDataServiceSubscribeEvent metadataEvent = - new MetaDataServiceSubscribeEvent(applicationModel, providerMetadataIdentifier.getUniqueServiceName()); + MetadataServiceSubscribeEvent metadataEvent = + new MetadataServiceSubscribeEvent(applicationModel, providerMetadataIdentifier.getUniqueServiceName()); DubboEventBus.post( metadataEvent, () -> { diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java index 8da92393776..dba769c54d4 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java @@ -31,6 +31,10 @@ public ConfigCenterSubDispatcher(ConfigCenterMetricsCollector collector) { @Override public void onEvent(ConfigCenterChangeEvent event) { collector.increase( - event.getKey(), event.getGroup(), event.getProtocol(), event.getChangeType(), event.getCount()); + event.getKey(), + event.getGroup(), + event.getProtocol(), + event.getChangeType().name(), + event.getCount()); } } diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java index 9033b57f85a..7af2abb2631 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java @@ -64,8 +64,8 @@ void increase4Initialized() { String applicationName = applicationModel.getApplicationName(); // collector.increase("key", "group", "nacos", ConfigChangeType.ADDED.name(), 1); // collector.increase("key", "group", "nacos", ConfigChangeType.ADDED.name(), 1); - ConfigCenterChangeEvent configCenterChangeEvent = new ConfigCenterChangeEvent( - applicationModel, "key", "group", "nacos", ConfigChangeType.ADDED.name(), 1); + ConfigCenterChangeEvent configCenterChangeEvent = + new ConfigCenterChangeEvent(applicationModel, "key", "group", "nacos", ConfigChangeType.ADDED, 1); DubboEventBus.publish(configCenterChangeEvent); DubboEventBus.publish(configCenterChangeEvent); @@ -97,7 +97,7 @@ void increaseUpdated() { // SELF_INCREMENT_SIZE); ConfigCenterChangeEvent configCenterChangeEvent = new ConfigCenterChangeEvent( - applicationModel, event.getKey(), event.getGroup(), "apollo", ConfigChangeType.ADDED.name()); + applicationModel, event.getKey(), event.getGroup(), "apollo", ConfigChangeType.ADDED); DubboEventBus.publish(configCenterChangeEvent); DubboEventBus.publish(configCenterChangeEvent); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java index 91d94b14870..cb8fe656416 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java @@ -17,7 +17,8 @@ package org.apache.dubbo.metrics; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; -import org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry; +import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; +import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; @@ -47,14 +48,13 @@ public class DefaultMetricsServiceTest { @BeforeEach public void setUp() { ApplicationModel applicationModel = Mockito.mock(ApplicationModel.class); - new DubboApplicationMulticasterRegistry().initializeApplicationModel(applicationModel); - ScopeBeanFactory beanFactory = Mockito.mock(ScopeBeanFactory.class); metricsCollector = Mockito.mock(MetricsCollector.class); when(applicationModel.getBeanFactory()).thenReturn(beanFactory); when(beanFactory.getBeansOfType(MetricsCollector.class)) .thenReturn(Collections.singletonList(metricsCollector)); + when(beanFactory.getBean(DubboLifecycleEventMulticaster.class)).thenReturn(new DefaultDubboEventMulticaster()); defaultMetricsService = new DefaultMetricsService(applicationModel); } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java index b12f20b0cb9..c6fbfc0c517 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java @@ -19,8 +19,9 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry; +import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; import org.apache.dubbo.common.event.DubboEventBus; +import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; import org.apache.dubbo.common.event.DubboListener; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ReflectionUtils; @@ -203,7 +204,6 @@ void testRequestsMetrics() { @Test public void testQPS() { ApplicationModel applicationModel = mock(ApplicationModel.class); - new DubboApplicationMulticasterRegistry().initializeApplicationModel(applicationModel); ConfigManager configManager = mock(ConfigManager.class); MetricsConfig metricsConfig = mock(MetricsConfig.class); @@ -212,6 +212,7 @@ public void testQPS() { when(applicationModel.getApplicationConfigManager()).thenReturn(configManager); when(applicationModel.getBeanFactory()).thenReturn(beanFactory); + when(beanFactory.getBean(DubboLifecycleEventMulticaster.class)).thenReturn(new DefaultDubboEventMulticaster()); DefaultMetricsCollector defaultMetricsCollector = new DefaultMetricsCollector(applicationModel); when(beanFactory.getBean(DefaultMetricsCollector.class)).thenReturn(defaultMetricsCollector); when(configManager.getMetrics()).thenReturn(Optional.of(metricsConfig)); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java index c31c06970e6..b5e3dec2540 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java @@ -17,7 +17,9 @@ package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; import org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry; +import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; @@ -35,7 +37,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -55,16 +56,10 @@ public class ThreadPoolMetricsSamplerTest { @BeforeEach void setUp() { - multicasterRegistry.initializeApplicationModel(applicationModel); DefaultMetricsCollector collector = new DefaultMetricsCollector(applicationModel); sampler = new ThreadPoolMetricsSampler(collector); } - @AfterEach - void tearDown() { - multicasterRegistry.onDestroy(applicationModel); - } - @Test void testSample() { @@ -145,15 +140,16 @@ void testSample() { @BeforeEach public void setUp2() { MockitoAnnotations.openMocks(this); - new DubboApplicationMulticasterRegistry().initializeApplicationModel(applicationModel); + + when(applicationModel.getBeanFactory()).thenReturn(scopeBeanFactory); + when(scopeBeanFactory.getBean(DubboLifecycleEventMulticaster.class)) + .thenReturn(new DefaultDubboEventMulticaster()); collector = new DefaultMetricsCollector(applicationModel); sampler2 = new ThreadPoolMetricsSampler(collector); when(scopeBeanFactory.getBean(FrameworkExecutorRepository.class)).thenReturn(new FrameworkExecutorRepository()); - collector.collectApplication(); - when(applicationModel.getBeanFactory()).thenReturn(scopeBeanFactory); when(applicationModel.getExtensionLoader(DataStore.class)).thenReturn(extensionLoader); when(extensionLoader.getDefaultExtension()).thenReturn(dataStore); } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java index 57d488cd16a..28909aa961b 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java @@ -104,7 +104,7 @@ public void teardown() { @Test void testCollectDisabled() { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); - + initParam(); filter.invoke(invoker, invocation); Map metricsMap = getMetricsMap(); metricsMap.remove(MetricsKey.APPLICATION_METRIC_INFO.getName()); diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEvent.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEvent.java index 2e8ad3e751d..b896619552e 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEvent.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEvent.java @@ -18,10 +18,10 @@ import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.utils.TimePair; -import org.apache.dubbo.metadata.event.MetaDataEvent; -import org.apache.dubbo.metadata.event.MetaDataPushEvent; -import org.apache.dubbo.metadata.event.MetaDataServiceSubscribeEvent; -import org.apache.dubbo.metadata.event.MetaDataSubscribeEvent; +import org.apache.dubbo.metadata.event.MetadataEvent; +import org.apache.dubbo.metadata.event.MetadataPushEvent; +import org.apache.dubbo.metadata.event.MetadataServiceSubscribeEvent; +import org.apache.dubbo.metadata.event.MetadataSubscribeEvent; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.metadata.collector.MetadataMetricsCollector; import org.apache.dubbo.metrics.model.key.MetricsLevel; @@ -89,15 +89,15 @@ public static MetadataMetricsEvent toServiceSubscribeEvent( return metadataMetricsEvent; } - public static MetadataMetricsEvent convertEvent(MetaDataEvent event) { + public static MetadataMetricsEvent convertEvent(MetadataEvent event) { MetadataMetricsEvent metadataMetricsEvent; - if (event instanceof MetaDataPushEvent) { + if (event instanceof MetadataPushEvent) { metadataMetricsEvent = MetadataMetricsEvent.toPushEvent(event.getApplicationModel(), event.getTimePair()); - } else if (event instanceof MetaDataSubscribeEvent) { + } else if (event instanceof MetadataSubscribeEvent) { metadataMetricsEvent = MetadataMetricsEvent.toSubscribeEvent(event.getApplicationModel(), event.getTimePair()); - } else if (event instanceof MetaDataServiceSubscribeEvent) { - MetaDataServiceSubscribeEvent serviceEvent = (MetaDataServiceSubscribeEvent) event; + } else if (event instanceof MetadataServiceSubscribeEvent) { + MetadataServiceSubscribeEvent serviceEvent = (MetadataServiceSubscribeEvent) event; metadataMetricsEvent = MetadataMetricsEvent.toServiceSubscribeEvent( event.getApplicationModel(), serviceEvent.getServiceKey(), event.getTimePair()); } else { diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java index de7caa9db45..93ab8d1615c 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java @@ -19,7 +19,7 @@ import org.apache.dubbo.common.event.AbstractDubboLifecycleListener; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.metadata.event.MetaDataEvent; +import org.apache.dubbo.metadata.event.MetadataEvent; import org.apache.dubbo.metrics.event.TimeCounterEventMulticaster; import org.apache.dubbo.metrics.listener.MetricsApplicationListener; import org.apache.dubbo.metrics.listener.MetricsServiceListener; @@ -35,7 +35,7 @@ import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_STORE_PROVIDER_INTERFACE; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_SUBSCRIBE; -public final class MetadataSubDispatcher extends AbstractDubboLifecycleListener { +public final class MetadataSubDispatcher extends AbstractDubboLifecycleListener { ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MetadataSubDispatcher.class); @@ -57,7 +57,7 @@ public MetadataSubDispatcher(MetadataMetricsCollector collector) { } @Override - public void onEventBefore(MetaDataEvent event) { + public void onEventBefore(MetadataEvent event) { MetadataMetricsEvent metadataMetricsEvent = MetadataMetricsEvent.convertEvent(event); if (metadataMetricsEvent == null) { logger.debug("Unsupported event type: {}", event.getClass().getName()); @@ -67,7 +67,7 @@ public void onEventBefore(MetaDataEvent event) { } @Override - public void onEventFinish(MetaDataEvent event) { + public void onEventFinish(MetadataEvent event) { MetadataMetricsEvent metadataMetricsEvent = MetadataMetricsEvent.convertEvent(event); if (metadataMetricsEvent == null) { logger.debug("Unsupported event type: {}", event.getClass().getName()); @@ -77,7 +77,7 @@ public void onEventFinish(MetaDataEvent event) { } @Override - public void onEventError(MetaDataEvent event) { + public void onEventError(MetadataEvent event) { MetadataMetricsEvent metadataMetricsEvent = MetadataMetricsEvent.convertEvent(event); if (metadataMetricsEvent == null) { logger.debug("Unsupported event type: {}", event.getClass().getName()); diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java index 4050b592a63..b870316a294 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java @@ -20,9 +20,9 @@ import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.utils.TimePair; import org.apache.dubbo.config.ApplicationConfig; -import org.apache.dubbo.metadata.event.MetaDataPushEvent; -import org.apache.dubbo.metadata.event.MetaDataServiceSubscribeEvent; -import org.apache.dubbo.metadata.event.MetaDataSubscribeEvent; +import org.apache.dubbo.metadata.event.MetadataPushEvent; +import org.apache.dubbo.metadata.event.MetadataServiceSubscribeEvent; +import org.apache.dubbo.metadata.event.MetadataSubscribeEvent; import org.apache.dubbo.metrics.metadata.collector.MetadataMetricsCollector; import org.apache.dubbo.metrics.metadata.event.MetadataSubDispatcher; import org.apache.dubbo.metrics.model.key.MetricsKey; @@ -70,10 +70,10 @@ public void setup() { @Test void testListener() { MetadataSubDispatcher dispatcher = new MetadataSubDispatcher(collector); - MetaDataPushEvent event = new MetaDataPushEvent(applicationModel); - MetaDataSubscribeEvent subscribeEvent = new MetaDataSubscribeEvent(applicationModel); - MetaDataServiceSubscribeEvent serviceSubscribeEvent = - new MetaDataServiceSubscribeEvent(applicationModel, "serviceKey"); + MetadataPushEvent event = new MetadataPushEvent(applicationModel); + MetadataSubscribeEvent subscribeEvent = new MetadataSubscribeEvent(applicationModel); + MetadataServiceSubscribeEvent serviceSubscribeEvent = + new MetadataServiceSubscribeEvent(applicationModel, "serviceKey"); DubboEvent otherEvent = new DubboEvent(applicationModel); Assertions.assertTrue(dispatcher.support(event.getClass())); @@ -89,7 +89,7 @@ public void teardown() { @Test void testPushMetrics() { - MetaDataPushEvent pushEvent = new MetaDataPushEvent(applicationModel); + MetadataPushEvent pushEvent = new MetadataPushEvent(applicationModel); DubboEventBus.post(pushEvent, () -> { List metricSamples = collector.collect(); @@ -108,7 +108,7 @@ void testPushMetrics() { Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size()); long c1 = pushEvent.getTimePair().calc(); - pushEvent = new MetaDataPushEvent(applicationModel); + pushEvent = new MetadataPushEvent(applicationModel); TimePair lastTimePair = pushEvent.getTimePair(); DubboEventBus.post( pushEvent, @@ -158,7 +158,7 @@ void testPushMetrics() { void testSubscribeMetrics() { // MetadataMetricsCollector collector = getCollector(); - MetaDataSubscribeEvent subscribeEvent = new MetaDataSubscribeEvent(applicationModel); + MetadataSubscribeEvent subscribeEvent = new MetadataSubscribeEvent(applicationModel); DubboEventBus.post(subscribeEvent, () -> { List metricSamples = collector.collect(); @@ -177,7 +177,7 @@ void testSubscribeMetrics() { // App(6) + rt(5) = 7 Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size()); - subscribeEvent = new MetaDataSubscribeEvent(applicationModel); + subscribeEvent = new MetadataSubscribeEvent(applicationModel); TimePair lastTimePair = subscribeEvent.getTimePair(); DubboEventBus.post( subscribeEvent, @@ -229,7 +229,7 @@ void testStoreProviderMetadataMetrics() { // MetadataMetricsCollector collector = getCollector(); String serviceKey = "store.provider.test"; - MetaDataServiceSubscribeEvent metadataEvent = new MetaDataServiceSubscribeEvent(applicationModel, serviceKey); + MetadataServiceSubscribeEvent metadataEvent = new MetadataServiceSubscribeEvent(applicationModel, serviceKey); DubboEventBus.post(metadataEvent, () -> { List metricSamples = collector.collect(); @@ -248,7 +248,7 @@ void testStoreProviderMetadataMetrics() { Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 2 + 5, metricSamples.size()); long c1 = metadataEvent.getTimePair().calc(); - metadataEvent = new MetaDataServiceSubscribeEvent(applicationModel, serviceKey); + metadataEvent = new MetadataServiceSubscribeEvent(applicationModel, serviceKey); TimePair lastTimePair = metadataEvent.getTimePair(); DubboEventBus.post( metadataEvent, @@ -305,7 +305,7 @@ void testStoreProviderMetadataMetrics() { void testMetadataPushNum() { for (int i = 0; i < 10; i++) { - MetaDataPushEvent event = new MetaDataPushEvent(applicationModel); + MetadataPushEvent event = new MetadataPushEvent(applicationModel); if (i % 2 == 0) { DubboEventBus.post(event, () -> true, r -> r); } else { @@ -328,7 +328,7 @@ void testMetadataPushNum() { void testSubscribeSum() { for (int i = 0; i < 10; i++) { - MetaDataSubscribeEvent event = new MetaDataSubscribeEvent(applicationModel); + MetadataSubscribeEvent event = new MetadataSubscribeEvent(applicationModel); if (i % 2 == 0) { DubboEventBus.post(event, () -> true, r -> r); } else { diff --git a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java index fc2dbe1b23b..a68be08887c 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java @@ -16,7 +16,9 @@ */ package org.apache.dubbo.metrics.registry.metrics.collector; -import org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry; +import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; +import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -42,10 +44,10 @@ import java.util.concurrent.TimeUnit; import com.google.common.collect.Lists; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; @@ -58,21 +60,15 @@ public class RegistryMetricsTest { String REGISTER = "register"; - DubboApplicationMulticasterRegistry registry = new DubboApplicationMulticasterRegistry(); - @BeforeEach void setUp() { this.applicationModel = getApplicationModel(); - registry.initializeApplicationModel(applicationModel); + ScopeBeanFactory beanFactory = Mockito.mock(ScopeBeanFactory.class); + when(beanFactory.getBean(DubboLifecycleEventMulticaster.class)).thenReturn(new DefaultDubboEventMulticaster()); this.collector = getTestCollector(this.applicationModel); this.collector.setCollectEnabled(true); } - @AfterEach - void tearDown() { - registry.onDestroy(applicationModel); - } - @Test void testRegisterRequestsCount() { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java index 795e7bc3c62..4fc29e20cc9 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java @@ -24,8 +24,8 @@ import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metadata.MetadataInfo; -import org.apache.dubbo.metadata.event.MetaDataPushEvent; -import org.apache.dubbo.metadata.event.MetaDataSubscribeEvent; +import org.apache.dubbo.metadata.event.MetadataPushEvent; +import org.apache.dubbo.metadata.event.MetadataSubscribeEvent; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.metadata.report.MetadataReportInstance; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; @@ -246,7 +246,7 @@ public MetadataInfo getRemoteMetadata(String revision, List ins while (triedTimes < 3) { metadata = DubboEventBus.post( - new MetaDataSubscribeEvent(applicationModel), + new MetadataSubscribeEvent(applicationModel), () -> MetadataUtils.getRemoteMetadata(revision, instances, metadataReport), result -> result != MetadataInfo.EMPTY); @@ -384,7 +384,7 @@ protected void reportMetadata(MetadataInfo metadataInfo) { new SubscriberMetadataIdentifier(serviceName, metadataInfo.getRevision()); if ((DEFAULT_METADATA_STORAGE_TYPE.equals(metadataType) && metadataReport.shouldReportMetadata()) || REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) { - DubboEventBus.post(new MetaDataPushEvent(applicationModel), () -> { + DubboEventBus.post(new MetadataPushEvent(applicationModel), () -> { metadataReport.publishAppMetadata(identifier, metadataInfo); return null; }); diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml index 5f57672cedb..5b8510d6f88 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml @@ -46,11 +46,6 @@ test - - org.apache.dubbo - dubbo-common - ${project.parent.version} - org.apache.curator curator-framework diff --git a/dubbo-test/dubbo-test-spring/pom.xml b/dubbo-test/dubbo-test-spring/pom.xml index b248dcaae2e..3cfab27e723 100644 --- a/dubbo-test/dubbo-test-spring/pom.xml +++ b/dubbo-test/dubbo-test-spring/pom.xml @@ -99,6 +99,11 @@ dubbo-rpc-dubbo ${project.version} + + org.apache.dubbo + dubbo-rpc-triple + ${project.version} + org.apache.dubbo dubbo-config-spring diff --git a/dubbo-test/dubbo-test-spring/src/main/resources/spring/dubbo-demo-provider.xml b/dubbo-test/dubbo-test-spring/src/main/resources/spring/dubbo-demo-provider.xml index 0520c33a135..a6b94583561 100644 --- a/dubbo-test/dubbo-test-spring/src/main/resources/spring/dubbo-demo-provider.xml +++ b/dubbo-test/dubbo-test-spring/src/main/resources/spring/dubbo-demo-provider.xml @@ -28,7 +28,7 @@ - + @@ -38,5 +38,5 @@ + ref="restDemoServiceImpl" protocol="tri"/> diff --git a/dubbo-test/dubbo-test-spring/src/main/resources/spring/dubbo-demo.xml b/dubbo-test/dubbo-test-spring/src/main/resources/spring/dubbo-demo.xml index 4175665f45f..4f31f8740f6 100644 --- a/dubbo-test/dubbo-test-spring/src/main/resources/spring/dubbo-demo.xml +++ b/dubbo-test/dubbo-test-spring/src/main/resources/spring/dubbo-demo.xml @@ -28,7 +28,7 @@ - + @@ -38,6 +38,6 @@ - From 320a564a3562a8eb94f4343181a495efb1eaf3c1 Mon Sep 17 00:00:00 2001 From: walklown Date: Mon, 27 May 2024 20:56:21 +0800 Subject: [PATCH 03/12] Merge branch '3.3' into feature/refector-metric-export --- .../org/apache/dubbo/metrics/MetricsServiceInitializer.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java b/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java index b9846e24207..49c23391753 100644 --- a/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java +++ b/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java @@ -70,7 +70,8 @@ public void onEvent(ApplicationLoadedEvent event) { if (MetricsSupportUtil.isSupportMetrics()) { MetricsConfig metricsConfig = initMetricsConfig(); - if (!PROTOCOL_PROMETHEUS.equals(metricsConfig.getProtocol()) || MetricsSupportUtil.isSupportPrometheus()) { + if (!PROTOCOL_PROMETHEUS.equals(metricsConfig.getProtocol()) + || MetricsSupportUtil.isSupportPrometheus()) { initDefaultMetricsCollector(metricsConfig); initMetricsReporter(metricsConfig); } From 19db740ec7f09c6488bfd1915e6d853635549920 Mon Sep 17 00:00:00 2001 From: walklown Date: Thu, 6 Jun 2024 19:05:29 +0800 Subject: [PATCH 04/12] Allows extension of DubboEventMulticaster --- .../event/CompositeDubboEventMulticaster.java | 49 +++++++++++++++ ...mpositeDubboLifecycleEventMulticaster.java | 63 +++++++++++++++++++ ...efaultDubboLifecycleEventMulticaster.java} | 5 +- .../dubbo/common/event/DubboEventBus.java | 28 +++++++-- .../common/event/DubboEventMulticaster.java | 3 + ...ubboMulticasterScopeModelInitializer.java} | 28 ++++++++- ...e.dubbo.common.event.DubboEventMulticaster | 1 + ...ache.dubbo.rpc.model.ScopeModelInitializer | 2 +- .../metrics/DefaultMetricsServiceTest.java | 12 +++- .../AggregateMetricsCollectorTest.java | 12 +++- .../sample/ThreadPoolMetricsSamplerTest.java | 18 ++++-- .../collector/RegistryMetricsTest.java | 13 +++- 12 files changed, 209 insertions(+), 25 deletions(-) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboEventMulticaster.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboLifecycleEventMulticaster.java rename dubbo-common/src/main/java/org/apache/dubbo/common/event/{DefaultDubboEventMulticaster.java => DefaultDubboLifecycleEventMulticaster.java} (96%) rename dubbo-common/src/main/java/org/apache/dubbo/common/event/{DubboApplicationMulticasterRegistry.java => DubboMulticasterScopeModelInitializer.java} (54%) create mode 100644 dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.event.DubboEventMulticaster diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboEventMulticaster.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboEventMulticaster.java new file mode 100644 index 00000000000..4432c2a0d33 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboEventMulticaster.java @@ -0,0 +1,49 @@ +/* + * 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.common.event; + +import java.util.List; + +public class CompositeDubboEventMulticaster implements DubboEventMulticaster { + + private final List multicasterList; + + public CompositeDubboEventMulticaster(List multicasterList) { + this.multicasterList = multicasterList; + } + + @Override + public void addListener(DubboListener listener) { + for (DubboEventMulticaster dubboEventMulticaster : multicasterList) { + dubboEventMulticaster.addListener(listener); + } + } + + @Override + public void removeListener(DubboListener listener) { + for (DubboEventMulticaster dubboEventMulticaster : multicasterList) { + dubboEventMulticaster.removeListener(listener); + } + } + + @Override + public void publishEvent(DubboEvent event) { + for (DubboEventMulticaster dubboEventMulticaster : multicasterList) { + dubboEventMulticaster.publishEvent(event); + } + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboLifecycleEventMulticaster.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboLifecycleEventMulticaster.java new file mode 100644 index 00000000000..5b496813dc9 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboLifecycleEventMulticaster.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.event; + +import java.util.List; + +public class CompositeDubboLifecycleEventMulticaster implements DubboLifecycleEventMulticaster { + + private final List multicasterList; + + public CompositeDubboLifecycleEventMulticaster(List multicasterList) { + this.multicasterList = multicasterList; + } + + @Override + public void publishBeforeEvent(DubboEvent event) { + for (DubboLifecycleEventMulticaster multicaster : multicasterList) { + multicaster.publishBeforeEvent(event); + } + } + + @Override + public void publishErrorEvent(DubboEvent event) { + for (DubboLifecycleEventMulticaster multicaster : multicasterList) { + multicaster.publishErrorEvent(event); + } + } + + @Override + public void addListener(DubboListener listener) { + for (DubboLifecycleEventMulticaster multicaster : multicasterList) { + multicaster.addListener(listener); + } + } + + @Override + public void removeListener(DubboListener listener) { + for (DubboLifecycleEventMulticaster multicaster : multicasterList) { + multicaster.removeListener(listener); + } + } + + @Override + public void publishEvent(DubboEvent event) { + for (DubboLifecycleEventMulticaster multicaster : multicasterList) { + multicaster.publishEvent(event); + } + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboLifecycleEventMulticaster.java similarity index 96% rename from dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboLifecycleEventMulticaster.java index 06a37292f10..f1b70f5c8f5 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboLifecycleEventMulticaster.java @@ -16,13 +16,16 @@ */ package org.apache.dubbo.common.event; +import org.apache.dubbo.common.extension.Activate; + import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; -public class DefaultDubboEventMulticaster implements DubboLifecycleEventMulticaster { +@Activate +public class DefaultDubboLifecycleEventMulticaster implements DubboLifecycleEventMulticaster { /** * All registered subscribers, indexed by event type. diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java index 66890853e48..444b80eb10d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java @@ -39,9 +39,12 @@ public class DubboEventBus { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboEventBus.class); - private static final ConcurrentHashMap cachedMulticasterMap = + private static final ConcurrentHashMap cachedMulticasterMap = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap + cachedLifecycleMulticasterMap = new ConcurrentHashMap<>(); + private DubboEventBus() {} /** @@ -50,6 +53,9 @@ private DubboEventBus() {} * @param listener object whose subscriber methods should be registered. */ public static void addListener(ApplicationModel applicationModel, DubboListener listener) { + if (listener instanceof DubboLifecycleListener) { + getLifecycleMulticaster(applicationModel).addListener(listener); + } getMulticaster(applicationModel).addListener(listener); } @@ -60,6 +66,9 @@ public static void addListener(ApplicationModel applicationModel, DubboListener< * @throws IllegalArgumentException if the object was not previously registered. */ public static void removeListener(ApplicationModel applicationModel, DubboListener listener) { + if (listener instanceof DubboLifecycleListener) { + getLifecycleMulticaster(applicationModel).removeListener(listener); + } getMulticaster(applicationModel).removeListener(listener); } @@ -131,7 +140,7 @@ private static void tryInvoke(Runnable runnable) { * eventSaveRunner saves the event, so that the calculation rt is introverted */ public static void before(DubboEvent event) { - tryInvoke(() -> getMulticaster(event.getApplicationModel()).publishBeforeEvent(event)); + tryInvoke(() -> getLifecycleMulticaster(event.getApplicationModel()).publishBeforeEvent(event)); } @SuppressWarnings({"unchecked", "rawtypes"}) @@ -140,18 +149,25 @@ public static void after(DubboEvent event, Object result) { if (event instanceof CustomAfterPost) { ((CustomAfterPost) event).customAfterPost(result); } - getMulticaster(event.getApplicationModel()).publishEvent(event); + getLifecycleMulticaster(event.getApplicationModel()).publishEvent(event); }); } public static void error(DubboEvent event) { - tryInvoke(() -> getMulticaster(event.getApplicationModel()).publishErrorEvent(event)); + tryInvoke(() -> getLifecycleMulticaster(event.getApplicationModel()).publishErrorEvent(event)); } - private static DubboLifecycleEventMulticaster getMulticaster(ApplicationModel applicationModel) { + private static DubboEventMulticaster getMulticaster(ApplicationModel applicationModel) { return cachedMulticasterMap.computeIfAbsent(applicationModel, t -> { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); - return beanFactory.getBean(DubboLifecycleEventMulticaster.class); + return beanFactory.getBean(CompositeDubboEventMulticaster.class); + }); + } + + private static DubboLifecycleEventMulticaster getLifecycleMulticaster(ApplicationModel applicationModel) { + return cachedLifecycleMulticasterMap.computeIfAbsent(applicationModel, t -> { + ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); + return beanFactory.getBean(CompositeDubboLifecycleEventMulticaster.class); }); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java index ecfae62a689..640c1d5710c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java @@ -16,6 +16,8 @@ */ package org.apache.dubbo.common.event; +import org.apache.dubbo.common.extension.SPI; + /** * Dispatches events to listeners, and provides ways for listeners to register themselves. * @@ -23,6 +25,7 @@ * @see DubboEvent * @see DubboListener */ +@SPI public interface DubboEventMulticaster { /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboMulticasterScopeModelInitializer.java similarity index 54% rename from dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboMulticasterScopeModelInitializer.java index de750ea7511..6808f1f4b65 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboMulticasterScopeModelInitializer.java @@ -17,18 +17,22 @@ package org.apache.dubbo.common.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; +import java.util.ArrayList; +import java.util.List; + /** * Initialize {@link DubboLifecycleEventMulticaster} for {@link ApplicationModel} * * @see DubboLifecycleEventMulticaster * @since 3.3.0 */ -public class DubboApplicationMulticasterRegistry implements ScopeModelInitializer { +public class DubboMulticasterScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @@ -36,7 +40,27 @@ public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); - beanFactory.registerBean(DefaultDubboEventMulticaster.class); + + List lifecycleEventMulticasters = new ArrayList<>(); + CompositeDubboLifecycleEventMulticaster lifecycleEventMulticaster = + new CompositeDubboLifecycleEventMulticaster(lifecycleEventMulticasters); + + List eventMulticasters = new ArrayList<>(); + CompositeDubboEventMulticaster dubboEventMulticaster = new CompositeDubboEventMulticaster(eventMulticasters); + + ExtensionLoader extensionLoader = + applicationModel.getExtensionLoader(DubboEventMulticaster.class); + if (extensionLoader != null) { + for (DubboEventMulticaster eventMulticaster : extensionLoader.getActivateExtensions()) { + eventMulticasters.add(eventMulticaster); + if (eventMulticaster instanceof DubboLifecycleEventMulticaster) { + lifecycleEventMulticasters.add((DubboLifecycleEventMulticaster) eventMulticaster); + } + } + } + + beanFactory.registerBean(lifecycleEventMulticaster); + beanFactory.registerBean(dubboEventMulticaster); } @Override diff --git a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.event.DubboEventMulticaster b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.event.DubboEventMulticaster new file mode 100644 index 00000000000..61f51901319 --- /dev/null +++ b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.event.DubboEventMulticaster @@ -0,0 +1 @@ +default=org.apache.dubbo.common.event.DefaultDubboLifecycleEventMulticaster \ No newline at end of file diff --git a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer index 956665085f0..f2258d26986 100644 --- a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer +++ b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer @@ -1,2 +1,2 @@ dubbo-common=org.apache.dubbo.common.CommonScopeModelInitializer -application-multicaster-registry=org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry \ No newline at end of file +dubbo-multicaster-init=org.apache.dubbo.common.event.DubboMulticasterScopeModelInitializer \ No newline at end of file diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java index cb8fe656416..db5feb959df 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java @@ -17,8 +17,9 @@ package org.apache.dubbo.metrics; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; -import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; -import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.CompositeDubboEventMulticaster; +import org.apache.dubbo.common.event.CompositeDubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.DefaultDubboLifecycleEventMulticaster; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; @@ -54,7 +55,12 @@ public void setUp() { when(applicationModel.getBeanFactory()).thenReturn(beanFactory); when(beanFactory.getBeansOfType(MetricsCollector.class)) .thenReturn(Collections.singletonList(metricsCollector)); - when(beanFactory.getBean(DubboLifecycleEventMulticaster.class)).thenReturn(new DefaultDubboEventMulticaster()); + when(beanFactory.getBean(CompositeDubboEventMulticaster.class)) + .thenReturn(new CompositeDubboEventMulticaster( + Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); + when(beanFactory.getBean(CompositeDubboLifecycleEventMulticaster.class)) + .thenReturn(new CompositeDubboLifecycleEventMulticaster( + Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); defaultMetricsService = new DefaultMetricsService(applicationModel); } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java index c6fbfc0c517..a9c905f71a7 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java @@ -19,9 +19,10 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; +import org.apache.dubbo.common.event.CompositeDubboEventMulticaster; +import org.apache.dubbo.common.event.CompositeDubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.DefaultDubboLifecycleEventMulticaster; import org.apache.dubbo.common.event.DubboEventBus; -import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; import org.apache.dubbo.common.event.DubboListener; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ReflectionUtils; @@ -212,7 +213,12 @@ public void testQPS() { when(applicationModel.getApplicationConfigManager()).thenReturn(configManager); when(applicationModel.getBeanFactory()).thenReturn(beanFactory); - when(beanFactory.getBean(DubboLifecycleEventMulticaster.class)).thenReturn(new DefaultDubboEventMulticaster()); + when(beanFactory.getBean(CompositeDubboEventMulticaster.class)) + .thenReturn(new CompositeDubboEventMulticaster( + Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); + when(beanFactory.getBean(CompositeDubboLifecycleEventMulticaster.class)) + .thenReturn(new CompositeDubboLifecycleEventMulticaster( + Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); DefaultMetricsCollector defaultMetricsCollector = new DefaultMetricsCollector(applicationModel); when(beanFactory.getBean(DefaultMetricsCollector.class)).thenReturn(defaultMetricsCollector); when(configManager.getMetrics()).thenReturn(Optional.of(metricsConfig)); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java index b5e3dec2540..7c6a2657e81 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java @@ -17,9 +17,10 @@ package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; -import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; -import org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry; -import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.CompositeDubboEventMulticaster; +import org.apache.dubbo.common.event.CompositeDubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.DefaultDubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.DubboMulticasterScopeModelInitializer; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; @@ -30,6 +31,7 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import java.lang.reflect.Field; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -52,7 +54,7 @@ public class ThreadPoolMetricsSamplerTest { ThreadPoolMetricsSampler sampler; - private DubboApplicationMulticasterRegistry multicasterRegistry = new DubboApplicationMulticasterRegistry(); + private DubboMulticasterScopeModelInitializer multicasterInitializer = new DubboMulticasterScopeModelInitializer(); @BeforeEach void setUp() { @@ -142,8 +144,12 @@ public void setUp2() { MockitoAnnotations.openMocks(this); when(applicationModel.getBeanFactory()).thenReturn(scopeBeanFactory); - when(scopeBeanFactory.getBean(DubboLifecycleEventMulticaster.class)) - .thenReturn(new DefaultDubboEventMulticaster()); + when(scopeBeanFactory.getBean(CompositeDubboEventMulticaster.class)) + .thenReturn(new CompositeDubboEventMulticaster( + Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); + when(scopeBeanFactory.getBean(CompositeDubboLifecycleEventMulticaster.class)) + .thenReturn(new CompositeDubboLifecycleEventMulticaster( + Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); collector = new DefaultMetricsCollector(applicationModel); sampler2 = new ThreadPoolMetricsSampler(collector); diff --git a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java index a68be08887c..2612a620a73 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java @@ -17,8 +17,9 @@ package org.apache.dubbo.metrics.registry.metrics.collector; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; -import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; -import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.CompositeDubboEventMulticaster; +import org.apache.dubbo.common.event.CompositeDubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.DefaultDubboLifecycleEventMulticaster; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -34,6 +35,7 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; @@ -64,7 +66,12 @@ public class RegistryMetricsTest { void setUp() { this.applicationModel = getApplicationModel(); ScopeBeanFactory beanFactory = Mockito.mock(ScopeBeanFactory.class); - when(beanFactory.getBean(DubboLifecycleEventMulticaster.class)).thenReturn(new DefaultDubboEventMulticaster()); + when(beanFactory.getBean(CompositeDubboEventMulticaster.class)) + .thenReturn(new CompositeDubboEventMulticaster( + Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); + when(beanFactory.getBean(CompositeDubboLifecycleEventMulticaster.class)) + .thenReturn(new CompositeDubboLifecycleEventMulticaster( + Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); this.collector = getTestCollector(this.applicationModel); this.collector.setCollectEnabled(true); } From 7eb1e23c9e0e3bf5996593a7e76de405ed5eec36 Mon Sep 17 00:00:00 2001 From: walklown Date: Fri, 7 Jun 2024 01:40:45 +0800 Subject: [PATCH 05/12] ScopeModelInitializer supports Ordered sorting --- .../java/org/apache/dubbo/common/Ordered.java | 28 +++++++++++++ .../dubbo/common/event/DubboEventBus.java | 12 +++++- .../utils/OrderedObjectCompareUtils.java | 40 +++++++++++++++++++ .../dubbo/rpc/model/ApplicationModel.java | 7 ++-- .../dubbo/rpc/model/FrameworkModel.java | 7 ++-- .../apache/dubbo/rpc/model/ModuleModel.java | 7 ++-- .../metrics/MetricsScopeModelInitializer.java | 8 +++- 7 files changed, 97 insertions(+), 12 deletions(-) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java new file mode 100644 index 00000000000..3c2d995296b --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java @@ -0,0 +1,28 @@ +/* + * 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.common; + +public interface Ordered { + + int HIGHEST_PRECEDENCE = Integer.MIN_VALUE; + + int LOWEST_PRECEDENCE = Integer.MAX_VALUE; + + default int getOrder() { + return 0; + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java index 444b80eb10d..60b4a57851b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java @@ -54,9 +54,17 @@ private DubboEventBus() {} */ public static void addListener(ApplicationModel applicationModel, DubboListener listener) { if (listener instanceof DubboLifecycleListener) { - getLifecycleMulticaster(applicationModel).addListener(listener); + DubboLifecycleEventMulticaster lifecycleEventMulticaster = getLifecycleMulticaster(applicationModel); + if (lifecycleEventMulticaster == null) { + throw new RuntimeException("DubboLifecycleEventMulticaster has not been initialized"); + } + lifecycleEventMulticaster.addListener(listener); + } + DubboEventMulticaster multicaster = getMulticaster(applicationModel); + if (multicaster == null) { + throw new RuntimeException("DubboEventMulticaster has not been initialized"); } - getMulticaster(applicationModel).addListener(listener); + multicaster.addListener(listener); } /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java new file mode 100644 index 00000000000..9e24f9d7bcf --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java @@ -0,0 +1,40 @@ +/* + * 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.common.utils; + +import org.apache.dubbo.common.Ordered; + +public class OrderedObjectCompareUtils { + + public static int compareByOrder(Object o1, Object o2) { + boolean o1Ordered = o1 instanceof Ordered; + boolean o2Ordered = o2 instanceof Ordered; + if (!o1Ordered) { + if (!o2Ordered) { + return 0; + } else { + return -1; + } + } else { + if (!o2Ordered) { + return 1; + } else { + return Integer.compare(((Ordered) o1).getOrder(), ((Ordered) o2).getOrder()); + } + } + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java index 1971cf25e70..8474638ca2c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java @@ -25,6 +25,7 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.Assert; +import org.apache.dubbo.common.utils.OrderedObjectCompareUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -123,9 +124,9 @@ protected ApplicationModel(FrameworkModel frameworkModel, boolean isInternal) { ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); - for (ScopeModelInitializer initializer : initializers) { - initializer.initializeApplicationModel(this); - } + initializers.stream() + .sorted(OrderedObjectCompareUtils::compareByOrder) + .forEach(initializer -> initializer.initializeApplicationModel(this)); Assert.notNull(getApplicationServiceRepository(), "ApplicationServiceRepository can not be null"); Assert.notNull(getApplicationConfigManager(), "ApplicationConfigManager can not be null"); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java index e5fb2b52ff4..bcd6ec3b3bc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java @@ -24,6 +24,7 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.GlobalResourcesRepository; import org.apache.dubbo.common.utils.Assert; +import org.apache.dubbo.common.utils.OrderedObjectCompareUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; @@ -94,9 +95,9 @@ public FrameworkModel() { ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); - for (ScopeModelInitializer initializer : initializers) { - initializer.initializeFrameworkModel(this); - } + initializers.stream() + .sorted(OrderedObjectCompareUtils::compareByOrder) + .forEach(initializer -> initializer.initializeFrameworkModel(this)); internalApplicationModel = new ApplicationModel(this, true); internalApplicationModel diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java index 9af38b04289..aea6c241cce 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java @@ -28,6 +28,7 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.ClassUtils; +import org.apache.dubbo.common.utils.OrderedObjectCompareUtils; import org.apache.dubbo.config.context.ModuleConfigManager; import java.util.HashMap; @@ -72,9 +73,9 @@ protected ModuleModel(ApplicationModel applicationModel, boolean isInternal) { ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); - for (ScopeModelInitializer initializer : initializers) { - initializer.initializeModuleModel(this); - } + initializers.stream() + .sorted(OrderedObjectCompareUtils::compareByOrder) + .forEach(initializer -> initializer.initializeModuleModel(this)); Assert.notNull(getServiceRepository(), "ModuleServiceRepository can not be null"); Assert.notNull(getConfigManager(), "ModuleConfigManager can not be null"); Assert.assertTrue(getConfigManager().isInitialized(), "ModuleConfigManager can not be initialized"); diff --git a/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java b/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java index d977ee102c2..562730d8e46 100644 --- a/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java +++ b/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.metrics; +import org.apache.dubbo.common.Ordered; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.event.DubboListener; @@ -28,7 +29,7 @@ import java.util.List; -public class MetricsScopeModelInitializer implements ScopeModelInitializer { +public class MetricsScopeModelInitializer implements ScopeModelInitializer, Ordered { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @@ -51,4 +52,9 @@ public void initializeApplicationModel(ApplicationModel applicationModel) { @Override public void initializeModuleModel(ModuleModel moduleModel) {} + + @Override + public int getOrder() { + return 1; + } } From 7fd5b1ad029d87ebd4435e0f4f9c1717ab07b9c9 Mon Sep 17 00:00:00 2001 From: walklown Date: Sat, 8 Jun 2024 14:12:52 +0800 Subject: [PATCH 06/12] Revert "ScopeModelInitializer supports Ordered sorting" This reverts commit 7eb1e23c9e0e3bf5996593a7e76de405ed5eec36. --- .../java/org/apache/dubbo/common/Ordered.java | 28 ------------- .../dubbo/common/event/DubboEventBus.java | 12 +----- .../utils/OrderedObjectCompareUtils.java | 40 ------------------- .../dubbo/rpc/model/ApplicationModel.java | 7 ++-- .../dubbo/rpc/model/FrameworkModel.java | 7 ++-- .../apache/dubbo/rpc/model/ModuleModel.java | 7 ++-- .../metrics/MetricsScopeModelInitializer.java | 8 +--- 7 files changed, 12 insertions(+), 97 deletions(-) delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java deleted file mode 100644 index 3c2d995296b..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.common; - -public interface Ordered { - - int HIGHEST_PRECEDENCE = Integer.MIN_VALUE; - - int LOWEST_PRECEDENCE = Integer.MAX_VALUE; - - default int getOrder() { - return 0; - } -} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java index 60b4a57851b..444b80eb10d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java @@ -54,17 +54,9 @@ private DubboEventBus() {} */ public static void addListener(ApplicationModel applicationModel, DubboListener listener) { if (listener instanceof DubboLifecycleListener) { - DubboLifecycleEventMulticaster lifecycleEventMulticaster = getLifecycleMulticaster(applicationModel); - if (lifecycleEventMulticaster == null) { - throw new RuntimeException("DubboLifecycleEventMulticaster has not been initialized"); - } - lifecycleEventMulticaster.addListener(listener); - } - DubboEventMulticaster multicaster = getMulticaster(applicationModel); - if (multicaster == null) { - throw new RuntimeException("DubboEventMulticaster has not been initialized"); + getLifecycleMulticaster(applicationModel).addListener(listener); } - multicaster.addListener(listener); + getMulticaster(applicationModel).addListener(listener); } /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java deleted file mode 100644 index 9e24f9d7bcf..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.common.utils; - -import org.apache.dubbo.common.Ordered; - -public class OrderedObjectCompareUtils { - - public static int compareByOrder(Object o1, Object o2) { - boolean o1Ordered = o1 instanceof Ordered; - boolean o2Ordered = o2 instanceof Ordered; - if (!o1Ordered) { - if (!o2Ordered) { - return 0; - } else { - return -1; - } - } else { - if (!o2Ordered) { - return 1; - } else { - return Integer.compare(((Ordered) o1).getOrder(), ((Ordered) o2).getOrder()); - } - } - } -} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java index 8474638ca2c..1971cf25e70 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java @@ -25,7 +25,6 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.Assert; -import org.apache.dubbo.common.utils.OrderedObjectCompareUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -124,9 +123,9 @@ protected ApplicationModel(FrameworkModel frameworkModel, boolean isInternal) { ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); - initializers.stream() - .sorted(OrderedObjectCompareUtils::compareByOrder) - .forEach(initializer -> initializer.initializeApplicationModel(this)); + for (ScopeModelInitializer initializer : initializers) { + initializer.initializeApplicationModel(this); + } Assert.notNull(getApplicationServiceRepository(), "ApplicationServiceRepository can not be null"); Assert.notNull(getApplicationConfigManager(), "ApplicationConfigManager can not be null"); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java index bcd6ec3b3bc..e5fb2b52ff4 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java @@ -24,7 +24,6 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.GlobalResourcesRepository; import org.apache.dubbo.common.utils.Assert; -import org.apache.dubbo.common.utils.OrderedObjectCompareUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; @@ -95,9 +94,9 @@ public FrameworkModel() { ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); - initializers.stream() - .sorted(OrderedObjectCompareUtils::compareByOrder) - .forEach(initializer -> initializer.initializeFrameworkModel(this)); + for (ScopeModelInitializer initializer : initializers) { + initializer.initializeFrameworkModel(this); + } internalApplicationModel = new ApplicationModel(this, true); internalApplicationModel diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java index aea6c241cce..9af38b04289 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java @@ -28,7 +28,6 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.ClassUtils; -import org.apache.dubbo.common.utils.OrderedObjectCompareUtils; import org.apache.dubbo.config.context.ModuleConfigManager; import java.util.HashMap; @@ -73,9 +72,9 @@ protected ModuleModel(ApplicationModel applicationModel, boolean isInternal) { ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); - initializers.stream() - .sorted(OrderedObjectCompareUtils::compareByOrder) - .forEach(initializer -> initializer.initializeModuleModel(this)); + for (ScopeModelInitializer initializer : initializers) { + initializer.initializeModuleModel(this); + } Assert.notNull(getServiceRepository(), "ModuleServiceRepository can not be null"); Assert.notNull(getConfigManager(), "ModuleConfigManager can not be null"); Assert.assertTrue(getConfigManager().isInitialized(), "ModuleConfigManager can not be initialized"); diff --git a/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java b/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java index 562730d8e46..d977ee102c2 100644 --- a/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java +++ b/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metrics; -import org.apache.dubbo.common.Ordered; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.event.DubboListener; @@ -29,7 +28,7 @@ import java.util.List; -public class MetricsScopeModelInitializer implements ScopeModelInitializer, Ordered { +public class MetricsScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @@ -52,9 +51,4 @@ public void initializeApplicationModel(ApplicationModel applicationModel) { @Override public void initializeModuleModel(ModuleModel moduleModel) {} - - @Override - public int getOrder() { - return 1; - } } From 3b67620c1f457337aa39492ffcf05485f7075ee4 Mon Sep 17 00:00:00 2001 From: walklown Date: Sat, 8 Jun 2024 14:12:54 +0800 Subject: [PATCH 07/12] Revert "Allows extension of DubboEventMulticaster" This reverts commit 19db740ec7f09c6488bfd1915e6d853635549920. --- .../event/CompositeDubboEventMulticaster.java | 49 --------------- ...mpositeDubboLifecycleEventMulticaster.java | 63 ------------------- ...java => DefaultDubboEventMulticaster.java} | 5 +- ... DubboApplicationMulticasterRegistry.java} | 28 +-------- .../dubbo/common/event/DubboEventBus.java | 28 ++------- .../common/event/DubboEventMulticaster.java | 3 - ...e.dubbo.common.event.DubboEventMulticaster | 1 - ...ache.dubbo.rpc.model.ScopeModelInitializer | 2 +- .../metrics/DefaultMetricsServiceTest.java | 12 +--- .../AggregateMetricsCollectorTest.java | 12 +--- .../sample/ThreadPoolMetricsSamplerTest.java | 18 ++---- .../collector/RegistryMetricsTest.java | 13 +--- 12 files changed, 25 insertions(+), 209 deletions(-) delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboEventMulticaster.java delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboLifecycleEventMulticaster.java rename dubbo-common/src/main/java/org/apache/dubbo/common/event/{DefaultDubboLifecycleEventMulticaster.java => DefaultDubboEventMulticaster.java} (96%) rename dubbo-common/src/main/java/org/apache/dubbo/common/event/{DubboMulticasterScopeModelInitializer.java => DubboApplicationMulticasterRegistry.java} (54%) delete mode 100644 dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.event.DubboEventMulticaster diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboEventMulticaster.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboEventMulticaster.java deleted file mode 100644 index 4432c2a0d33..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboEventMulticaster.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.common.event; - -import java.util.List; - -public class CompositeDubboEventMulticaster implements DubboEventMulticaster { - - private final List multicasterList; - - public CompositeDubboEventMulticaster(List multicasterList) { - this.multicasterList = multicasterList; - } - - @Override - public void addListener(DubboListener listener) { - for (DubboEventMulticaster dubboEventMulticaster : multicasterList) { - dubboEventMulticaster.addListener(listener); - } - } - - @Override - public void removeListener(DubboListener listener) { - for (DubboEventMulticaster dubboEventMulticaster : multicasterList) { - dubboEventMulticaster.removeListener(listener); - } - } - - @Override - public void publishEvent(DubboEvent event) { - for (DubboEventMulticaster dubboEventMulticaster : multicasterList) { - dubboEventMulticaster.publishEvent(event); - } - } -} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboLifecycleEventMulticaster.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboLifecycleEventMulticaster.java deleted file mode 100644 index 5b496813dc9..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/CompositeDubboLifecycleEventMulticaster.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.common.event; - -import java.util.List; - -public class CompositeDubboLifecycleEventMulticaster implements DubboLifecycleEventMulticaster { - - private final List multicasterList; - - public CompositeDubboLifecycleEventMulticaster(List multicasterList) { - this.multicasterList = multicasterList; - } - - @Override - public void publishBeforeEvent(DubboEvent event) { - for (DubboLifecycleEventMulticaster multicaster : multicasterList) { - multicaster.publishBeforeEvent(event); - } - } - - @Override - public void publishErrorEvent(DubboEvent event) { - for (DubboLifecycleEventMulticaster multicaster : multicasterList) { - multicaster.publishErrorEvent(event); - } - } - - @Override - public void addListener(DubboListener listener) { - for (DubboLifecycleEventMulticaster multicaster : multicasterList) { - multicaster.addListener(listener); - } - } - - @Override - public void removeListener(DubboListener listener) { - for (DubboLifecycleEventMulticaster multicaster : multicasterList) { - multicaster.removeListener(listener); - } - } - - @Override - public void publishEvent(DubboEvent event) { - for (DubboLifecycleEventMulticaster multicaster : multicasterList) { - multicaster.publishEvent(event); - } - } -} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboLifecycleEventMulticaster.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java similarity index 96% rename from dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboLifecycleEventMulticaster.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java index f1b70f5c8f5..06a37292f10 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboLifecycleEventMulticaster.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java @@ -16,16 +16,13 @@ */ package org.apache.dubbo.common.event; -import org.apache.dubbo.common.extension.Activate; - import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; -@Activate -public class DefaultDubboLifecycleEventMulticaster implements DubboLifecycleEventMulticaster { +public class DefaultDubboEventMulticaster implements DubboLifecycleEventMulticaster { /** * All registered subscribers, indexed by event type. diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboMulticasterScopeModelInitializer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java similarity index 54% rename from dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboMulticasterScopeModelInitializer.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java index 6808f1f4b65..de750ea7511 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboMulticasterScopeModelInitializer.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java @@ -17,22 +17,18 @@ package org.apache.dubbo.common.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; -import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; -import java.util.ArrayList; -import java.util.List; - /** * Initialize {@link DubboLifecycleEventMulticaster} for {@link ApplicationModel} * * @see DubboLifecycleEventMulticaster * @since 3.3.0 */ -public class DubboMulticasterScopeModelInitializer implements ScopeModelInitializer { +public class DubboApplicationMulticasterRegistry implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @@ -40,27 +36,7 @@ public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); - - List lifecycleEventMulticasters = new ArrayList<>(); - CompositeDubboLifecycleEventMulticaster lifecycleEventMulticaster = - new CompositeDubboLifecycleEventMulticaster(lifecycleEventMulticasters); - - List eventMulticasters = new ArrayList<>(); - CompositeDubboEventMulticaster dubboEventMulticaster = new CompositeDubboEventMulticaster(eventMulticasters); - - ExtensionLoader extensionLoader = - applicationModel.getExtensionLoader(DubboEventMulticaster.class); - if (extensionLoader != null) { - for (DubboEventMulticaster eventMulticaster : extensionLoader.getActivateExtensions()) { - eventMulticasters.add(eventMulticaster); - if (eventMulticaster instanceof DubboLifecycleEventMulticaster) { - lifecycleEventMulticasters.add((DubboLifecycleEventMulticaster) eventMulticaster); - } - } - } - - beanFactory.registerBean(lifecycleEventMulticaster); - beanFactory.registerBean(dubboEventMulticaster); + beanFactory.registerBean(DefaultDubboEventMulticaster.class); } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java index 444b80eb10d..66890853e48 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java @@ -39,12 +39,9 @@ public class DubboEventBus { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboEventBus.class); - private static final ConcurrentHashMap cachedMulticasterMap = + private static final ConcurrentHashMap cachedMulticasterMap = new ConcurrentHashMap<>(); - private static final ConcurrentHashMap - cachedLifecycleMulticasterMap = new ConcurrentHashMap<>(); - private DubboEventBus() {} /** @@ -53,9 +50,6 @@ private DubboEventBus() {} * @param listener object whose subscriber methods should be registered. */ public static void addListener(ApplicationModel applicationModel, DubboListener listener) { - if (listener instanceof DubboLifecycleListener) { - getLifecycleMulticaster(applicationModel).addListener(listener); - } getMulticaster(applicationModel).addListener(listener); } @@ -66,9 +60,6 @@ public static void addListener(ApplicationModel applicationModel, DubboListener< * @throws IllegalArgumentException if the object was not previously registered. */ public static void removeListener(ApplicationModel applicationModel, DubboListener listener) { - if (listener instanceof DubboLifecycleListener) { - getLifecycleMulticaster(applicationModel).removeListener(listener); - } getMulticaster(applicationModel).removeListener(listener); } @@ -140,7 +131,7 @@ private static void tryInvoke(Runnable runnable) { * eventSaveRunner saves the event, so that the calculation rt is introverted */ public static void before(DubboEvent event) { - tryInvoke(() -> getLifecycleMulticaster(event.getApplicationModel()).publishBeforeEvent(event)); + tryInvoke(() -> getMulticaster(event.getApplicationModel()).publishBeforeEvent(event)); } @SuppressWarnings({"unchecked", "rawtypes"}) @@ -149,25 +140,18 @@ public static void after(DubboEvent event, Object result) { if (event instanceof CustomAfterPost) { ((CustomAfterPost) event).customAfterPost(result); } - getLifecycleMulticaster(event.getApplicationModel()).publishEvent(event); + getMulticaster(event.getApplicationModel()).publishEvent(event); }); } public static void error(DubboEvent event) { - tryInvoke(() -> getLifecycleMulticaster(event.getApplicationModel()).publishErrorEvent(event)); + tryInvoke(() -> getMulticaster(event.getApplicationModel()).publishErrorEvent(event)); } - private static DubboEventMulticaster getMulticaster(ApplicationModel applicationModel) { + private static DubboLifecycleEventMulticaster getMulticaster(ApplicationModel applicationModel) { return cachedMulticasterMap.computeIfAbsent(applicationModel, t -> { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); - return beanFactory.getBean(CompositeDubboEventMulticaster.class); - }); - } - - private static DubboLifecycleEventMulticaster getLifecycleMulticaster(ApplicationModel applicationModel) { - return cachedLifecycleMulticasterMap.computeIfAbsent(applicationModel, t -> { - ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); - return beanFactory.getBean(CompositeDubboLifecycleEventMulticaster.class); + return beanFactory.getBean(DubboLifecycleEventMulticaster.class); }); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java index 640c1d5710c..ecfae62a689 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.common.event; -import org.apache.dubbo.common.extension.SPI; - /** * Dispatches events to listeners, and provides ways for listeners to register themselves. * @@ -25,7 +23,6 @@ * @see DubboEvent * @see DubboListener */ -@SPI public interface DubboEventMulticaster { /** diff --git a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.event.DubboEventMulticaster b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.event.DubboEventMulticaster deleted file mode 100644 index 61f51901319..00000000000 --- a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.event.DubboEventMulticaster +++ /dev/null @@ -1 +0,0 @@ -default=org.apache.dubbo.common.event.DefaultDubboLifecycleEventMulticaster \ No newline at end of file diff --git a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer index f2258d26986..956665085f0 100644 --- a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer +++ b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer @@ -1,2 +1,2 @@ dubbo-common=org.apache.dubbo.common.CommonScopeModelInitializer -dubbo-multicaster-init=org.apache.dubbo.common.event.DubboMulticasterScopeModelInitializer \ No newline at end of file +application-multicaster-registry=org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry \ No newline at end of file diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java index db5feb959df..cb8fe656416 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java @@ -17,9 +17,8 @@ package org.apache.dubbo.metrics; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; -import org.apache.dubbo.common.event.CompositeDubboEventMulticaster; -import org.apache.dubbo.common.event.CompositeDubboLifecycleEventMulticaster; -import org.apache.dubbo.common.event.DefaultDubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; +import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; @@ -55,12 +54,7 @@ public void setUp() { when(applicationModel.getBeanFactory()).thenReturn(beanFactory); when(beanFactory.getBeansOfType(MetricsCollector.class)) .thenReturn(Collections.singletonList(metricsCollector)); - when(beanFactory.getBean(CompositeDubboEventMulticaster.class)) - .thenReturn(new CompositeDubboEventMulticaster( - Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); - when(beanFactory.getBean(CompositeDubboLifecycleEventMulticaster.class)) - .thenReturn(new CompositeDubboLifecycleEventMulticaster( - Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); + when(beanFactory.getBean(DubboLifecycleEventMulticaster.class)).thenReturn(new DefaultDubboEventMulticaster()); defaultMetricsService = new DefaultMetricsService(applicationModel); } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java index a9c905f71a7..c6fbfc0c517 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java @@ -19,10 +19,9 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.common.event.CompositeDubboEventMulticaster; -import org.apache.dubbo.common.event.CompositeDubboLifecycleEventMulticaster; -import org.apache.dubbo.common.event.DefaultDubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; import org.apache.dubbo.common.event.DubboEventBus; +import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; import org.apache.dubbo.common.event.DubboListener; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ReflectionUtils; @@ -213,12 +212,7 @@ public void testQPS() { when(applicationModel.getApplicationConfigManager()).thenReturn(configManager); when(applicationModel.getBeanFactory()).thenReturn(beanFactory); - when(beanFactory.getBean(CompositeDubboEventMulticaster.class)) - .thenReturn(new CompositeDubboEventMulticaster( - Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); - when(beanFactory.getBean(CompositeDubboLifecycleEventMulticaster.class)) - .thenReturn(new CompositeDubboLifecycleEventMulticaster( - Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); + when(beanFactory.getBean(DubboLifecycleEventMulticaster.class)).thenReturn(new DefaultDubboEventMulticaster()); DefaultMetricsCollector defaultMetricsCollector = new DefaultMetricsCollector(applicationModel); when(beanFactory.getBean(DefaultMetricsCollector.class)).thenReturn(defaultMetricsCollector); when(configManager.getMetrics()).thenReturn(Optional.of(metricsConfig)); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java index 7c6a2657e81..b5e3dec2540 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java @@ -17,10 +17,9 @@ package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; -import org.apache.dubbo.common.event.CompositeDubboEventMulticaster; -import org.apache.dubbo.common.event.CompositeDubboLifecycleEventMulticaster; -import org.apache.dubbo.common.event.DefaultDubboLifecycleEventMulticaster; -import org.apache.dubbo.common.event.DubboMulticasterScopeModelInitializer; +import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; +import org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry; +import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; @@ -31,7 +30,6 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import java.lang.reflect.Field; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -54,7 +52,7 @@ public class ThreadPoolMetricsSamplerTest { ThreadPoolMetricsSampler sampler; - private DubboMulticasterScopeModelInitializer multicasterInitializer = new DubboMulticasterScopeModelInitializer(); + private DubboApplicationMulticasterRegistry multicasterRegistry = new DubboApplicationMulticasterRegistry(); @BeforeEach void setUp() { @@ -144,12 +142,8 @@ public void setUp2() { MockitoAnnotations.openMocks(this); when(applicationModel.getBeanFactory()).thenReturn(scopeBeanFactory); - when(scopeBeanFactory.getBean(CompositeDubboEventMulticaster.class)) - .thenReturn(new CompositeDubboEventMulticaster( - Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); - when(scopeBeanFactory.getBean(CompositeDubboLifecycleEventMulticaster.class)) - .thenReturn(new CompositeDubboLifecycleEventMulticaster( - Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); + when(scopeBeanFactory.getBean(DubboLifecycleEventMulticaster.class)) + .thenReturn(new DefaultDubboEventMulticaster()); collector = new DefaultMetricsCollector(applicationModel); sampler2 = new ThreadPoolMetricsSampler(collector); diff --git a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java index 2612a620a73..a68be08887c 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java @@ -17,9 +17,8 @@ package org.apache.dubbo.metrics.registry.metrics.collector; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; -import org.apache.dubbo.common.event.CompositeDubboEventMulticaster; -import org.apache.dubbo.common.event.CompositeDubboLifecycleEventMulticaster; -import org.apache.dubbo.common.event.DefaultDubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; +import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -35,7 +34,6 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; @@ -66,12 +64,7 @@ public class RegistryMetricsTest { void setUp() { this.applicationModel = getApplicationModel(); ScopeBeanFactory beanFactory = Mockito.mock(ScopeBeanFactory.class); - when(beanFactory.getBean(CompositeDubboEventMulticaster.class)) - .thenReturn(new CompositeDubboEventMulticaster( - Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); - when(beanFactory.getBean(CompositeDubboLifecycleEventMulticaster.class)) - .thenReturn(new CompositeDubboLifecycleEventMulticaster( - Collections.singletonList(new DefaultDubboLifecycleEventMulticaster()))); + when(beanFactory.getBean(DubboLifecycleEventMulticaster.class)).thenReturn(new DefaultDubboEventMulticaster()); this.collector = getTestCollector(this.applicationModel); this.collector.setCollectEnabled(true); } From 3f1c88d4b706ebf7e3af0fea82febca8d14dccd2 Mon Sep 17 00:00:00 2001 From: walklown Date: Sat, 8 Jun 2024 14:18:47 +0800 Subject: [PATCH 08/12] rename DubboApplicationMulticasterRegistry --- ...gistry.java => DubboMulticasterScopeModelInitializer.java} | 2 +- .../internal/org.apache.dubbo.rpc.model.ScopeModelInitializer | 2 +- .../collector/sample/ThreadPoolMetricsSamplerTest.java | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) rename dubbo-common/src/main/java/org/apache/dubbo/common/event/{DubboApplicationMulticasterRegistry.java => DubboMulticasterScopeModelInitializer.java} (95%) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboMulticasterScopeModelInitializer.java similarity index 95% rename from dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboMulticasterScopeModelInitializer.java index de750ea7511..24ab6ed0626 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboApplicationMulticasterRegistry.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboMulticasterScopeModelInitializer.java @@ -28,7 +28,7 @@ * @see DubboLifecycleEventMulticaster * @since 3.3.0 */ -public class DubboApplicationMulticasterRegistry implements ScopeModelInitializer { +public class DubboMulticasterScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} diff --git a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer index 956665085f0..57bb7d1398c 100644 --- a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer +++ b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer @@ -1,2 +1,2 @@ dubbo-common=org.apache.dubbo.common.CommonScopeModelInitializer -application-multicaster-registry=org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry \ No newline at end of file +dubbo-multicaster-init=org.apache.dubbo.common.event.DubboMulticasterScopeModelInitializer diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java index b5e3dec2540..bacbd7502ba 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java @@ -18,7 +18,7 @@ import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; -import org.apache.dubbo.common.event.DubboApplicationMulticasterRegistry; +import org.apache.dubbo.common.event.DubboMulticasterScopeModelInitializer; import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.store.DataStore; @@ -52,7 +52,7 @@ public class ThreadPoolMetricsSamplerTest { ThreadPoolMetricsSampler sampler; - private DubboApplicationMulticasterRegistry multicasterRegistry = new DubboApplicationMulticasterRegistry(); + private DubboMulticasterScopeModelInitializer multicasterRegistry = new DubboMulticasterScopeModelInitializer(); @BeforeEach void setUp() { From 76484fc8d20e29ceeafff687ef817b411123ac5f Mon Sep 17 00:00:00 2001 From: walklown Date: Fri, 7 Jun 2024 01:40:45 +0800 Subject: [PATCH 09/12] ScopeModelInitializer supports Ordered sorting --- .../java/org/apache/dubbo/common/Ordered.java | 28 +++++++++++++ .../utils/OrderedObjectCompareUtils.java | 40 +++++++++++++++++++ .../dubbo/rpc/model/ApplicationModel.java | 7 ++-- .../dubbo/rpc/model/FrameworkModel.java | 7 ++-- .../apache/dubbo/rpc/model/ModuleModel.java | 7 ++-- .../sample/ThreadPoolMetricsSamplerTest.java | 2 +- .../metrics/MetricsScopeModelInitializer.java | 8 +++- 7 files changed, 88 insertions(+), 11 deletions(-) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java new file mode 100644 index 00000000000..3c2d995296b --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java @@ -0,0 +1,28 @@ +/* + * 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.common; + +public interface Ordered { + + int HIGHEST_PRECEDENCE = Integer.MIN_VALUE; + + int LOWEST_PRECEDENCE = Integer.MAX_VALUE; + + default int getOrder() { + return 0; + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java new file mode 100644 index 00000000000..9e24f9d7bcf --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java @@ -0,0 +1,40 @@ +/* + * 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.common.utils; + +import org.apache.dubbo.common.Ordered; + +public class OrderedObjectCompareUtils { + + public static int compareByOrder(Object o1, Object o2) { + boolean o1Ordered = o1 instanceof Ordered; + boolean o2Ordered = o2 instanceof Ordered; + if (!o1Ordered) { + if (!o2Ordered) { + return 0; + } else { + return -1; + } + } else { + if (!o2Ordered) { + return 1; + } else { + return Integer.compare(((Ordered) o1).getOrder(), ((Ordered) o2).getOrder()); + } + } + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java index 1971cf25e70..8474638ca2c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java @@ -25,6 +25,7 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.Assert; +import org.apache.dubbo.common.utils.OrderedObjectCompareUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -123,9 +124,9 @@ protected ApplicationModel(FrameworkModel frameworkModel, boolean isInternal) { ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); - for (ScopeModelInitializer initializer : initializers) { - initializer.initializeApplicationModel(this); - } + initializers.stream() + .sorted(OrderedObjectCompareUtils::compareByOrder) + .forEach(initializer -> initializer.initializeApplicationModel(this)); Assert.notNull(getApplicationServiceRepository(), "ApplicationServiceRepository can not be null"); Assert.notNull(getApplicationConfigManager(), "ApplicationConfigManager can not be null"); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java index e5fb2b52ff4..bcd6ec3b3bc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java @@ -24,6 +24,7 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.GlobalResourcesRepository; import org.apache.dubbo.common.utils.Assert; +import org.apache.dubbo.common.utils.OrderedObjectCompareUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; @@ -94,9 +95,9 @@ public FrameworkModel() { ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); - for (ScopeModelInitializer initializer : initializers) { - initializer.initializeFrameworkModel(this); - } + initializers.stream() + .sorted(OrderedObjectCompareUtils::compareByOrder) + .forEach(initializer -> initializer.initializeFrameworkModel(this)); internalApplicationModel = new ApplicationModel(this, true); internalApplicationModel diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java index 9af38b04289..aea6c241cce 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java @@ -28,6 +28,7 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.ClassUtils; +import org.apache.dubbo.common.utils.OrderedObjectCompareUtils; import org.apache.dubbo.config.context.ModuleConfigManager; import java.util.HashMap; @@ -72,9 +73,9 @@ protected ModuleModel(ApplicationModel applicationModel, boolean isInternal) { ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); - for (ScopeModelInitializer initializer : initializers) { - initializer.initializeModuleModel(this); - } + initializers.stream() + .sorted(OrderedObjectCompareUtils::compareByOrder) + .forEach(initializer -> initializer.initializeModuleModel(this)); Assert.notNull(getServiceRepository(), "ModuleServiceRepository can not be null"); Assert.notNull(getConfigManager(), "ModuleConfigManager can not be null"); Assert.assertTrue(getConfigManager().isInitialized(), "ModuleConfigManager can not be initialized"); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java index bacbd7502ba..c36fc8bbdae 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java @@ -18,8 +18,8 @@ import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; -import org.apache.dubbo.common.event.DubboMulticasterScopeModelInitializer; import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.DubboMulticasterScopeModelInitializer; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; diff --git a/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java b/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java index d977ee102c2..562730d8e46 100644 --- a/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java +++ b/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.metrics; +import org.apache.dubbo.common.Ordered; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.event.DubboListener; @@ -28,7 +29,7 @@ import java.util.List; -public class MetricsScopeModelInitializer implements ScopeModelInitializer { +public class MetricsScopeModelInitializer implements ScopeModelInitializer, Ordered { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @@ -51,4 +52,9 @@ public void initializeApplicationModel(ApplicationModel applicationModel) { @Override public void initializeModuleModel(ModuleModel moduleModel) {} + + @Override + public int getOrder() { + return 1; + } } From 41b26678640bead2476084f998e6a62cd1a15e55 Mon Sep 17 00:00:00 2001 From: walklown Date: Sun, 16 Jun 2024 16:02:29 +0800 Subject: [PATCH 10/12] remote dubbo-metrics-starter split MetricsServiceExporter from DefaultApplicationDeployer split monitor from metrics module --- .artifacts | 3 +- dubbo-config/dubbo-config-api/pom.xml | 2 +- .../deploy/DefaultApplicationDeployer.java | 42 ++----------- .../PreDestroyApplicationInstanceEvent.java} | 23 ++----- .../PrepareApplicationInstanceEvent.java | 27 ++++++++ ...mon.metrics.service.MetricsServiceExporter | 1 - dubbo-distribution/dubbo-all-shaded/pom.xml | 12 +--- dubbo-distribution/dubbo-all/pom.xml | 12 +--- dubbo-distribution/dubbo-bom/pom.xml | 7 +-- dubbo-distribution/dubbo-core-spi/pom.xml | 3 +- dubbo-metrics/dubbo-metrics-api/pom.xml | 5 -- dubbo-metrics/dubbo-metrics-default/pom.xml | 5 ++ .../metrics/MetricsScopeModelInitializer.java | 0 .../metrics/MetricsServiceInitializer.java | 45 ++++++++------ ...stroyApplicationInstanceEventListener.java | 37 +++++++++++ ...epareApplicationInstanceEventListener.java | 54 ++++++++++++++++ .../service/MetricsServiceExporter.java | 0 .../internal/org.apache.dubbo.rpc.Filter | 1 - ...che.dubbo.rpc.cluster.filter.ClusterFilter | 1 - ...ache.dubbo.rpc.model.ScopeModelInitializer | 0 .../metrics/collector/CollectorInitTest.java | 0 .../pom.xml | 12 +++- .../org/apache/dubbo/monitor/Constants.java | 0 .../org/apache/dubbo/monitor/Monitor.java | 0 .../apache/dubbo/monitor/MonitorFactory.java | 0 .../apache/dubbo/monitor/MonitorService.java | 0 .../monitor/support/MonitorClusterFilter.java | 0 .../dubbo/monitor/support/MonitorFilter.java | 0 .../internal/org.apache.dubbo.rpc.Filter | 1 + ...che.dubbo.rpc.cluster.filter.ClusterFilter | 1 + .../monitor/support/MonitorFilterTest.java | 0 dubbo-metrics/dubbo-metrics-starter/pom.xml | 62 ------------------- dubbo-metrics/pom.xml | 3 +- dubbo-test/dubbo-dependencies-all/pom.xml | 7 +-- 34 files changed, 181 insertions(+), 185 deletions(-) rename dubbo-config/dubbo-config-api/src/{test/java/org/apache/dubbo/config/metrics/MockMetricsServiceExporter.java => main/java/org/apache/dubbo/config/deploy/event/PreDestroyApplicationInstanceEvent.java} (65%) create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PrepareApplicationInstanceEvent.java delete mode 100644 dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.common.metrics.service.MetricsServiceExporter rename dubbo-metrics/{dubbo-metrics-starter => dubbo-metrics-default}/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java (100%) rename dubbo-metrics/{dubbo-metrics-starter => dubbo-metrics-default}/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java (83%) create mode 100644 dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PreDestroyApplicationInstanceEventListener.java create mode 100644 dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PrepareApplicationInstanceEventListener.java rename dubbo-metrics/{dubbo-metrics-annotation => dubbo-metrics-default}/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java (100%) rename dubbo-metrics/{dubbo-metrics-starter => dubbo-metrics-default}/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer (100%) rename dubbo-metrics/{dubbo-metrics-starter => dubbo-metrics-default}/src/test/java/org/apache/dubbo/metrics/collector/CollectorInitTest.java (100%) rename dubbo-metrics/{dubbo-metrics-annotation => dubbo-metrics-monitor}/pom.xml (80%) rename dubbo-metrics/{dubbo-metrics-annotation => dubbo-metrics-monitor}/src/main/java/org/apache/dubbo/monitor/Constants.java (100%) rename dubbo-metrics/{dubbo-metrics-annotation => dubbo-metrics-monitor}/src/main/java/org/apache/dubbo/monitor/Monitor.java (100%) rename dubbo-metrics/{dubbo-metrics-annotation => dubbo-metrics-monitor}/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java (100%) rename dubbo-metrics/{dubbo-metrics-annotation => dubbo-metrics-monitor}/src/main/java/org/apache/dubbo/monitor/MonitorService.java (100%) rename dubbo-metrics/{dubbo-metrics-default => dubbo-metrics-monitor}/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java (100%) rename dubbo-metrics/{dubbo-metrics-default => dubbo-metrics-monitor}/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java (100%) create mode 100644 dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter create mode 100644 dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter rename dubbo-metrics/{dubbo-metrics-default => dubbo-metrics-monitor}/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java (100%) delete mode 100644 dubbo-metrics/dubbo-metrics-starter/pom.xml diff --git a/.artifacts b/.artifacts index eb3010b473c..61dc29d220e 100644 --- a/.artifacts +++ b/.artifacts @@ -59,8 +59,7 @@ dubbo-metrics-prometheus dubbo-metrics-registry dubbo-metrics-config-center dubbo-metrics-netty -dubbo-metrics-annotation -dubbo-metrics-starter +dubbo-metrics-monitor dubbo-native dubbo-parent dubbo-plugin diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 62b87e06df2..0b46d30253d 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -38,7 +38,7 @@ org.apache.dubbo - dubbo-metrics-annotation + dubbo-metrics-monitor ${project.parent.version} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java index 09b62bf00f1..8f806a6e648 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java @@ -46,16 +46,16 @@ import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.DubboShutdownHook; import org.apache.dubbo.config.MetadataReportConfig; -import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.deploy.event.ApplicationLoadedEvent; import org.apache.dubbo.config.deploy.event.ApplicationStartedEvent; +import org.apache.dubbo.config.deploy.event.PreDestroyApplicationInstanceEvent; +import org.apache.dubbo.config.deploy.event.PrepareApplicationInstanceEvent; import org.apache.dubbo.config.utils.CompositeReferenceCache; import org.apache.dubbo.config.utils.ConfigValidationUtils; import org.apache.dubbo.metadata.report.MetadataReportFactory; import org.apache.dubbo.metadata.report.MetadataReportInstance; -import org.apache.dubbo.metrics.service.MetricsServiceExporter; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils; @@ -684,7 +684,7 @@ public void prepareApplicationInstance(ModuleModel moduleModel) { } // export MetricsService - exportMetricsService(); + DubboEventBus.publish(new PrepareApplicationInstanceEvent(applicationModel)); if (moduleModel.getDeployer().hasRegistryInteraction()) { ApplicationConfig applicationConfig = configManager.getApplicationOrElseThrow(); @@ -736,40 +736,6 @@ public void prepareInternalModule() { } } - private void exportMetricsService() { - MetricsServiceExporter metricsServiceExporter = - applicationModel.getBeanFactory().getBean(MetricsServiceExporter.class); - boolean exportMetrics = applicationModel - .getApplicationConfigManager() - .getMetrics() - .map(MetricsConfig::getExportMetricsService) - .orElse(true); - if (exportMetrics && metricsServiceExporter != null) { - try { - metricsServiceExporter.export(); - } catch (Exception e) { - logger.error( - LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION, - "", - "", - "exportMetricsService an exception occurred when handle starting event", - e); - } - } - } - - private void unexportMetricsService() { - MetricsServiceExporter metricsServiceExporter = - applicationModel.getBeanFactory().getBean(MetricsServiceExporter.class); - if (metricsServiceExporter != null) { - try { - metricsServiceExporter.unexport(); - } catch (Exception ignored) { - // ignored - } - } - } - private boolean hasExportedServices() { for (ModuleModel moduleModel : applicationModel.getModuleModels()) { if (CollectionUtils.isNotEmpty(moduleModel.getConfigManager().getServices())) { @@ -1002,7 +968,7 @@ public void preDestroy() { unregisterServiceInstance(); - unexportMetricsService(); + DubboEventBus.publish(new PreDestroyApplicationInstanceEvent(applicationModel)); unRegisterShutdownHook(); if (asyncMetadataFuture != null) { diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metrics/MockMetricsServiceExporter.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PreDestroyApplicationInstanceEvent.java similarity index 65% rename from dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metrics/MockMetricsServiceExporter.java rename to dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PreDestroyApplicationInstanceEvent.java index 91c956425f2..6e215575c9c 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metrics/MockMetricsServiceExporter.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PreDestroyApplicationInstanceEvent.java @@ -14,25 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.config.metrics; +package org.apache.dubbo.config.deploy.event; -import org.apache.dubbo.metrics.service.MetricsServiceExporter; +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; -/** - * Export metrics service - */ -public class MockMetricsServiceExporter implements MetricsServiceExporter { - - @Override - public void init() {} - - @Override - public MetricsServiceExporter export() { - return null; - } +public class PreDestroyApplicationInstanceEvent extends DubboEvent { - @Override - public MetricsServiceExporter unexport() { - return null; + public PreDestroyApplicationInstanceEvent(ApplicationModel source) { + super(source); } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PrepareApplicationInstanceEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PrepareApplicationInstanceEvent.java new file mode 100644 index 00000000000..cdead7419a7 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PrepareApplicationInstanceEvent.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.deploy.event; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class PrepareApplicationInstanceEvent extends DubboEvent { + + public PrepareApplicationInstanceEvent(ApplicationModel source) { + super(source); + } +} diff --git a/dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.common.metrics.service.MetricsServiceExporter b/dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.common.metrics.service.MetricsServiceExporter deleted file mode 100644 index 6d35362e1c0..00000000000 --- a/dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.common.metrics.service.MetricsServiceExporter +++ /dev/null @@ -1 +0,0 @@ -default=org.apache.dubbo.config.metrics.MockMetricsServiceExporter diff --git a/dubbo-distribution/dubbo-all-shaded/pom.xml b/dubbo-distribution/dubbo-all-shaded/pom.xml index 5436856f95e..1098bb08f5a 100644 --- a/dubbo-distribution/dubbo-all-shaded/pom.xml +++ b/dubbo-distribution/dubbo-all-shaded/pom.xml @@ -174,7 +174,7 @@ org.apache.dubbo - dubbo-metrics-annotation + dubbo-metrics-monitor ${project.version} compile true @@ -193,13 +193,6 @@ compile true - - org.apache.dubbo - dubbo-metrics-starter - ${project.version} - compile - true - org.apache.dubbo dubbo-metrics-registry @@ -475,10 +468,9 @@ org.apache.dubbo:dubbo-metadata-report-nacos org.apache.dubbo:dubbo-metadata-report-redis org.apache.dubbo:dubbo-metadata-report-zookeeper - org.apache.dubbo:dubbo-metrics-annotation + org.apache.dubbo:dubbo-metrics-monitor org.apache.dubbo:dubbo-metrics-api org.apache.dubbo:dubbo-metrics-default - org.apache.dubbo:dubbo-metrics-starter org.apache.dubbo:dubbo-metrics-registry org.apache.dubbo:dubbo-metrics-metadata org.apache.dubbo:dubbo-metrics-config-center diff --git a/dubbo-distribution/dubbo-all/pom.xml b/dubbo-distribution/dubbo-all/pom.xml index 90d7b48b4bc..f10033f10d7 100644 --- a/dubbo-distribution/dubbo-all/pom.xml +++ b/dubbo-distribution/dubbo-all/pom.xml @@ -160,7 +160,7 @@ org.apache.dubbo - dubbo-metrics-annotation + dubbo-metrics-monitor ${project.version} compile true @@ -214,13 +214,6 @@ compile true - - org.apache.dubbo - dubbo-metrics-starter - ${project.version} - compile - true - @@ -504,7 +497,7 @@ org.apache.dubbo:dubbo-metadata-report-nacos org.apache.dubbo:dubbo-metadata-report-redis org.apache.dubbo:dubbo-metadata-report-zookeeper - org.apache.dubbo:dubbo-metrics-annotation + org.apache.dubbo:dubbo-metrics-monitor org.apache.dubbo:dubbo-metrics-api org.apache.dubbo:dubbo-metrics-default org.apache.dubbo:dubbo-metrics-registry @@ -512,7 +505,6 @@ org.apache.dubbo:dubbo-metrics-config-center org.apache.dubbo:dubbo-metrics-netty org.apache.dubbo:dubbo-metrics-prometheus - org.apache.dubbo:dubbo-metrics-starter org.apache.dubbo:dubbo-tracing org.apache.dubbo:dubbo-qos org.apache.dubbo:dubbo-qos-api diff --git a/dubbo-distribution/dubbo-bom/pom.xml b/dubbo-distribution/dubbo-bom/pom.xml index c78841a7140..2209d927116 100644 --- a/dubbo-distribution/dubbo-bom/pom.xml +++ b/dubbo-distribution/dubbo-bom/pom.xml @@ -237,7 +237,7 @@ org.apache.dubbo - dubbo-metrics-annotation + dubbo-metrics-monitor ${project.version} @@ -270,11 +270,6 @@ dubbo-metrics-netty ${project.version} - - org.apache.dubbo - dubbo-metrics-starter - ${project.version} - diff --git a/dubbo-distribution/dubbo-core-spi/pom.xml b/dubbo-distribution/dubbo-core-spi/pom.xml index bbe643de37d..bf7c2f66591 100644 --- a/dubbo-distribution/dubbo-core-spi/pom.xml +++ b/dubbo-distribution/dubbo-core-spi/pom.xml @@ -125,10 +125,9 @@ org.apache.dubbo:dubbo-common org.apache.dubbo:dubbo-config-api org.apache.dubbo:dubbo-metadata-api - org.apache.dubbo:dubbo-metrics-annotation + org.apache.dubbo:dubbo-metrics-monitor org.apache.dubbo:dubbo-metrics-api org.apache.dubbo:dubbo-metrics-default - org.apache.dubbo:dubbo-metrics-starter org.apache.dubbo:dubbo-tracing org.apache.dubbo:dubbo-registry-api org.apache.dubbo:dubbo-remoting-api diff --git a/dubbo-metrics/dubbo-metrics-api/pom.xml b/dubbo-metrics/dubbo-metrics-api/pom.xml index 4d9a6486ff3..2c387a2cb05 100644 --- a/dubbo-metrics/dubbo-metrics-api/pom.xml +++ b/dubbo-metrics/dubbo-metrics-api/pom.xml @@ -36,11 +36,6 @@ dubbo-common ${project.parent.version} - - org.apache.dubbo - dubbo-metrics-annotation - ${project.parent.version} - org.apache.dubbo dubbo-rpc-api diff --git a/dubbo-metrics/dubbo-metrics-default/pom.xml b/dubbo-metrics/dubbo-metrics-default/pom.xml index 35d5026a340..d570d5da2e2 100644 --- a/dubbo-metrics/dubbo-metrics-default/pom.xml +++ b/dubbo-metrics/dubbo-metrics-default/pom.xml @@ -31,6 +31,11 @@ false + + org.apache.dubbo + dubbo-tracing + ${project.parent.version} + org.apache.dubbo dubbo-metrics-api diff --git a/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java rename to dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java diff --git a/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java similarity index 83% rename from dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java rename to dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java index 49c23391753..30f18d90393 100644 --- a/dubbo-metrics/dubbo-metrics-starter/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java @@ -25,6 +25,8 @@ import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.config.deploy.event.ApplicationLoadedEvent; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; +import org.apache.dubbo.metrics.listener.PreDestroyApplicationInstanceEventListener; +import org.apache.dubbo.metrics.listener.PrepareApplicationInstanceEventListener; import org.apache.dubbo.metrics.report.DefaultMetricsReporterFactory; import org.apache.dubbo.metrics.report.MetricsReporter; import org.apache.dubbo.metrics.report.MetricsReporterFactory; @@ -64,25 +66,28 @@ public MetricsServiceInitializer(ApplicationModel applicationModel) { this.metricsServiceExporter = applicationModel .getExtensionLoader(MetricsServiceExporter.class) .getDefaultExtension(); - dubboListeners = Arrays.asList(new AbstractDubboListener() { - @Override - public void onEvent(ApplicationLoadedEvent event) { - - if (MetricsSupportUtil.isSupportMetrics()) { - MetricsConfig metricsConfig = initMetricsConfig(); - if (!PROTOCOL_PROMETHEUS.equals(metricsConfig.getProtocol()) - || MetricsSupportUtil.isSupportPrometheus()) { - initDefaultMetricsCollector(metricsConfig); - initMetricsReporter(metricsConfig); + dubboListeners = Arrays.asList( + new AbstractDubboListener() { + @Override + public void onEvent(ApplicationLoadedEvent event) { + + if (MetricsSupportUtil.isSupportMetrics()) { + MetricsConfig metricsConfig = initMetricsConfig(); + if (!PROTOCOL_PROMETHEUS.equals(metricsConfig.getProtocol()) + || MetricsSupportUtil.isSupportPrometheus()) { + initDefaultMetricsCollector(metricsConfig); + initMetricsReporter(metricsConfig); + } + } + + initMetricsService(); + + // @since 3.2.3 + initObservationRegistry(); } - } - - initMetricsService(); - - // @since 3.2.3 - initObservationRegistry(); - } - }); + }, + new PrepareApplicationInstanceEventListener(), + new PreDestroyApplicationInstanceEventListener()); } public List> getDubboListeners() { @@ -149,8 +154,8 @@ private void initMetricsReporter(MetricsConfig metricsConfig) { private void initObservationRegistry() { if (!ObservationSupportUtil.isSupportObservation()) { if (logger.isDebugEnabled()) { - logger.debug( - "Not found micrometer-observation or plz check the version of micrometer-observation version if already introduced, need > 1.10.0"); + logger.debug("Not found micrometer-observation or plz check the version of micrometer-observation " + + "version if already introduced, need > 1.10.0"); } return; } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PreDestroyApplicationInstanceEventListener.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PreDestroyApplicationInstanceEventListener.java new file mode 100644 index 00000000000..98cd8f5a01c --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PreDestroyApplicationInstanceEventListener.java @@ -0,0 +1,37 @@ +/* + * 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.listener; + +import org.apache.dubbo.common.event.AbstractDubboListener; +import org.apache.dubbo.config.deploy.event.PreDestroyApplicationInstanceEvent; +import org.apache.dubbo.metrics.service.MetricsServiceExporter; + +public class PreDestroyApplicationInstanceEventListener + extends AbstractDubboListener { + @Override + public void onEvent(PreDestroyApplicationInstanceEvent event) { + MetricsServiceExporter metricsServiceExporter = + event.getApplicationModel().getBeanFactory().getBean(MetricsServiceExporter.class); + if (metricsServiceExporter != null) { + try { + metricsServiceExporter.unexport(); + } catch (Exception ignored) { + // ignored + } + } + } +} diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PrepareApplicationInstanceEventListener.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PrepareApplicationInstanceEventListener.java new file mode 100644 index 00000000000..e11f90cf615 --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PrepareApplicationInstanceEventListener.java @@ -0,0 +1,54 @@ +/* + * 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.listener; + +import org.apache.dubbo.common.constants.LoggerCodeConstants; +import org.apache.dubbo.common.event.AbstractDubboListener; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.config.MetricsConfig; +import org.apache.dubbo.config.deploy.event.PrepareApplicationInstanceEvent; +import org.apache.dubbo.metrics.service.MetricsServiceExporter; + +public class PrepareApplicationInstanceEventListener extends AbstractDubboListener { + + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(PrepareApplicationInstanceEventListener.class); + + @Override + public void onEvent(PrepareApplicationInstanceEvent event) { + MetricsServiceExporter metricsServiceExporter = + event.getApplicationModel().getBeanFactory().getBean(MetricsServiceExporter.class); + boolean exportMetrics = event.getApplicationModel() + .getApplicationConfigManager() + .getMetrics() + .map(MetricsConfig::getExportMetricsService) + .orElse(true); + if (exportMetrics && metricsServiceExporter != null) { + try { + metricsServiceExporter.export(); + } catch (Exception e) { + logger.error( + LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION, + "", + "", + "exportMetricsService an" + " exception occurred when handle starting event", + e); + } + } + } +} diff --git a/dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java rename to dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter index ecb9e24f278..08e822be301 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter +++ b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter @@ -1,2 +1 @@ metrics-provider=org.apache.dubbo.metrics.filter.MetricsProviderFilter -monitor=org.apache.dubbo.monitor.support.MonitorFilter diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter index c0bcbe620b6..ca716e377a7 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter +++ b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter @@ -1,3 +1,2 @@ metricsClusterFilter=org.apache.dubbo.rpc.cluster.filter.support.MetricsClusterFilter -monitor=org.apache.dubbo.monitor.support.MonitorClusterFilter metricsConsumerFilter=org.apache.dubbo.metrics.filter.MetricsConsumerFilter diff --git a/dubbo-metrics/dubbo-metrics-starter/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer similarity index 100% rename from dubbo-metrics/dubbo-metrics-starter/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer rename to dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer diff --git a/dubbo-metrics/dubbo-metrics-starter/src/test/java/org/apache/dubbo/metrics/collector/CollectorInitTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/CollectorInitTest.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-starter/src/test/java/org/apache/dubbo/metrics/collector/CollectorInitTest.java rename to dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/CollectorInitTest.java diff --git a/dubbo-metrics/dubbo-metrics-annotation/pom.xml b/dubbo-metrics/dubbo-metrics-monitor/pom.xml similarity index 80% rename from dubbo-metrics/dubbo-metrics-annotation/pom.xml rename to dubbo-metrics/dubbo-metrics-monitor/pom.xml index 1fe6d1d1d73..a761fccaf4a 100644 --- a/dubbo-metrics/dubbo-metrics-annotation/pom.xml +++ b/dubbo-metrics/dubbo-metrics-monitor/pom.xml @@ -23,7 +23,7 @@ ${revision} ../pom.xml - dubbo-metrics-annotation + dubbo-metrics-monitor jar ${project.artifactId} The metrics module of dubbo project @@ -36,5 +36,15 @@ dubbo-common ${project.parent.version} + + org.apache.dubbo + dubbo-cluster + ${project.parent.version} + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + diff --git a/dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/Constants.java b/dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/Constants.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/Constants.java rename to dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/Constants.java diff --git a/dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/Monitor.java b/dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/Monitor.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/Monitor.java rename to dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/Monitor.java diff --git a/dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java b/dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java rename to dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java diff --git a/dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/MonitorService.java b/dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/MonitorService.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-annotation/src/main/java/org/apache/dubbo/monitor/MonitorService.java rename to dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/MonitorService.java diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java b/dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java rename to dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java b/dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java rename to dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java diff --git a/dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter b/dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter new file mode 100644 index 00000000000..fbeff59d1df --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter @@ -0,0 +1 @@ +monitor=org.apache.dubbo.monitor.support.MonitorFilter diff --git a/dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter b/dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter new file mode 100644 index 00000000000..454d429d93f --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter @@ -0,0 +1 @@ +monitor=org.apache.dubbo.monitor.support.MonitorClusterFilter diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java b/dubbo-metrics/dubbo-metrics-monitor/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java rename to dubbo-metrics/dubbo-metrics-monitor/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java diff --git a/dubbo-metrics/dubbo-metrics-starter/pom.xml b/dubbo-metrics/dubbo-metrics-starter/pom.xml deleted file mode 100644 index cebb1fdcf44..00000000000 --- a/dubbo-metrics/dubbo-metrics-starter/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-metrics - ${revision} - ../pom.xml - - dubbo-metrics-starter - jar - ${project.artifactId} - The metrics module of dubbo project - - false - - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-tracing - ${project.parent.version} - - - - org.apache.dubbo - dubbo-native - ${project.parent.version} - - - - io.micrometer - micrometer-test - test - - - org.apache.logging.log4j - log4j-slf4j-impl - test - - - diff --git a/dubbo-metrics/pom.xml b/dubbo-metrics/pom.xml index d67b8135098..c6990b624cb 100644 --- a/dubbo-metrics/pom.xml +++ b/dubbo-metrics/pom.xml @@ -28,10 +28,9 @@ ${project.artifactId} The metrics module of dubbo project - dubbo-metrics-annotation + dubbo-metrics-monitor dubbo-metrics-api dubbo-metrics-default - dubbo-metrics-starter dubbo-metrics-registry dubbo-metrics-metadata dubbo-metrics-prometheus diff --git a/dubbo-test/dubbo-dependencies-all/pom.xml b/dubbo-test/dubbo-dependencies-all/pom.xml index 620d8b6ec16..d437215ecaf 100644 --- a/dubbo-test/dubbo-dependencies-all/pom.xml +++ b/dubbo-test/dubbo-dependencies-all/pom.xml @@ -158,7 +158,7 @@ org.apache.dubbo - dubbo-metrics-annotation + dubbo-metrics-monitor ${project.version} @@ -195,11 +195,6 @@ dubbo-metrics-prometheus ${project.version} - - org.apache.dubbo - dubbo-metrics-starter - ${project.version} - org.apache.dubbo dubbo-tracing From 679b37f2f3ac9739c3300beccff571696056c2c2 Mon Sep 17 00:00:00 2001 From: walklown Date: Sun, 16 Jun 2024 20:40:45 +0800 Subject: [PATCH 11/12] DefaultMetricsCollector filter RequestEvent when avalidate is false --- .../metrics/collector/HistogramMetricsCollector.java | 3 +++ .../dubbo/metrics/event/DefaultSubDispatcher.java | 10 +++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java index 7ac47364d03..4793c0a0792 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java @@ -98,6 +98,9 @@ public void onEventError(RequestMetricsEvent event) { } private void onRTEvent(RequestMetricsEvent event) { + if (!event.isAvailable()) { + return; + } if (collector.metricRegister != null) { MethodMetric metric = new MethodMetric( collector.applicationModel, diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java index 03b6872bce9..e89be70aca3 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java @@ -49,6 +49,9 @@ public DefaultSubDispatcher(DefaultMetricsCollector collector) { @Override public void onEventBefore(RequestMetricsEvent event) { + if (!event.isAvailable()) { + return; + } this.multicaster.publishEvent(event); } @@ -57,7 +60,9 @@ public void onEventBefore(RequestMetricsEvent event) { @Override public void onEventFinish(RequestMetricsEvent event) { - this.multicaster.publishFinishEvent(event); + if (event.isAvailable()) { + this.multicaster.publishFinishEvent(event); + } if (event.isRequestErrorEvent()) { MetricsSupport.increment( METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, @@ -69,6 +74,9 @@ public void onEventFinish(RequestMetricsEvent event) { @Override public void onEventError(RequestMetricsEvent event) { + if (!event.isAvailable()) { + return; + } this.multicaster.publishErrorEvent(event); } From e6b48c8a3c51324ee5e40a45b22427ea31982ce0 Mon Sep 17 00:00:00 2001 From: walklown Date: Wed, 19 Jun 2024 01:18:09 +0800 Subject: [PATCH 12/12] Rollback fix for unrelated unit tests --- .../spring/propertyconfigurer/provider/dubbo-provider.xml | 2 +- .../spring/reference/registryNA/provider/dubbo-provider.xml | 2 +- .../src/main/resources/spring/rest-provider.xml | 2 +- .../src/main/resources/spring/dubbo-provider.xml | 4 ++-- .../src/main/resources/spring/dubbo-demo.xml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml index e8e1c4bec4f..fca1aa5218f 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml @@ -38,7 +38,7 @@ - + diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml index c98b7fa52b8..09a71c3aca5 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml @@ -29,7 +29,7 @@ - + diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/resources/spring/rest-provider.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/resources/spring/rest-provider.xml index 78bafadd0ba..8c6be976f72 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/resources/spring/rest-provider.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/resources/spring/rest-provider.xml @@ -32,7 +32,7 @@ - + diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/resources/spring/dubbo-provider.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/resources/spring/dubbo-provider.xml index ae236a6bfe3..ad402bc0683 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/resources/spring/dubbo-provider.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/resources/spring/dubbo-provider.xml @@ -29,7 +29,7 @@ - + @@ -41,7 +41,7 @@ + ref="restDemoService" protocol="rest"/> diff --git a/dubbo-test/dubbo-test-spring/src/main/resources/spring/dubbo-demo.xml b/dubbo-test/dubbo-test-spring/src/main/resources/spring/dubbo-demo.xml index 4f31f8740f6..5b67af72efd 100644 --- a/dubbo-test/dubbo-test-spring/src/main/resources/spring/dubbo-demo.xml +++ b/dubbo-test/dubbo-test-spring/src/main/resources/spring/dubbo-demo.xml @@ -28,7 +28,7 @@ - +