From bc383544e29b0cb6a45b07c8e41beb02d11f878a Mon Sep 17 00:00:00 2001
From: Wu <88076398+dengWuuu@users.noreply.github.com>
Date: Tue, 21 Mar 2023 17:52:31 +0800
Subject: [PATCH 001/122] Observability task: add metadata buried points at the
provider responder interface level (#11798)
* feat: add metadata buried points listener
* feat: add test unit
* feat: add buried in store provider meta
* fix: remove unuse import
* fix: restore demo
* fix: remove * import
* fix: test time window
* fix: test unit error
* fix: fix metadata report unit error
* fix: remove unuse import
* fix: remove * import
* fix: use getOrDefaultApplication to compatible with test unit
* fix: resolve conflict
* fix: change test comment
* fix: update collector
* fix: update test unit
* fix: update buried points function
* fix: update buried points function
* fix: remove * import
* fix: fix test unit
* fix: fix error rename
* fix: update type to application-type
---
dubbo-metadata/dubbo-metadata-api/pom.xml | 19 ++++
.../report/MetadataReportInstance.java | 2 +-
.../support/AbstractMetadataReport.java | 14 +++
.../support/AbstractMetadataReportTest.java | 25 ++++--
.../dubbo/metrics/model/MetricsKey.java | 11 ++-
.../collector/MetadataMetricsCollector.java | 15 +++-
.../collector/stat/MetadataStatComposite.java | 86 +++++++++++++++----
.../collector/stat/ServiceKeyMetric.java | 78 +++++++++++++++++
.../metrics/metadata/event/MetadataEvent.java | 47 +++++++++-
.../MetadataMetricsEventMulticaster.java | 2 +-
.../metadata/event/MetricsPushListener.java | 6 +-
.../event/MetricsSubscribeListener.java | 6 +-
.../event/StoreProviderMetadataListener.java | 49 +++++++++++
.../MetadataMetricsCollectorTest.java | 52 +++++++++++
.../metadata/MetadataStatCompositeTest.java | 18 ++--
.../collector/stat/ServiceKeyMetric.java | 1 -
16 files changed, 377 insertions(+), 54 deletions(-)
create mode 100644 dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/stat/ServiceKeyMetric.java
create mode 100644 dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/StoreProviderMetadataListener.java
diff --git a/dubbo-metadata/dubbo-metadata-api/pom.xml b/dubbo-metadata/dubbo-metadata-api/pom.xml
index 9fc83dd32f..c951e1d36b 100644
--- a/dubbo-metadata/dubbo-metadata-api/pom.xml
+++ b/dubbo-metadata/dubbo-metadata-api/pom.xml
@@ -66,6 +66,25 @@
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
+
+
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java
index 65fe2689f3..264d6a18f9 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java
@@ -57,7 +57,7 @@ public class MetadataReportInstance implements Disposable {
// mapping of registry id to metadata report instance, registry instances will use this mapping to find related metadata reports
private final Map metadataReports = new HashMap<>();
- private ApplicationModel applicationModel;
+ private final ApplicationModel applicationModel;
private final NopMetadataReport nopMetadataReport;
public MetadataReportInstance(ApplicationModel applicationModel) {
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 dcd0bd001c..ccad3a3493 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
@@ -30,6 +30,10 @@ 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.GlobalMetricsEventMulticaster;
+import org.apache.dubbo.metrics.metadata.event.MetadataEvent;
+import org.apache.dubbo.metrics.model.TimePair;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.File;
import java.io.FileInputStream;
@@ -103,9 +107,11 @@ public abstract class AbstractMetadataReport implements MetadataReport {
private final boolean reportMetadata;
private final boolean reportDefinition;
+ protected ApplicationModel applicationModel;
public AbstractMetadataReport(URL reportServerURL) {
setUrl(reportServerURL);
+ applicationModel = reportServerURL.getOrDefaultApplicationModel();
boolean localCacheEnabled = reportServerURL.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true);
// Start file save timer
@@ -273,6 +279,10 @@ public abstract class AbstractMetadataReport implements MetadataReport {
}
private void storeProviderMetadataTask(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) {
+ TimePair timePair = TimePair.start();
+ GlobalMetricsEventMulticaster eventMulticaster = applicationModel.getBeanFactory().getBean(GlobalMetricsEventMulticaster.class);
+ String interfaceMethodName = serviceDefinition.getCanonicalName();
+ eventMulticaster.publishEvent(new MetadataEvent.StoreProviderMetadataEvent(applicationModel, timePair, interfaceMethodName));
try {
if (logger.isInfoEnabled()) {
logger.info("store provider metadata. Identifier : " + providerMetadataIdentifier + "; definition: " + serviceDefinition);
@@ -287,7 +297,11 @@ public abstract class AbstractMetadataReport implements MetadataReport {
failedReports.put(providerMetadataIdentifier, serviceDefinition);
metadataReportRetry.startRetryTask();
logger.error(PROXY_FAILED_EXPORT_SERVICE, "", "", "Failed to put provider metadata " + providerMetadataIdentifier + " in " + serviceDefinition + ", cause: " + e.getMessage(), e);
+ // fail
+ eventMulticaster.publishErrorEvent(new MetadataEvent.StoreProviderMetadataEvent(applicationModel, timePair, interfaceMethodName));
+ return;
}
+ eventMulticaster.publishFinishEvent(new MetadataEvent.StoreProviderMetadataEvent(applicationModel, timePair, interfaceMethodName));
}
@Override
diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java
index fc091b01d9..2dce6ea6c6 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java
@@ -29,7 +29,7 @@ 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.rpc.model.ApplicationModel;
-
+import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@@ -55,13 +55,18 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class AbstractMetadataReportTest {
private NewMetadataReport abstractMetadataReport;
+ private ApplicationModel applicationModel;
@BeforeEach
public void before() {
- URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
- abstractMetadataReport = new NewMetadataReport(url);
// set the simple name of current class as the application name
- ApplicationModel.defaultModel().getConfigManager().setApplication(new ApplicationConfig(getClass().getSimpleName()));
+ FrameworkModel frameworkModel = FrameworkModel.defaultModel();
+ applicationModel = frameworkModel.newApplication();
+ applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig(getClass().getSimpleName()));
+
+ URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
+ abstractMetadataReport = new NewMetadataReport(url, applicationModel);
+
}
@AfterEach
@@ -110,7 +115,7 @@ class AbstractMetadataReportTest {
void testFileExistAfterPut() throws ClassNotFoundException {
//just for one method
URL singleUrl = URL.valueOf("redis://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.metadata.store.InterfaceNameTestService?version=1.0.0&application=singleTest");
- NewMetadataReport singleMetadataReport = new NewMetadataReport(singleUrl);
+ NewMetadataReport singleMetadataReport = new NewMetadataReport(singleUrl, applicationModel);
assertFalse(singleMetadataReport.file.exists());
@@ -135,7 +140,7 @@ class AbstractMetadataReportTest {
String group = null;
String application = "vic.retry";
URL storeUrl = URL.valueOf("retryReport://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestServiceForRetry?version=1.0.0.retry&application=vic.retry");
- RetryMetadataReport retryReport = new RetryMetadataReport(storeUrl, 2);
+ RetryMetadataReport retryReport = new RetryMetadataReport(storeUrl, 2, applicationModel);
retryReport.metadataReportRetry.retryPeriod = 400L;
URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
Assertions.assertNull(retryReport.metadataReportRetry.retryScheduledFuture);
@@ -170,7 +175,7 @@ class AbstractMetadataReportTest {
String group = null;
String application = "vic.retry";
URL storeUrl = URL.valueOf("retryReport://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestServiceForRetryCancel?version=1.0.0.retrycancel&application=vic.retry");
- RetryMetadataReport retryReport = new RetryMetadataReport(storeUrl, 2);
+ RetryMetadataReport retryReport = new RetryMetadataReport(storeUrl, 2, applicationModel);
retryReport.metadataReportRetry.retryPeriod = 150L;
retryReport.metadataReportRetry.retryTimesIfNonFail = 2;
@@ -292,8 +297,9 @@ class AbstractMetadataReportTest {
Map store = new ConcurrentHashMap<>();
- public NewMetadataReport(URL metadataReportURL) {
+ public NewMetadataReport(URL metadataReportURL, ApplicationModel applicationModel) {
super(metadataReportURL);
+ this.applicationModel = applicationModel;
}
@Override
@@ -348,9 +354,10 @@ class AbstractMetadataReportTest {
int needRetryTimes;
int executeTimes = 0;
- public RetryMetadataReport(URL metadataReportURL, int needRetryTimes) {
+ public RetryMetadataReport(URL metadataReportURL, int needRetryTimes, ApplicationModel applicationModel) {
super(metadataReportURL);
this.needRetryTimes = needRetryTimes;
+ this.applicationModel = applicationModel;
}
@Override
diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
index a931adcb19..fbf3a5e1fd 100644
--- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
@@ -23,7 +23,7 @@ public enum MetricsKey {
// provider metrics key
METRIC_REQUESTS("dubbo.%s.requests.total", "Total Requests"),
METRIC_REQUESTS_SUCCEED("dubbo.%s.requests.succeed.total", "Total Succeed Requests"),
- METRIC_REQUEST_BUSINESS_FAILED("dubbo.%s.requests.business.failed.total","Total Failed Business Requests"),
+ METRIC_REQUEST_BUSINESS_FAILED("dubbo.%s.requests.business.failed.total", "Total Failed Business Requests"),
METRIC_REQUESTS_PROCESSING("dubbo.%s.requests.processing", "Processing Requests"),
METRIC_REQUESTS_TIMEOUT("dubbo.%s.requests.timeout.total", "Total Timeout Failed Requests"),
@@ -101,7 +101,14 @@ public enum MetricsKey {
SERVICE_SUBSCRIBE_METRIC_NUM("dubbo.registry.subscribe.service.num.total", "Total Service-Level Subscribe Num"),
SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED("dubbo.registry.subscribe.service.num.succeed.total", "Succeed Service-Level Num"),
SERVICE_SUBSCRIBE_METRIC_NUM_FAILED("dubbo.registry.subscribe.service.num.failed.total", "Failed Service-Level Num"),
- METADATA_GIT_COMMITID_METRIC("git.commit.id","Git Commit Id Metrics");
+ // store provider metadata service key
+ STORE_PROVIDER_METADATA("dubbo.metadata.store.provider.total", "Store Provider Metadata"),
+
+ STORE_PROVIDER_METADATA_SUCCEED("dubbo.metadata.store.provider.succeed.total", "Succeed Store Provider Metadata"),
+
+ STORE_PROVIDER_METADATA_FAILED("dubbo.metadata.store.provider.failed.total", "Failed Store Provider Metadata"),
+ METADATA_GIT_COMMITID_METRIC("git.commit.id", "Git Commit Id Metrics"),
+
// consumer metrics key
;
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 405abe7390..d254ab8024 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
@@ -38,7 +38,7 @@ import java.util.Optional;
* Registry implementation of {@link MetricsCollector}
*/
@Activate
-public class MetadataMetricsCollector implements ApplicationMetricsCollector {
+public class MetadataMetricsCollector implements ApplicationMetricsCollector {
private Boolean collectEnabled = null;
private final MetadataStatComposite stats;
@@ -67,13 +67,21 @@ public class MetadataMetricsCollector implements ApplicationMetricsCollector> numStats = new ConcurrentHashMap<>();
- public List> rtStats = new ArrayList<>();
+ public Map> applicationNumStats = new ConcurrentHashMap<>();
+ public Map> serviceNumStats = new ConcurrentHashMap<>();
+ public List> appRtStats = new ArrayList<>();
+
+ public List> serviceRtStats = new ArrayList<>();
public static String OP_TYPE_PUSH = "push";
public static String OP_TYPE_SUBSCRIBE = "subscribe";
+ public static String OP_TYPE_STORE_PROVIDER_INTERFACE = "store.provider.interface";
public MetadataStatComposite() {
- for (MetadataEvent.Type type : MetadataEvent.Type.values()) {
- numStats.put(type, new ConcurrentHashMap<>());
+ for (MetadataEvent.ApplicationType applicationType : MetadataEvent.ApplicationType.values()) {
+ applicationNumStats.put(applicationType, new ConcurrentHashMap<>());
+ }
+ for (MetadataEvent.ServiceType serviceType : MetadataEvent.ServiceType.values()) {
+ serviceNumStats.put(serviceType, new ConcurrentHashMap<>());
}
- rtStats.addAll(initStats(OP_TYPE_PUSH));
- rtStats.addAll(initStats(OP_TYPE_SUBSCRIBE));
+ appRtStats.addAll(initStats(OP_TYPE_PUSH, appRtStats));
+ appRtStats.addAll(initStats(OP_TYPE_SUBSCRIBE, appRtStats));
+
+ serviceRtStats.addAll(initStats(OP_TYPE_STORE_PROVIDER_INTERFACE, serviceRtStats));
}
- private List> initStats(String registryOpType) {
+ private List> initStats(String registryOpType, List> rtStats) {
+
List> singleRtStats = new ArrayList<>();
singleRtStats.add(new AtomicLongContainer(new MetricsKeyWrapper(registryOpType, MetricsKey.METRIC_RT_LAST)));
singleRtStats.add(new LongAccumulatorContainer(new MetricsKeyWrapper(registryOpType, MetricsKey.METRIC_RT_MIN), new LongAccumulator(Long::min, Long.MAX_VALUE)));
@@ -78,27 +89,56 @@ public class MetadataStatComposite implements MetricsExport {
return singleRtStats;
}
- public void increment(MetadataEvent.Type type, String applicationName) {
- if (!numStats.containsKey(type)) {
+ public void increment(MetadataEvent.ApplicationType type, String applicationName) {
+ incrementSize(type, applicationName, 1);
+ }
+
+ public void incrementServiceKey(MetadataEvent.ServiceType type, String applicationName, String serviceKey, int size) {
+ if (!serviceNumStats.containsKey(type)) {
return;
}
- numStats.get(type).computeIfAbsent(applicationName, k -> new AtomicLong(0L)).incrementAndGet();
+ serviceNumStats.get(type).computeIfAbsent(new ServiceKeyMetric(applicationName, serviceKey), k -> new AtomicLong(0L)).getAndAdd(size);
+ }
+
+ public void incrementSize(MetadataEvent.ApplicationType type, String applicationName, int size) {
+ if (!applicationNumStats.containsKey(type)) {
+ return;
+ }
+ applicationNumStats.get(type).computeIfAbsent(applicationName, k -> new AtomicLong(0L)).getAndAdd(size);
}
@SuppressWarnings({"rawtypes", "unchecked"})
- public void calcRt(String applicationName, String registryOpType, Long responseTime) {
- for (LongContainer container : rtStats.stream().filter(longContainer -> longContainer.specifyType(registryOpType)).collect(Collectors.toList())) {
+ public void calcApplicationRt(String applicationName, String registryOpType, Long responseTime) {
+ for (LongContainer container : appRtStats.stream().filter(longContainer -> longContainer.specifyType(registryOpType)).collect(Collectors.toList())) {
Number current = (Number) ConcurrentHashMapUtils.computeIfAbsent(container, applicationName, container.getInitFunc());
container.getConsumerFunc().accept(responseTime, current);
}
}
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ public void calcServiceKeyRt(String applicationName, String serviceKey, String registryOpType, Long responseTime) {
+ for (LongContainer container : serviceRtStats.stream().filter(longContainer -> longContainer.specifyType(registryOpType)).collect(Collectors.toList())) {
+ Number current = (Number) ConcurrentHashMapUtils.computeIfAbsent(container, applicationName + "_" + serviceKey, container.getInitFunc());
+ container.getConsumerFunc().accept(responseTime, current);
+ }
+ }
+
+ @SuppressWarnings({"rawtypes"})
+ private void doExportRt(List list, List> rtStats, Function> tagNameFunc) {
+ for (LongContainer extends Number> rtContainer : rtStats) {
+ MetricsKeyWrapper metricsKeyWrapper = rtContainer.getMetricsKeyWrapper();
+ for (Map.Entry entry : rtContainer.entrySet()) {
+ list.add(new GaugeMetricSample<>(metricsKeyWrapper.targetKey(), metricsKeyWrapper.targetDesc(), tagNameFunc.apply(entry.getKey()), MetricsCategory.RT, entry.getKey().intern(), value -> rtContainer.getValueSupplier().apply(value.intern())));
+ }
+ }
+ }
+
@Override
@SuppressWarnings("rawtypes")
public List exportNumMetrics() {
List list = new ArrayList<>();
- for (MetadataEvent.Type type : numStats.keySet()) {
- Map stringAtomicLongMap = numStats.get(type);
+ for (MetadataEvent.ApplicationType type : applicationNumStats.keySet()) {
+ Map stringAtomicLongMap = applicationNumStats.get(type);
for (String applicationName : stringAtomicLongMap.keySet()) {
list.add(convertToSample(applicationName, type, MetricsCategory.REGISTRY, stringAtomicLongMap.get(applicationName)));
}
@@ -110,17 +150,25 @@ public class MetadataStatComposite implements MetricsExport {
@SuppressWarnings("rawtypes")
public List exportRtMetrics() {
List list = new ArrayList<>();
- for (LongContainer extends Number> rtContainer : rtStats) {
- MetricsKeyWrapper metricsKeyWrapper = rtContainer.getMetricsKeyWrapper();
- for (Map.Entry entry : rtContainer.entrySet()) {
- list.add(new GaugeMetricSample<>(metricsKeyWrapper.targetKey(), metricsKeyWrapper.targetDesc(), ApplicationMetric.getTagsByName(entry.getKey()), MetricsCategory.RT, entry.getKey().intern(), value -> rtContainer.getValueSupplier().apply(value.intern())));
+ doExportRt(list, appRtStats, ApplicationMetric::getTagsByName);
+ doExportRt(list, serviceRtStats, ApplicationMetric::getServiceTags);
+ return list;
+ }
+
+ @SuppressWarnings({"rawtypes"})
+ public List exportServiceNumMetrics() {
+ List list = new ArrayList<>();
+ for (MetadataEvent.ServiceType type : serviceNumStats.keySet()) {
+ Map stringAtomicLongMap = serviceNumStats.get(type);
+ for (ServiceKeyMetric serviceKeyMetric : stringAtomicLongMap.keySet()) {
+ list.add(new GaugeMetricSample<>(type.getMetricsKey(), serviceKeyMetric.getTags(), MetricsCategory.REGISTRY, stringAtomicLongMap, value -> value.get(serviceKeyMetric).get()));
}
}
return list;
}
@SuppressWarnings("rawtypes")
- public GaugeMetricSample convertToSample(String applicationName, MetadataEvent.Type type, MetricsCategory category, AtomicLong targetNumber) {
+ public GaugeMetricSample convertToSample(String applicationName, MetadataEvent.ApplicationType type, MetricsCategory category, AtomicLong targetNumber) {
return new GaugeMetricSample<>(type.getMetricsKey(), ApplicationMetric.getTagsByName(applicationName), category, targetNumber, AtomicLong::get);
}
diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/stat/ServiceKeyMetric.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/stat/ServiceKeyMetric.java
new file mode 100644
index 0000000000..7643d7368a
--- /dev/null
+++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/stat/ServiceKeyMetric.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.metadata.collector.stat;
+
+import org.apache.dubbo.metrics.model.Metric;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_INTERFACE_KEY;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP;
+import static org.apache.dubbo.common.utils.NetUtils.getLocalHost;
+import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName;
+
+/**
+ * Metric class for interface.
+ */
+public class ServiceKeyMetric implements Metric {
+ private final String applicationName;
+ private final String serviceKey;
+
+ public ServiceKeyMetric(String applicationName, String serviceKey) {
+ this.applicationName = applicationName;
+ this.serviceKey = serviceKey;
+ }
+
+ public Map getTags() {
+ Map tags = new HashMap<>();
+ tags.put(TAG_IP, getLocalHost());
+ tags.put(TAG_HOSTNAME, getLocalHostName());
+ tags.put(TAG_APPLICATION_NAME, applicationName);
+ tags.put(TAG_INTERFACE_KEY, serviceKey);
+ return tags;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ ServiceKeyMetric that = (ServiceKeyMetric) o;
+
+ if (!applicationName.equals(that.applicationName)) return false;
+ return serviceKey.equals(that.serviceKey);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = applicationName.hashCode();
+ result = 31 * result + serviceKey.hashCode();
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "ServiceKeyMetric{" +
+ "applicationName='" + applicationName + '\'' +
+ ", serviceKey='" + serviceKey + '\'' +
+ '}';
+ }
+}
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/MetadataEvent.java
index 8d68e5a189..1b419c588d 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/MetadataEvent.java
@@ -56,7 +56,7 @@ public class MetadataEvent extends MetricsEvent implements TimeCounter {
return timePair;
}
- public enum Type {
+ public enum ApplicationType {
P_TOTAL(MetricsKey.METADATA_PUSH_METRIC_NUM),
P_SUCCEED(MetricsKey.METADATA_PUSH_METRIC_NUM_SUCCEED),
P_FAILED(MetricsKey.METADATA_PUSH_METRIC_NUM_FAILED),
@@ -66,17 +66,44 @@ public class MetadataEvent extends MetricsEvent implements TimeCounter {
S_FAILED(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_FAILED),
;
+ private final MetricsKey metricsKey;
+ private final boolean isIncrement;
+ ApplicationType(MetricsKey metricsKey) {
+ this(metricsKey, true);
+ }
+
+ ApplicationType(MetricsKey metricsKey, boolean isIncrement) {
+ this.metricsKey = metricsKey;
+ this.isIncrement = isIncrement;
+ }
+
+ public MetricsKey getMetricsKey() {
+ return metricsKey;
+ }
+
+ public boolean isIncrement() {
+ return isIncrement;
+ }
+ }
+
+ public enum ServiceType {
+
+ S_P_TOTAL(MetricsKey.STORE_PROVIDER_METADATA),
+ S_P_SUCCEED(MetricsKey.STORE_PROVIDER_METADATA_SUCCEED),
+ S_P_FAILED(MetricsKey.STORE_PROVIDER_METADATA_FAILED),
+
+ ;
private final MetricsKey metricsKey;
private final boolean isIncrement;
- Type(MetricsKey metricsKey) {
+ ServiceType(MetricsKey metricsKey) {
this(metricsKey, true);
}
- Type(MetricsKey metricsKey, boolean isIncrement) {
+ ServiceType(MetricsKey metricsKey, boolean isIncrement) {
this.metricsKey = metricsKey;
this.isIncrement = isIncrement;
}
@@ -106,4 +133,18 @@ public class MetadataEvent extends MetricsEvent implements TimeCounter {
}
+ public static class StoreProviderMetadataEvent extends MetadataEvent {
+ private final String serviceKey;
+
+ public StoreProviderMetadataEvent(ApplicationModel applicationModel, TimePair timePair, String serviceKey) {
+ super(applicationModel, timePair);
+ this.serviceKey = serviceKey;
+ }
+
+ public String getServiceKey() {
+ return serviceKey;
+ }
+
+ }
+
}
diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEventMulticaster.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEventMulticaster.java
index 92b3c96da3..7bc3197b67 100644
--- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEventMulticaster.java
+++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEventMulticaster.java
@@ -24,7 +24,7 @@ public final class MetadataMetricsEventMulticaster extends SimpleMetricsEventMul
public MetadataMetricsEventMulticaster() {
super.addListener(new MetricsPushListener());
super.addListener(new MetricsSubscribeListener());
-
+ super.addListener(new StoreProviderMetadataListener());
setAvailable();
}
diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetricsPushListener.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetricsPushListener.java
index 1c3352cf50..a1ceaee3b1 100644
--- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetricsPushListener.java
+++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetricsPushListener.java
@@ -32,18 +32,18 @@ public class MetricsPushListener implements MetricsLifeListener {
+
+
+ @Override
+ public boolean isSupport(MetricsEvent event) {
+ return event instanceof MetadataEvent.StoreProviderMetadataEvent && ((MetadataEvent) event).isAvailable();
+ }
+
+ @Override
+ public void onEvent(MetadataEvent.StoreProviderMetadataEvent event) {
+ event.getCollector().incrementServiceKey(event.getSource().getApplicationName(), event.getServiceKey(), MetadataEvent.ServiceType.S_P_TOTAL, 1);
+ }
+
+ @Override
+ public void onEventFinish(MetadataEvent.StoreProviderMetadataEvent event) {
+ event.getCollector().incrementServiceKey(event.getSource().getApplicationName(), event.getServiceKey(), MetadataEvent.ServiceType.S_P_SUCCEED, 1);
+ event.getCollector().addServiceKeyRT(event.getSource().getApplicationName(), event.getServiceKey(), OP_TYPE_STORE_PROVIDER_INTERFACE, event.getTimePair().calc());
+ }
+
+ @Override
+ public void onEventError(MetadataEvent.StoreProviderMetadataEvent event) {
+ event.getCollector().incrementServiceKey(event.getSource().getApplicationName(), event.getServiceKey(), MetadataEvent.ServiceType.S_P_FAILED, 1);
+ event.getCollector().addServiceKeyRT(event.getSource().getApplicationName(), event.getServiceKey(), OP_TYPE_STORE_PROVIDER_INTERFACE, event.getTimePair().calc());
+ }
+}
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 0b6d44c2b1..380a99f021 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
@@ -41,6 +41,7 @@ import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME;
import static org.apache.dubbo.metrics.metadata.collector.stat.MetadataStatComposite.OP_TYPE_PUSH;
import static org.apache.dubbo.metrics.metadata.collector.stat.MetadataStatComposite.OP_TYPE_SUBSCRIBE;
+import static org.apache.dubbo.metrics.metadata.collector.stat.MetadataStatComposite.OP_TYPE_STORE_PROVIDER_INTERFACE;
class MetadataMetricsCollectorTest {
@@ -162,4 +163,55 @@ class MetadataMetricsCollectorTest {
}
+ @Test
+ void testStoreProviderMetadataMetrics() throws InterruptedException {
+
+ TimePair timePair = TimePair.start();
+ GlobalMetricsEventMulticaster eventMulticaster = applicationModel.getBeanFactory().getOrRegisterBean(GlobalMetricsEventMulticaster.class);
+ MetadataMetricsCollector collector = applicationModel.getBeanFactory().getOrRegisterBean(MetadataMetricsCollector.class);
+ collector.setCollectEnabled(true);
+
+ String serviceKey = "store.provider.test";
+ eventMulticaster.publishEvent(new MetadataEvent.StoreProviderMetadataEvent(applicationModel, timePair, serviceKey));
+ List metricSamples = collector.collect();
+
+ // push success +1
+ Assertions.assertEquals(1, metricSamples.size());
+ Assertions.assertTrue(metricSamples.get(0) instanceof GaugeMetricSample);
+ Assertions.assertEquals(metricSamples.get(0).getName(), MetricsKey.STORE_PROVIDER_METADATA.getName());
+ Assertions.assertEquals(metricSamples.get(0).getTags().get("interface"), serviceKey);
+
+ eventMulticaster.publishFinishEvent(new MetadataEvent.StoreProviderMetadataEvent(applicationModel, timePair, serviceKey));
+ // push finish rt +1
+ metricSamples = collector.collect();
+ //num(total+success) + rt(5) = 7
+ Assertions.assertEquals(7, metricSamples.size());
+ long c1 = timePair.calc();
+ TimePair lastTimePair = TimePair.start();
+ eventMulticaster.publishEvent(new MetadataEvent.StoreProviderMetadataEvent(applicationModel, lastTimePair, serviceKey));
+ Thread.sleep(50);
+ // push error rt +1
+ eventMulticaster.publishErrorEvent(new MetadataEvent.StoreProviderMetadataEvent(applicationModel, lastTimePair, serviceKey));
+ long c2 = lastTimePair.calc();
+ metricSamples = collector.collect();
+
+ // num(total+success+error) + rt(5)
+ Assertions.assertEquals(8, metricSamples.size());
+
+ // calc rt
+ for (MetricSample sample : metricSamples) {
+ Map tags = sample.getTags();
+ Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName());
+ }
+
+ @SuppressWarnings("rawtypes")
+ Map sampleMap = metricSamples.stream().collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong()));
+
+ Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(OP_TYPE_STORE_PROVIDER_INTERFACE, MetricsKey.METRIC_RT_LAST).targetKey()), lastTimePair.calc());
+ Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(OP_TYPE_STORE_PROVIDER_INTERFACE, MetricsKey.METRIC_RT_MIN).targetKey()), Math.min(c1, c2));
+ Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(OP_TYPE_STORE_PROVIDER_INTERFACE, MetricsKey.METRIC_RT_MAX).targetKey()), Math.max(c1, c2));
+ Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(OP_TYPE_STORE_PROVIDER_INTERFACE, MetricsKey.METRIC_RT_AVG).targetKey()), (c1 + c2) / 2);
+ Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(OP_TYPE_STORE_PROVIDER_INTERFACE, MetricsKey.METRIC_RT_SUM).targetKey()), c1 + c2);
+ }
+
}
diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataStatCompositeTest.java b/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataStatCompositeTest.java
index 66906decce..7d7d26a89a 100644
--- a/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataStatCompositeTest.java
+++ b/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataStatCompositeTest.java
@@ -36,12 +36,12 @@ public class MetadataStatCompositeTest {
@Test
void testInit() {
MetadataStatComposite statComposite = new MetadataStatComposite();
- Assertions.assertEquals(statComposite.numStats.size(), MetadataEvent.Type.values().length);
+ Assertions.assertEquals(statComposite.applicationNumStats.size(), MetadataEvent.ApplicationType.values().length);
//(rt)5 * (push,subscribe)2
- Assertions.assertEquals(5 * 2, statComposite.rtStats.size());
- statComposite.numStats.values().forEach((v ->
+ Assertions.assertEquals(5 * 2, statComposite.appRtStats.size());
+ statComposite.applicationNumStats.values().forEach((v ->
Assertions.assertEquals(v, new ConcurrentHashMap<>())));
- statComposite.rtStats.forEach(rtContainer ->
+ statComposite.appRtStats.forEach(rtContainer ->
{
for (Map.Entry entry : rtContainer.entrySet()) {
Assertions.assertEquals(0L, rtContainer.getValueSupplier().apply(entry.getKey()));
@@ -52,16 +52,16 @@ public class MetadataStatCompositeTest {
@Test
void testIncrement() {
MetadataStatComposite statComposite = new MetadataStatComposite();
- statComposite.increment(MetadataEvent.Type.P_TOTAL, applicationName);
- Assertions.assertEquals(1L, statComposite.numStats.get(MetadataEvent.Type.P_TOTAL).get(applicationName).get());
+ statComposite.increment(MetadataEvent.ApplicationType.P_TOTAL, applicationName);
+ Assertions.assertEquals(1L, statComposite.applicationNumStats.get(MetadataEvent.ApplicationType.P_TOTAL).get(applicationName).get());
}
@Test
void testCalcRt() {
MetadataStatComposite statComposite = new MetadataStatComposite();
- statComposite.calcRt(applicationName, OP_TYPE_SUBSCRIBE, 10L);
- Assertions.assertTrue(statComposite.rtStats.stream().anyMatch(longContainer -> longContainer.specifyType(OP_TYPE_SUBSCRIBE)));
- Optional> subContainer = statComposite.rtStats.stream().filter(longContainer -> longContainer.specifyType(OP_TYPE_SUBSCRIBE)).findFirst();
+ statComposite.calcApplicationRt(applicationName, OP_TYPE_SUBSCRIBE, 10L);
+ Assertions.assertTrue(statComposite.appRtStats.stream().anyMatch(longContainer -> longContainer.specifyType(OP_TYPE_SUBSCRIBE)));
+ Optional> subContainer = statComposite.appRtStats.stream().filter(longContainer -> longContainer.specifyType(OP_TYPE_SUBSCRIBE)).findFirst();
subContainer.ifPresent(v -> Assertions.assertEquals(10L, v.get(applicationName).longValue()));
}
}
diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/stat/ServiceKeyMetric.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/stat/ServiceKeyMetric.java
index f77fe9e5f1..9fa387418e 100644
--- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/stat/ServiceKeyMetric.java
+++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/stat/ServiceKeyMetric.java
@@ -46,7 +46,6 @@ public class ServiceKeyMetric implements Metric {
tags.put(TAG_IP, getLocalHost());
tags.put(TAG_HOSTNAME, getLocalHostName());
tags.put(TAG_APPLICATION_NAME, applicationName);
-
tags.put(TAG_INTERFACE_KEY, serviceKey);
return tags;
}
From feaa530589fdc39e76771cdacb65b4ec58e4b181 Mon Sep 17 00:00:00 2001
From: aamingaa <49740762+aamingaa@users.noreply.github.com>
Date: Wed, 22 Mar 2023 13:25:15 +0800
Subject: [PATCH 002/122] feat: change default mode (#11653)
---
.../manager/ExecutorRepository.java | 8 +-
.../dubbo/config/ApplicationConfig.java | 20 +--
.../common/extension/ExtensionLoaderTest.java | 6 +-
.../dubbo/config/ApplicationConfigTest.java | 5 +-
.../transport/dispatcher/ChannelHandlers.java | 2 +-
.../support/header/HeartbeatHandlerTest.java | 20 ++-
.../transport/netty/ClientReconnectTest.java | 15 ++-
.../transport/netty/NettyClientTest.java | 38 ++++--
.../netty/NettyClientToServerTest.java | 14 +++
.../transport/netty/NettyStringTest.java | 18 ++-
.../transport/netty/ThreadNameTest.java | 17 ++-
.../transport/netty4/ClientReconnectTest.java | 32 ++++-
.../transport/netty4/ConnectionTest.java | 19 ++-
.../netty4/NettyClientToServerTest.java | 33 ++++-
.../netty4/NettyTransporterTest.java | 29 ++++-
.../netty4/PortUnificationExchangerTest.java | 19 ++-
.../netty4/PortUnificationServerTest.java | 19 ++-
.../netty4/ReplierDispatcherTest.java | 20 ++-
...ultiplexProtocolConnectionManagerTest.java | 20 +++
.../SingleProtocolConnectionManagerTest.java | 19 ++-
.../managemode}/ChannelHandlersTest.java | 4 +-
.../ConnectChannelHandlerTest.java | 4 +-
.../dubbo/managemode/MockedChannel.java | 115 ++++++++++++++++++
.../managemode/MockedChannelHandler.java | 61 ++++++++++
.../WrappedChannelHandlerTest.java | 6 +-
25 files changed, 500 insertions(+), 63 deletions(-)
rename {dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/dispatcher => dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode}/ChannelHandlersTest.java (93%)
rename {dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler => dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode}/ConnectChannelHandlerTest.java (99%)
create mode 100644 dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannel.java
create mode 100644 dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannelHandler.java
rename {dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler => dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode}/WrappedChannelHandlerTest.java (98%)
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepository.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepository.java
index e9e13b77c7..56e79fa08f 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepository.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepository.java
@@ -22,19 +22,19 @@ import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ApplicationConfig;
-import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.executor.ExecutorSupport;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
-import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION;
/**
*
*/
-@SPI(value = "default", scope = ExtensionScope.APPLICATION)
+@SPI(value = "isolation", scope = ExtensionScope.APPLICATION)
public interface ExecutorRepository {
/**
@@ -187,7 +187,7 @@ public interface ExecutorRepository {
static String getMode(ApplicationModel applicationModel) {
Optional optional = applicationModel.getApplicationConfigManager().getApplication();
- return optional.map(ApplicationConfig::getExecutorManagementMode).orElse(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ return optional.map(ApplicationConfig::getExecutorManagementMode).orElse(EXECUTOR_MANAGEMENT_MODE_ISOLATION);
}
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java
index 78198f2462..63dcfb5375 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java
@@ -16,14 +16,6 @@
*/
package org.apache.dubbo.config;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
import org.apache.dubbo.common.compiler.support.AdaptiveCompiler;
import org.apache.dubbo.common.infra.InfraAdapter;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
@@ -33,6 +25,14 @@ import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ApplicationModel;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_VERSION_KEY;
@@ -40,7 +40,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY;
import static org.apache.dubbo.common.constants.CommonConstants.DUMP_ENABLE;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE;
-import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION;
import static org.apache.dubbo.common.constants.CommonConstants.HOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LIVENESS_PROBE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_KEY;
@@ -274,7 +274,7 @@ public class ApplicationConfig extends AbstractConfig {
}
}
if (executorManagementMode == null) {
- executorManagementMode = EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+ executorManagementMode = EXECUTOR_MANAGEMENT_MODE_ISOLATION;
}
if (enableFileCache == null) {
enableFileCache = Boolean.TRUE;
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java
index ff62b95ea7..9913fbd966 100644
--- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java
+++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java
@@ -720,7 +720,7 @@ class ExtensionLoaderTest {
void testDuplicatedImplWithoutOverriddenStrategy() {
List loadingStrategies = ExtensionLoader.getLoadingStrategies();
ExtensionLoader.setLoadingStrategies(new DubboExternalLoadingStrategyTest(false),
- new DubboInternalLoadingStrategyTest(false));
+ new DubboInternalLoadingStrategyTest(false));
ExtensionLoader extensionLoader = getExtensionLoader(DuplicatedWithoutOverriddenExt.class);
try {
extensionLoader.getExtension("duplicated");
@@ -738,7 +738,7 @@ class ExtensionLoaderTest {
void testDuplicatedImplWithOverriddenStrategy() {
List loadingStrategies = ExtensionLoader.getLoadingStrategies();
ExtensionLoader.setLoadingStrategies(new DubboExternalLoadingStrategyTest(true),
- new DubboInternalLoadingStrategyTest(true));
+ new DubboInternalLoadingStrategyTest(true));
ExtensionLoader extensionLoader = getExtensionLoader(DuplicatedOverriddenExt.class);
DuplicatedOverriddenExt duplicatedOverriddenExt = extensionLoader.getExtension("duplicated");
assertEquals("DuplicatedOverriddenExt1", duplicatedOverriddenExt.echo());
@@ -832,4 +832,4 @@ class ExtensionLoaderTest {
return MAX_PRIORITY;
}
}
-}
\ No newline at end of file
+}
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java
index ee7be3f03c..a6ec4dac6e 100644
--- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java
+++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java
@@ -18,7 +18,6 @@
package org.apache.dubbo.config;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
-
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@@ -31,7 +30,7 @@ import java.util.Map;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY;
-import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP;
import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -346,7 +345,7 @@ class ApplicationConfigTest {
ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication();
Assertions.assertEquals(DUBBO, applicationConfig.getProtocol());
- Assertions.assertEquals(EXECUTOR_MANAGEMENT_MODE_DEFAULT, applicationConfig.getExecutorManagementMode());
+ Assertions.assertEquals(EXECUTOR_MANAGEMENT_MODE_ISOLATION, applicationConfig.getExecutorManagementMode());
Assertions.assertEquals(Boolean.TRUE, applicationConfig.getEnableFileCache());
DubboBootstrap.getInstance().destroy();
diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java
index 42fdcaf3dd..f11163515a 100644
--- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java
+++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java
@@ -33,7 +33,7 @@ public class ChannelHandlers {
return ChannelHandlers.getInstance().wrapInternal(handler, url);
}
- protected static ChannelHandlers getInstance() {
+ public static ChannelHandlers getInstance() {
return INSTANCE;
}
diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java
index d457f5e33a..608a530731 100644
--- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java
@@ -21,6 +21,7 @@ import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.NetUtils;
+import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
@@ -30,7 +31,7 @@ import org.apache.dubbo.remoting.exchange.ExchangeHandler;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.transport.dispatcher.FakeChannelHandlers;
-
+import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -38,6 +39,8 @@ import org.junit.jupiter.api.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+
class HeartbeatHandlerTest {
private static final Logger logger = LoggerFactory.getLogger(HeartbeatHandlerTest.class);
@@ -72,6 +75,11 @@ class HeartbeatHandlerTest {
.addParameter(Constants.HEARTBEAT_KEY, 1000);
CountDownLatch connect = new CountDownLatch(1);
CountDownLatch disconnect = new CountDownLatch(1);
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ serverURL = serverURL.setScopeModel(applicationModel);
TestHeartbeatHandler handler = new TestHeartbeatHandler(connect, disconnect);
server = Exchangers.bind(serverURL, handler);
System.out.println("Server bind successfully");
@@ -97,6 +105,11 @@ class HeartbeatHandlerTest {
.addParameter(Constants.TRANSPORTER_KEY, "netty3")
.addParameter(Constants.HEARTBEAT_KEY, 1000)
.addParameter(Constants.CODEC_KEY, "telnet");
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ serverURL = serverURL.setScopeModel(applicationModel);
CountDownLatch connect = new CountDownLatch(1);
CountDownLatch disconnect = new CountDownLatch(1);
TestHeartbeatHandler handler = new TestHeartbeatHandler(connect, disconnect);
@@ -118,6 +131,11 @@ class HeartbeatHandlerTest {
.addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME)
.addParameter(Constants.TRANSPORTER_KEY, "netty3")
.addParameter(Constants.CODEC_KEY, "telnet");
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ serverURL = serverURL.setScopeModel(applicationModel);
CountDownLatch connect = new CountDownLatch(1);
CountDownLatch disconnect = new CountDownLatch(1);
TestHeartbeatHandler handler = new TestHeartbeatHandler(connect, disconnect);
diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java
index a90828dbad..f4229aa56d 100644
--- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java
@@ -16,8 +16,10 @@
*/
package org.apache.dubbo.remoting.transport.netty;
+import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.DubboAppender;
import org.apache.dubbo.common.utils.NetUtils;
+import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Client;
import org.apache.dubbo.remoting.Constants;
@@ -25,12 +27,14 @@ import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
-
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+
/**
* Client reconnect test
*/
@@ -71,8 +75,13 @@ class ClientReconnectTest {
public Client startClient(int port, int heartbeat) throws RemotingException {
- final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?check=false&codec=exchange&client=netty3&" +
- Constants.HEARTBEAT_KEY + "=" + heartbeat;
+ URL url = URL.valueOf("exchange://127.0.0.1:" + port + "/client.reconnect.test?check=false&codec=exchange&client=netty3&" +
+ Constants.HEARTBEAT_KEY + "=" + heartbeat);
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ url = url.setScopeModel(applicationModel);
return Exchangers.connect(url);
}
diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientTest.java
index 675a1474a0..4b14d0f4b1 100644
--- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientTest.java
@@ -18,11 +18,11 @@ package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
-import org.apache.dubbo.remoting.RemotingException;
+import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.Exchangers;
-
+import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -30,6 +30,8 @@ import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+
/**
* Date: 5/3/11
* Time: 5:47 PM
@@ -40,7 +42,13 @@ class NettyClientTest {
@BeforeAll
public static void setUp() throws Exception {
- server = Exchangers.bind(URL.valueOf("exchange://localhost:" + port + "?server=netty3&codec=exchange"), new TelnetServerHandler());
+ URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty3&codec=exchange");
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ url = url.setScopeModel(applicationModel);
+ server = Exchangers.bind(url, new TelnetServerHandler());
}
@AfterAll
@@ -52,16 +60,22 @@ class NettyClientTest {
}
}
- public static void main(String[] args) throws RemotingException, InterruptedException {
- ExchangeChannel client = Exchangers.connect(URL.valueOf("exchange://10.20.153.10:20880?client=netty3&heartbeat=1000&codec=exchange"));
- Thread.sleep(60 * 1000 * 50);
- }
+// public static void main(String[] args) throws RemotingException, InterruptedException {
+// ExchangeChannel client = Exchangers.connect(URL.valueOf("exchange://10.20.153.10:20880?client=netty3&heartbeat=1000&codec=exchange"));
+// Thread.sleep(60 * 1000 * 50);
+// }
@Test
void testClientClose() throws Exception {
List clients = new ArrayList(100);
for (int i = 0; i < 100; i++) {
- ExchangeChannel client = Exchangers.connect(URL.valueOf("exchange://localhost:" + port + "?client=netty3&codec=exchange"));
+ URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty3&codec=exchange");
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ url = url.setScopeModel(applicationModel);
+ ExchangeChannel client = Exchangers.connect(url);
Thread.sleep(5);
clients.add(client);
}
@@ -74,7 +88,13 @@ class NettyClientTest {
@Test
void testServerClose() throws Exception {
for (int i = 0; i < 100; i++) {
- RemotingServer aServer = Exchangers.bind(URL.valueOf("exchange://localhost:" + NetUtils.getAvailablePort(6000) + "?server=netty3&codec=exchange"), new TelnetServerHandler());
+ URL url = URL.valueOf("exchange://localhost:" + NetUtils.getAvailablePort(6000) + "?server=netty3&codec=exchange");
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ url = url.setScopeModel(applicationModel);
+ RemotingServer aServer = Exchangers.bind(url, new TelnetServerHandler());
aServer.close();
}
}
diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java
index 4a871e0fb7..57131fcbc6 100644
--- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java
@@ -17,12 +17,16 @@
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.Replier;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
/**
* NettyClientToServerTest
@@ -33,6 +37,11 @@ class NettyClientToServerTest extends ClientToServerTest {
// add heartbeat cycle to avoid unstable ut.
URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty3&codec=exchange");
url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000);
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ url = url.setScopeModel(applicationModel);
return Exchangers.bind(url, receiver);
}
@@ -40,6 +49,11 @@ class NettyClientToServerTest extends ClientToServerTest {
// add heartbeat cycle to avoid unstable ut.
URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty3&timeout=3000&codec=exchange");
url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000);
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ url = url.setScopeModel(applicationModel);
return Exchangers.connect(url);
}
diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyStringTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyStringTest.java
index d1221f8ec0..8b1fde4034 100644
--- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyStringTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyStringTest.java
@@ -18,14 +18,17 @@ package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
+import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
-
+import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+
/**
* Date: 4/26/11
* Time: 4:13 PM
@@ -40,8 +43,17 @@ class NettyStringTest {
//int port = 10001;
int port = NetUtils.getAvailablePort();
System.out.println(port);
- server = Exchangers.bind(URL.valueOf("telnet://0.0.0.0:" + port + "?server=netty3&codec=telnet"), new TelnetServerHandler());
- client = Exchangers.connect(URL.valueOf("telnet://127.0.0.1:" + port + "?client=netty3&codec=telnet"), new TelnetClientHandler());
+ URL serverURL = URL.valueOf("telnet://0.0.0.0:" + port + "?server=netty3&codec=telnet");
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ serverURL = serverURL.setScopeModel(applicationModel);
+
+ URL clientURL = URL.valueOf("telnet://127.0.0.1:" + port + "?client=netty3&codec=telnet");
+ clientURL = clientURL.setScopeModel(applicationModel);
+ server = Exchangers.bind(serverURL, new TelnetServerHandler());
+ client = Exchangers.connect(clientURL, new TelnetClientHandler());
}
@AfterAll
diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ThreadNameTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ThreadNameTest.java
index d990649654..203cc35353 100644
--- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ThreadNameTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ThreadNameTest.java
@@ -18,11 +18,11 @@ package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
+import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.rpc.model.ApplicationModel;
-
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@@ -32,6 +32,8 @@ import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+
class ThreadNameTest {
private NettyServer server;
@@ -53,12 +55,15 @@ class ThreadNameTest {
public void before() throws Exception {
int port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000));
serverURL = URL.valueOf("telnet://localhost?side=provider&codec=telnet")
- .setPort(port)
- .setScopeModel(ApplicationModel.defaultModel());
+ .setPort(port);
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ serverURL = serverURL.setScopeModel(applicationModel);
clientURL = URL.valueOf("telnet://localhost?side=consumer&codec=telnet")
- .setPort(port)
- .setScopeModel(ApplicationModel.defaultModel());
-
+ .setPort(port);
+ clientURL = clientURL.setScopeModel(applicationModel);
serverHandler = new ThreadNameVerifyHandler(serverRegex, false, serverLatch);
clientHandler = new ThreadNameVerifyHandler(clientRegex, true, clientLatch);
server = new NettyServer(serverURL, serverHandler);
diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java
index 03918da077..369108ea6b 100644
--- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java
@@ -16,8 +16,12 @@
*/
package org.apache.dubbo.remoting.transport.netty4;
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.DubboAppender;
import org.apache.dubbo.common.utils.NetUtils;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Client;
import org.apache.dubbo.remoting.Constants;
@@ -25,12 +29,15 @@ import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
-
+import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+
/**
* Client reconnect test
*/
@@ -74,12 +81,31 @@ class ClientReconnectTest {
public Client startClient(int port, int heartbeat) throws RemotingException {
- final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?client=netty4&check=false&" + Constants.HEARTBEAT_KEY + "=" + heartbeat;
+ URL url = URL.valueOf("exchange://127.0.0.1:" + port + "/client.reconnect.test?client=netty4&check=false&" + Constants.HEARTBEAT_KEY + "=" + heartbeat);
+ FrameworkModel frameworkModel = new FrameworkModel();
+ ApplicationModel applicationModel = frameworkModel.newApplication();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ ConfigManager configManager = new ConfigManager(applicationModel);
+ configManager.setApplication(applicationConfig);
+ configManager.getApplication();
+ applicationModel.setConfigManager(configManager);
+ url = url.putAttribute(CommonConstants.SCOPE_MODEL, applicationModel);
return Exchangers.connect(url);
}
public RemotingServer startServer(int port) throws RemotingException {
- final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?server=netty4";
+ URL url = URL.valueOf("exchange://127.0.0.1:" + port + "/client.reconnect.test?server=netty4");
+ FrameworkModel frameworkModel = new FrameworkModel();
+ ApplicationModel applicationModel = frameworkModel.newApplication();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ ConfigManager configManager = new ConfigManager(applicationModel);
+ configManager.setApplication(applicationConfig);
+ configManager.getApplication();
+ applicationModel.setConfigManager(configManager);
+ ModuleModel moduleModel = applicationModel.getDefaultModule();
+ url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
return Exchangers.bind(url, new HandlerAdapter());
}
diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java
index 0c5d8c4845..2c230d6c61 100644
--- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java
@@ -17,13 +17,17 @@
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.NetUtils;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.api.connection.ConnectionManager;
import org.apache.dubbo.remoting.api.connection.MultiplexProtocolConnectionManager;
import org.apache.dubbo.remoting.api.pu.DefaultPuHandler;
-
+import org.apache.dubbo.rpc.model.ApplicationModel;
+import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
@@ -34,6 +38,8 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+
public class ConnectionTest {
@@ -47,6 +53,17 @@ public class ConnectionTest {
public static void init() throws RemotingException {
int port = NetUtils.getAvailablePort();
url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar");
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ ConfigManager configManager = new ConfigManager(applicationModel);
+ configManager.setApplication(applicationConfig);
+ configManager.getApplication();
+ applicationModel.setConfigManager(configManager);
+ url = url.setScopeModel(applicationModel);
+ ModuleModel moduleModel = applicationModel.getDefaultModule();
+ url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
server = new NettyPortUnificationServer(url, new DefaultPuHandler());
server.bind();
connectionManager = url.getOrDefaultFrameworkModel().getExtensionLoader(ConnectionManager.class).getExtension(MultiplexProtocolConnectionManager.NAME);
diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java
index 79fe9b2571..2f0f6e03fb 100644
--- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java
@@ -17,12 +17,19 @@
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.constants.CommonConstants;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.Replier;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+import org.apache.dubbo.rpc.model.ModuleModel;
+
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
/**
* Netty4ClientToServerTest
@@ -32,7 +39,20 @@ class NettyClientToServerTest extends ClientToServerTest {
protected ExchangeServer newServer(int port, Replier> receiver) throws RemotingException {
// add heartbeat cycle to avoid unstable ut.
URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty4");
- url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000);
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ ConfigManager configManager = new ConfigManager(applicationModel);
+ configManager.setApplication(applicationConfig);
+ configManager.getApplication();
+ applicationModel.setConfigManager(configManager);
+ url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000).putAttribute(CommonConstants.SCOPE_MODEL, applicationModel);
+ url = url.setScopeModel(applicationModel);
+// ModuleModel moduleModel = applicationModel.getDefaultModule();
+
+ ModuleModel moduleModel = applicationModel.getDefaultModule();
+ url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
return Exchangers.bind(url, receiver);
}
@@ -40,6 +60,17 @@ class NettyClientToServerTest extends ClientToServerTest {
// add heartbeat cycle to avoid unstable ut.
URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty4&timeout=3000");
url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000);
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ ConfigManager configManager = new ConfigManager(applicationModel);
+ configManager.setApplication(applicationConfig);
+ configManager.getApplication();
+ applicationModel.setConfigManager(configManager);
+ url = url.setScopeModel(applicationModel);
+ ModuleModel moduleModel = applicationModel.getDefaultModule();
+ url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
return Exchangers.connect(url);
}
diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java
index 17b0db79f2..772f3d604a 100644
--- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java
@@ -17,18 +17,24 @@
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.NetUtils;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -39,6 +45,17 @@ class NettyTransporterTest {
URL url = new ServiceConfigURL("telnet", "localhost", port,
new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)});
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ ConfigManager configManager = new ConfigManager(applicationModel);
+ configManager.setApplication(applicationConfig);
+ configManager.getApplication();
+ applicationModel.setConfigManager(configManager);
+ url = url.setScopeModel(applicationModel);
+ ModuleModel moduleModel = applicationModel.getDefaultModule();
+ url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
RemotingServer server = new NettyTransporter().bind(url, new ChannelHandlerAdapter());
assertThat(server.isBound(), is(true));
@@ -51,7 +68,17 @@ class NettyTransporterTest {
int port = NetUtils.getAvailablePort();
URL url = new ServiceConfigURL("telnet", "localhost", port,
new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)});
-
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ ConfigManager configManager = new ConfigManager(applicationModel);
+ configManager.setApplication(applicationConfig);
+ configManager.getApplication();
+ applicationModel.setConfigManager(configManager);
+ url = url.setScopeModel(applicationModel);
+ ModuleModel moduleModel = applicationModel.getDefaultModule();
+ url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
new NettyTransporter().bind(url, new ChannelHandlerAdapter() {
@Override
diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationExchangerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationExchangerTest.java
index f06c018f3e..faa9de8869 100644
--- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationExchangerTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationExchangerTest.java
@@ -17,16 +17,22 @@
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.NetUtils;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.api.pu.DefaultPuHandler;
import org.apache.dubbo.remoting.exchange.PortUnificationExchanger;
-
+import org.apache.dubbo.rpc.model.ApplicationModel;
+import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+
class PortUnificationExchangerTest {
private static URL url;
@@ -35,6 +41,17 @@ class PortUnificationExchangerTest {
public static void init() throws RemotingException {
int port = NetUtils.getAvailablePort();
url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar");
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ ConfigManager configManager = new ConfigManager(applicationModel);
+ configManager.setApplication(applicationConfig);
+ configManager.getApplication();
+ applicationModel.setConfigManager(configManager);
+ url = url.setScopeModel(applicationModel);
+ ModuleModel moduleModel = applicationModel.getDefaultModule();
+ url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
}
@Test
diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationServerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationServerTest.java
index 61273baf4c..0f5268da89 100644
--- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationServerTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationServerTest.java
@@ -17,20 +17,37 @@
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.NetUtils;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.pu.DefaultPuHandler;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+
class PortUnificationServerTest {
@Test
void testBind() throws RemotingException {
int port = NetUtils.getAvailablePort();
URL url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar");
-
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ ConfigManager configManager = new ConfigManager(applicationModel);
+ configManager.setApplication(applicationConfig);
+ configManager.getApplication();
+ applicationModel.setConfigManager(configManager);
+ url = url.setScopeModel(applicationModel);
+ ModuleModel moduleModel = applicationModel.getDefaultModule();
+ url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
// abstract endpoint need to get codec of url(which is in triple package)
final NettyPortUnificationServer server = new NettyPortUnificationServer(url, new DefaultPuHandler());
server.bind();
diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ReplierDispatcherTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ReplierDispatcherTest.java
index 5d76aa0099..bc3f5d8cbb 100644
--- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ReplierDispatcherTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ReplierDispatcherTest.java
@@ -19,12 +19,15 @@ package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.NetUtils;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ReplierDispatcher;
-
+import org.apache.dubbo.rpc.model.ApplicationModel;
+import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@@ -38,6 +41,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
import static org.junit.jupiter.api.Assertions.fail;
@@ -59,7 +63,19 @@ class ReplierDispatcherTest {
ReplierDispatcher dispatcher = new ReplierDispatcher();
dispatcher.addReplier(RpcMessage.class, new RpcMessageHandler());
dispatcher.addReplier(Data.class, (channel, msg) -> new StringMessage("hello world"));
- exchangeServer = Exchangers.bind(URL.valueOf("exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000"), dispatcher);
+ URL url = URL.valueOf("exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000");
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ ConfigManager configManager = new ConfigManager(applicationModel);
+ configManager.setApplication(applicationConfig);
+ configManager.getApplication();
+ applicationModel.setConfigManager(configManager);
+ url = url.setScopeModel(applicationModel);
+ ModuleModel moduleModel = applicationModel.getDefaultModule();
+ url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
+ exchangeServer = Exchangers.bind(url, dispatcher);
}
diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/MultiplexProtocolConnectionManagerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/MultiplexProtocolConnectionManagerTest.java
index 634c4a72c1..2bceec7ab6 100644
--- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/MultiplexProtocolConnectionManagerTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/MultiplexProtocolConnectionManagerTest.java
@@ -18,6 +18,9 @@
package org.apache.dubbo.remoting.transport.netty4.api;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.constants.CommonConstants;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.api.connection.ConnectionManager;
@@ -25,6 +28,8 @@ import org.apache.dubbo.remoting.api.connection.MultiplexProtocolConnectionManag
import org.apache.dubbo.remoting.api.pu.DefaultPuHandler;
import org.apache.dubbo.remoting.transport.netty4.NettyPortUnificationServer;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
@@ -34,6 +39,8 @@ import java.lang.reflect.Field;
import java.util.Map;
import java.util.function.Consumer;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+
public class MultiplexProtocolConnectionManagerTest {
private static URL url1;
@@ -46,8 +53,21 @@ public class MultiplexProtocolConnectionManagerTest {
@BeforeAll
public static void init() throws RemotingException {
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ ConfigManager configManager = new ConfigManager(applicationModel);
+ configManager.setApplication(applicationConfig);
+ configManager.getApplication();
+ applicationModel.setConfigManager(configManager);
url1 = URL.valueOf("empty://127.0.0.1:8080?foo=bar");
url2 = URL.valueOf("tri://127.0.0.1:8081?foo=bar");
+ url1 = url1.setScopeModel(applicationModel);
+ ModuleModel moduleModel = applicationModel.getDefaultModule();
+ url1 = url1.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
+ url2 = url2.setScopeModel(applicationModel);
+ url2 = url2.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
server = new NettyPortUnificationServer(url1, new DefaultPuHandler());
server.bind();
connectionManager = url1.getOrDefaultFrameworkModel()
diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/SingleProtocolConnectionManagerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/SingleProtocolConnectionManagerTest.java
index fab70fd76e..bc4d548008 100644
--- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/SingleProtocolConnectionManagerTest.java
+++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/SingleProtocolConnectionManagerTest.java
@@ -18,7 +18,10 @@
package org.apache.dubbo.remoting.transport.netty4.api;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.NetUtils;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.api.connection.ConnectionManager;
@@ -26,7 +29,8 @@ import org.apache.dubbo.remoting.api.connection.SingleProtocolConnectionManager;
import org.apache.dubbo.remoting.api.pu.DefaultPuHandler;
import org.apache.dubbo.remoting.transport.netty4.NettyConnectionClient;
import org.apache.dubbo.remoting.transport.netty4.NettyPortUnificationServer;
-
+import org.apache.dubbo.rpc.model.ApplicationModel;
+import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
@@ -36,6 +40,8 @@ import java.lang.reflect.Field;
import java.util.Map;
import java.util.function.Consumer;
+import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
+
public class SingleProtocolConnectionManagerTest {
private static URL url;
@@ -48,6 +54,17 @@ public class SingleProtocolConnectionManagerTest {
public static void init() throws RemotingException {
int port = NetUtils.getAvailablePort();
url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar");
+ ApplicationModel applicationModel = ApplicationModel.defaultModel();
+ ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
+ applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
+ applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
+ ConfigManager configManager = new ConfigManager(applicationModel);
+ configManager.setApplication(applicationConfig);
+ configManager.getApplication();
+ applicationModel.setConfigManager(configManager);
+ url = url.setScopeModel(applicationModel);
+ ModuleModel moduleModel = applicationModel.getDefaultModule();
+ url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
server = new NettyPortUnificationServer(url, new DefaultPuHandler());
server.bind();
connectionManager = url.getOrDefaultFrameworkModel()
diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlersTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ChannelHandlersTest.java
similarity index 93%
rename from dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlersTest.java
rename to dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ChannelHandlersTest.java
index 8c7ccbf724..4876dd7b85 100644
--- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlersTest.java
+++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ChannelHandlersTest.java
@@ -14,13 +14,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.remoting.transport.dispatcher;
+package org.apache.dubbo.rpc.protocol.dubbo.managemode;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.transport.MultiMessageHandler;
-
+import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/ConnectChannelHandlerTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ConnectChannelHandlerTest.java
similarity index 99%
rename from dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/ConnectChannelHandlerTest.java
rename to dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ConnectChannelHandlerTest.java
index c131b8bbe7..352a8c2738 100644
--- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/ConnectChannelHandlerTest.java
+++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ConnectChannelHandlerTest.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.remoting.handler;
+package org.apache.dubbo.rpc.protocol.dubbo.managemode;
import org.apache.dubbo.remoting.ExecutionException;
import org.apache.dubbo.remoting.RemotingException;
@@ -22,7 +22,6 @@ import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.exchange.Response;
import org.apache.dubbo.remoting.transport.dispatcher.connection.ConnectionOrderedChannelHandler;
import org.apache.dubbo.rpc.model.ApplicationModel;
-
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
@@ -31,7 +30,6 @@ import org.junit.jupiter.api.Test;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
-
class ConnectChannelHandlerTest extends WrappedChannelHandlerTest {
@BeforeEach
diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannel.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannel.java
new file mode 100644
index 0000000000..baa35eac69
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannel.java
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.dubbo.managemode;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.remoting.Channel;
+import org.apache.dubbo.remoting.ChannelHandler;
+import org.apache.dubbo.remoting.RemotingException;
+
+import java.net.InetSocketAddress;
+import java.util.HashMap;
+import java.util.Map;
+
+public class MockedChannel implements Channel {
+ private boolean isClosed;
+ private volatile boolean closing = false;
+ private URL url;
+ private ChannelHandler handler;
+ private Map map = new HashMap();
+
+ public MockedChannel() {
+ super();
+ }
+
+
+ @Override
+ public URL getUrl() {
+ return url;
+ }
+
+ @Override
+ public ChannelHandler getChannelHandler() {
+
+ return this.handler;
+ }
+
+ @Override
+ public InetSocketAddress getLocalAddress() {
+
+ return null;
+ }
+
+ @Override
+ public void send(Object message) throws RemotingException {
+ }
+
+ @Override
+ public void send(Object message, boolean sent) throws RemotingException {
+ this.send(message);
+ }
+
+ @Override
+ public void close() {
+ isClosed = true;
+ }
+
+ @Override
+ public void close(int timeout) {
+ this.close();
+ }
+
+ @Override
+ public void startClose() {
+ closing = true;
+ }
+
+ @Override
+ public boolean isClosed() {
+ return isClosed;
+ }
+
+ @Override
+ public InetSocketAddress getRemoteAddress() {
+ return null;
+ }
+
+ @Override
+ public boolean isConnected() {
+ return false;
+ }
+
+ @Override
+ public boolean hasAttribute(String key) {
+ return map.containsKey(key);
+ }
+
+ @Override
+ public Object getAttribute(String key) {
+ return map.get(key);
+ }
+
+ @Override
+ public void setAttribute(String key, Object value) {
+ map.put(key, value);
+ }
+
+ @Override
+ public void removeAttribute(String key) {
+ map.remove(key);
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannelHandler.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannelHandler.java
new file mode 100644
index 0000000000..f2dc66abba
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannelHandler.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.dubbo.managemode;
+
+import org.apache.dubbo.common.utils.ConcurrentHashSet;
+import org.apache.dubbo.remoting.Channel;
+import org.apache.dubbo.remoting.ChannelHandler;
+import org.apache.dubbo.remoting.RemotingException;
+
+import java.util.Collections;
+import java.util.Set;
+
+public class MockedChannelHandler implements ChannelHandler {
+ // ConcurrentMap channels = new ConcurrentHashMap();
+ ConcurrentHashSet channels = new ConcurrentHashSet();
+
+ @Override
+ public void connected(Channel channel) throws RemotingException {
+ channels.add(channel);
+ }
+
+ @Override
+ public void disconnected(Channel channel) throws RemotingException {
+ channels.remove(channel);
+ }
+
+ @Override
+ public void sent(Channel channel, Object message) throws RemotingException {
+ channel.send(message);
+ }
+
+ @Override
+ public void received(Channel channel, Object message) throws RemotingException {
+ //echo
+ channel.send(message);
+ }
+
+ @Override
+ public void caught(Channel channel, Throwable exception) throws RemotingException {
+ throw new RemotingException(channel, exception);
+
+ }
+
+ public Set getChannels() {
+ return Collections.unmodifiableSet(channels);
+ }
+}
diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/WrappedChannelHandlerTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/WrappedChannelHandlerTest.java
similarity index 98%
rename from dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/WrappedChannelHandlerTest.java
rename to dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/WrappedChannelHandlerTest.java
index 4ef2f5203a..e0e567d9b8 100644
--- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/WrappedChannelHandlerTest.java
+++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/WrappedChannelHandlerTest.java
@@ -14,8 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.remoting.handler;
-
+package org.apache.dubbo.rpc.protocol.dubbo.managemode;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
@@ -28,7 +27,6 @@ import org.apache.dubbo.remoting.exchange.Response;
import org.apache.dubbo.remoting.exchange.support.DefaultFuture;
import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler;
import org.apache.dubbo.rpc.model.ApplicationModel;
-
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -40,7 +38,7 @@ import static org.junit.jupiter.api.Assertions.fail;
class WrappedChannelHandlerTest {
WrappedChannelHandler handler;
- URL url = URL.valueOf("test://10.20.30.40:1234");
+ URL url = URL.valueOf("dubbo://10.20.30.40:1234");
@BeforeEach
public void setUp() throws Exception {
From c283c4134794ed3d252855d38bde666c82d121c5 Mon Sep 17 00:00:00 2001
From: Albumen Kevin
Date: Thu, 23 Mar 2023 17:51:05 +0800
Subject: [PATCH 003/122] Only support rest convert when all servers are from
spring cloud (#11888)
---
...ServiceInstanceNotificationCustomizer.java | 36 +++++++++++--------
1 file changed, 21 insertions(+), 15 deletions(-)
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/SpringCloudServiceInstanceNotificationCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/SpringCloudServiceInstanceNotificationCustomizer.java
index 444f08fb69..750eb6e6e9 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/SpringCloudServiceInstanceNotificationCustomizer.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/SpringCloudServiceInstanceNotificationCustomizer.java
@@ -28,24 +28,30 @@ import java.util.concurrent.ConcurrentHashMap;
public class SpringCloudServiceInstanceNotificationCustomizer implements ServiceInstanceNotificationCustomizer {
@Override
public void customize(List serviceInstance) {
+ if (serviceInstance.isEmpty()) {
+ return;
+ }
+
+ if (!serviceInstance.stream().allMatch(instance -> "SPRING_CLOUD".equals(instance.getMetadata("preserved.register.source")))) {
+ return;
+ }
+
for (ServiceInstance instance : serviceInstance) {
- if ("SPRING_CLOUD".equals(instance.getMetadata("preserved.register.source"))) {
- MetadataInfo.ServiceInfo serviceInfo = new MetadataInfo.ServiceInfo("*", "*", "*", "rest", instance.getPort(), "*", new HashMap<>());
- String revision = "SPRING_CLOUD-" + instance.getServiceName() + "-" + instance.getAddress() + "-" + instance.getPort();
- MetadataInfo metadataInfo = new MetadataInfo(instance.getServiceName(), revision, new ConcurrentHashMap<>(Collections.singletonMap("*", serviceInfo))) {
- @Override
- public List getMatchedServiceInfos(ProtocolServiceKey consumerProtocolServiceKey) {
- getServices().putIfAbsent(consumerProtocolServiceKey.getServiceKeyString(),
- new MetadataInfo.ServiceInfo(consumerProtocolServiceKey.getInterfaceName(),
- consumerProtocolServiceKey.getGroup(), consumerProtocolServiceKey.getVersion(),
- consumerProtocolServiceKey.getProtocol(), instance.getPort(), consumerProtocolServiceKey.getInterfaceName(), new HashMap<>()));
- return super.getMatchedServiceInfos(consumerProtocolServiceKey);
- }
- };
+ MetadataInfo.ServiceInfo serviceInfo = new MetadataInfo.ServiceInfo("*", "*", "*", "rest", instance.getPort(), "*", new HashMap<>());
+ String revision = "SPRING_CLOUD-" + instance.getServiceName() + "-" + instance.getAddress() + "-" + instance.getPort();
+ MetadataInfo metadataInfo = new MetadataInfo(instance.getServiceName(), revision, new ConcurrentHashMap<>(Collections.singletonMap("*", serviceInfo))) {
+ @Override
+ public List getMatchedServiceInfos(ProtocolServiceKey consumerProtocolServiceKey) {
+ getServices().putIfAbsent(consumerProtocolServiceKey.getServiceKeyString(),
+ new MetadataInfo.ServiceInfo(consumerProtocolServiceKey.getInterfaceName(),
+ consumerProtocolServiceKey.getGroup(), consumerProtocolServiceKey.getVersion(),
+ consumerProtocolServiceKey.getProtocol(), instance.getPort(), consumerProtocolServiceKey.getInterfaceName(), new HashMap<>()));
+ return super.getMatchedServiceInfos(consumerProtocolServiceKey);
+ }
+ };
- instance.setServiceMetadata(metadataInfo);
- }
+ instance.setServiceMetadata(metadataInfo);
}
}
}
From 01049311ace1dfc0cbead9aa3cf1e1038fc6db0d Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Thu, 23 Mar 2023 19:48:31 +0800
Subject: [PATCH 004/122] Bump maven-plugin-api from 3.9.0 to 3.9.1 (#11868)
Bumps [maven-plugin-api](https://github.com/apache/maven) from 3.9.0 to 3.9.1.
- [Release notes](https://github.com/apache/maven/releases)
- [Commits](https://github.com/apache/maven/compare/maven-3.9.0...maven-3.9.1)
---
updated-dependencies:
- dependency-name: org.apache.maven:maven-plugin-api
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
dubbo-maven-plugin/pom.xml | 2 +-
dubbo-native-plugin/pom.xml | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/dubbo-maven-plugin/pom.xml b/dubbo-maven-plugin/pom.xml
index 6f2ddf18e9..c3b924dbc9 100644
--- a/dubbo-maven-plugin/pom.xml
+++ b/dubbo-maven-plugin/pom.xml
@@ -34,7 +34,7 @@
org.apache.mavenmaven-plugin-api
- 3.9.0
+ 3.9.1
diff --git a/dubbo-native-plugin/pom.xml b/dubbo-native-plugin/pom.xml
index c41fa9d15e..cd1a9d7e30 100644
--- a/dubbo-native-plugin/pom.xml
+++ b/dubbo-native-plugin/pom.xml
@@ -36,7 +36,7 @@
org.apache.mavenmaven-plugin-api
- 3.9.0
+ 3.9.1
From 08f3c6b0185438e43187390505c9639f9d66e60c Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Thu, 23 Mar 2023 19:48:52 +0800
Subject: [PATCH 005/122] Bump maven-core from 3.9.0 to 3.9.1 (#11869)
Bumps [maven-core](https://github.com/apache/maven) from 3.9.0 to 3.9.1.
- [Release notes](https://github.com/apache/maven/releases)
- [Commits](https://github.com/apache/maven/compare/maven-3.9.0...maven-3.9.1)
---
updated-dependencies:
- dependency-name: org.apache.maven:maven-core
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
dubbo-maven-plugin/pom.xml | 2 +-
dubbo-native-plugin/pom.xml | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/dubbo-maven-plugin/pom.xml b/dubbo-maven-plugin/pom.xml
index c3b924dbc9..0b3302d763 100644
--- a/dubbo-maven-plugin/pom.xml
+++ b/dubbo-maven-plugin/pom.xml
@@ -40,7 +40,7 @@
org.apache.mavenmaven-core
- 3.9.0
+ 3.9.1provided
diff --git a/dubbo-native-plugin/pom.xml b/dubbo-native-plugin/pom.xml
index cd1a9d7e30..f3bf948f03 100644
--- a/dubbo-native-plugin/pom.xml
+++ b/dubbo-native-plugin/pom.xml
@@ -42,7 +42,7 @@
org.apache.mavenmaven-core
- 3.9.0
+ 3.9.1provided
From 3f8a16f0ac04b9f6bca18d48d13f8d0d0dc1fdf4 Mon Sep 17 00:00:00 2001
From: wxbty <38374721+wxbty@users.noreply.github.com>
Date: Thu, 23 Mar 2023 19:50:11 +0800
Subject: [PATCH 006/122] support exception process when service not found
(#11088)
---
.../common/constants/CommonConstants.java | 5 +
dubbo-distribution/dubbo-all/pom.xml | 6 +
.../rpc/protocol/dubbo/ByteAccessor.java | 41 ++++
.../dubbo/DecodeableRpcInvocation.java | 183 +++++++++---------
.../dubbo/rpc/protocol/dubbo/DubboCodec.java | 22 ++-
5 files changed, 164 insertions(+), 93 deletions(-)
create mode 100644 dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ByteAccessor.java
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java
index 62ff4beeeb..6a723f78a4 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java
@@ -620,5 +620,10 @@ public interface CommonConstants {
String ENCODE_IN_IO_THREAD_KEY = "encode.in.io";
boolean DEFAULT_ENCODE_IN_IO_THREAD = false;
+ /**
+ * @since 3.2.0
+ */
+ String BYTE_ACCESSOR_KEY = "byte.accessor";
+
String PAYLOAD = "payload";
}
diff --git a/dubbo-distribution/dubbo-all/pom.xml b/dubbo-distribution/dubbo-all/pom.xml
index 1e0501e7d4..a5e7f381ea 100644
--- a/dubbo-distribution/dubbo-all/pom.xml
+++ b/dubbo-distribution/dubbo-all/pom.xml
@@ -1004,6 +1004,12 @@
META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter
+
+
+ META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.dubbo.ByteAccessor
+
+
diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ByteAccessor.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ByteAccessor.java
new file mode 100644
index 0000000000..e0913486da
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ByteAccessor.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.dubbo;
+
+import org.apache.dubbo.common.extension.SPI;
+import org.apache.dubbo.remoting.Channel;
+import org.apache.dubbo.remoting.exchange.Request;
+
+import java.io.InputStream;
+
+import static org.apache.dubbo.common.extension.ExtensionScope.FRAMEWORK;
+
+/**
+ * Extension of Byte Accessor, holding attributes as RpcInvocation objects
+ * so that the decoded service can be used more flexibly
+ * @since 3.2.0
+ */
+@SPI(scope = FRAMEWORK)
+public interface ByteAccessor {
+
+ /**
+ * Get an enhanced DecodeableRpcInvocation subclass to allow custom decode.
+ * The parameters are the same as {@link DecodeableRpcInvocation}
+ */
+ DecodeableRpcInvocation getRpcInvocation(Channel channel, Request req, InputStream is, byte proto);
+}
diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java
index c133913f9b..76b3f5ce76 100644
--- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java
+++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java
@@ -16,7 +16,6 @@
*/
package org.apache.dubbo.rpc.protocol.dubbo;
-
import org.apache.dubbo.common.utils.CacheableSupplier;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
@@ -60,21 +59,21 @@ import static org.apache.dubbo.rpc.Constants.SERIALIZATION_SECURITY_CHECK_KEY;
public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Decodeable {
- private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DecodeableRpcInvocation.class);
+ protected static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DecodeableRpcInvocation.class);
- private final Channel channel;
+ protected final transient Channel channel;
- private final byte serializationType;
+ protected final byte serializationType;
- private final InputStream inputStream;
+ protected final transient InputStream inputStream;
- private final Request request;
+ protected final transient Request request;
- private volatile boolean hasDecoded;
+ protected volatile boolean hasDecoded;
protected final FrameworkModel frameworkModel;
- private final Supplier callbackServiceCodecFactory;
+ protected final transient Supplier callbackServiceCodecFactory;
public DecodeableRpcInvocation(FrameworkModel frameworkModel, Channel channel, Request request, InputStream is, byte id) {
this.frameworkModel = frameworkModel;
@@ -85,7 +84,7 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec
this.request = request;
this.inputStream = is;
this.serializationType = id;
- this.callbackServiceCodecFactory = CacheableSupplier.newSupplier(()->
+ this.callbackServiceCodecFactory = CacheableSupplier.newSupplier(() ->
new CallbackServiceCodec(frameworkModel));
}
@@ -111,10 +110,6 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec
throw new UnsupportedOperationException();
}
- private void checkSerializationTypeFromRemote() {
-
- }
-
@Override
public Object decode(Channel channel, InputStream input) throws IOException {
ObjectInput in = CodecSupport.getSerialization(serializationType)
@@ -143,78 +138,14 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec
Object[] args = DubboCodec.EMPTY_OBJECT_ARRAY;
Class>[] pts = DubboCodec.EMPTY_CLASS_ARRAY;
if (desc.length() > 0) {
-// if (RpcUtils.isGenericCall(path, getMethodName()) || RpcUtils.isEcho(path, getMethodName())) {
-// pts = ReflectUtils.desc2classArray(desc);
-// } else {
- FrameworkServiceRepository repository = frameworkModel.getServiceRepository();
- List providerModels = repository.lookupExportedServicesWithoutGroup(keyWithoutGroup(path, version));
- ServiceDescriptor serviceDescriptor = null;
- if (CollectionUtils.isNotEmpty(providerModels)) {
- for (ProviderModel providerModel : providerModels) {
- serviceDescriptor = providerModel.getServiceModel();
- if (serviceDescriptor != null) {
- break;
- }
- }
- }
- if (serviceDescriptor == null) {
- // Unable to find ProviderModel from Exported Services
- for (ApplicationModel applicationModel : frameworkModel.getApplicationModels()) {
- for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
- serviceDescriptor = moduleModel.getServiceRepository().lookupService(path);
- if (serviceDescriptor != null) {
- break;
- }
- }
- }
- }
-
- if (serviceDescriptor != null) {
- MethodDescriptor methodDescriptor = serviceDescriptor.getMethod(getMethodName(), desc);
- if (methodDescriptor != null) {
- pts = methodDescriptor.getParameterClasses();
- this.setReturnTypes(methodDescriptor.getReturnTypes());
-
- // switch TCCL
- if (CollectionUtils.isNotEmpty(providerModels)) {
- if (providerModels.size() == 1) {
- Thread.currentThread().setContextClassLoader(providerModels.get(0).getClassLoader());
- } else {
- // try all providerModels' classLoader can load pts, use the first one
- for (ProviderModel providerModel : providerModels) {
- ClassLoader classLoader = providerModel.getClassLoader();
- boolean match = true;
- for (Class> pt : pts) {
- try {
- if (!pt.equals(classLoader.loadClass(pt.getName()))) {
- match = false;
- }
- } catch (ClassNotFoundException e) {
- match = false;
- }
- }
- if (match) {
- Thread.currentThread().setContextClassLoader(classLoader);
- break;
- }
- }
- }
- }
- }
- }
-
+ pts = drawPts(path, version, desc, pts);
if (pts == DubboCodec.EMPTY_CLASS_ARRAY) {
if (!RpcUtils.isGenericCall(desc, getMethodName()) && !RpcUtils.isEcho(desc, getMethodName())) {
throw new IllegalArgumentException("Service not found:" + path + ", " + getMethodName());
}
pts = ReflectUtils.desc2classArray(desc);
}
-// }
-
- args = new Object[pts.length];
- for (int i = 0; i < args.length; i++) {
- args[i] = in.readObject(pts[i]);
- }
+ args = drawArgs(in, pts);
}
setParameterTypes(pts);
@@ -223,17 +154,7 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec
addObjectAttachments(map);
}
- //decode argument ,may be callback
- CallbackServiceCodec callbackServiceCodec = callbackServiceCodecFactory.get();
- for (int i = 0; i < args.length; i++) {
- args[i] = callbackServiceCodec.decodeInvocationArgument(channel, this, pts, i, args[i]);
- }
-
- setArguments(args);
- String targetServiceName = buildKey(getAttachment(PATH_KEY),
- getAttachment(GROUP_KEY),
- getAttachment(VERSION_KEY));
- setTargetServiceUniqueName(targetServiceName);
+ decodeArgument(channel, pts, args);
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.toString("Read invocation data failed.", e));
} finally {
@@ -245,4 +166,86 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec
return this;
}
+
+ protected void decodeArgument(Channel channel, Class>[] pts, Object[] args) throws IOException {
+ CallbackServiceCodec callbackServiceCodec = callbackServiceCodecFactory.get();
+ for (int i = 0; i < args.length; i++) {
+ args[i] = callbackServiceCodec.decodeInvocationArgument(channel, this, pts, i, args[i]);
+ }
+
+ setArguments(args);
+ String targetServiceName = buildKey(getAttachment(PATH_KEY),
+ getAttachment(GROUP_KEY),
+ getAttachment(VERSION_KEY));
+ setTargetServiceUniqueName(targetServiceName);
+ }
+
+ protected Class>[] drawPts(String path, String version, String desc, Class>[] pts) {
+ FrameworkServiceRepository repository = frameworkModel.getServiceRepository();
+ List providerModels = repository.lookupExportedServicesWithoutGroup(keyWithoutGroup(path, version));
+ ServiceDescriptor serviceDescriptor = null;
+ if (CollectionUtils.isNotEmpty(providerModels)) {
+ for (ProviderModel providerModel : providerModels) {
+ serviceDescriptor = providerModel.getServiceModel();
+ if (serviceDescriptor != null) {
+ break;
+ }
+ }
+ }
+ if (serviceDescriptor == null) {
+ // Unable to find ProviderModel from Exported Services
+ for (ApplicationModel applicationModel : frameworkModel.getApplicationModels()) {
+ for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
+ serviceDescriptor = moduleModel.getServiceRepository().lookupService(path);
+ if (serviceDescriptor != null) {
+ break;
+ }
+ }
+ }
+ }
+
+ if (serviceDescriptor != null) {
+ MethodDescriptor methodDescriptor = serviceDescriptor.getMethod(getMethodName(), desc);
+ if (methodDescriptor != null) {
+ pts = methodDescriptor.getParameterClasses();
+ this.setReturnTypes(methodDescriptor.getReturnTypes());
+
+ // switch TCCL
+ if (CollectionUtils.isNotEmpty(providerModels)) {
+ if (providerModels.size() == 1) {
+ Thread.currentThread().setContextClassLoader(providerModels.get(0).getClassLoader());
+ } else {
+ // try all providerModels' classLoader can load pts, use the first one
+ for (ProviderModel providerModel : providerModels) {
+ ClassLoader classLoader = providerModel.getClassLoader();
+ boolean match = true;
+ for (Class> pt : pts) {
+ try {
+ if (!pt.equals(classLoader.loadClass(pt.getName()))) {
+ match = false;
+ }
+ } catch (ClassNotFoundException e) {
+ match = false;
+ }
+ }
+ if (match) {
+ Thread.currentThread().setContextClassLoader(classLoader);
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ return pts;
+ }
+
+ protected Object[] drawArgs(ObjectInput in, Class>[] pts) throws IOException, ClassNotFoundException {
+ Object[] args;
+ args = new Object[pts.length];
+ for (int i = 0; i < args.length; i++) {
+ args[i] = in.readObject(pts[i]);
+ }
+ return args;
+ }
}
diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java
index 88a0f5622d..0a7f96745c 100644
--- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java
+++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java
@@ -42,9 +42,11 @@ import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.BYTE_ACCESSOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
@@ -73,10 +75,15 @@ public class DubboCodec extends ExchangeCodec {
private static final AtomicBoolean decodeInUserThreadLogged = new AtomicBoolean(false);
private final CallbackServiceCodec callbackServiceCodec;
private final FrameworkModel frameworkModel;
+ private final ByteAccessor customByteAccessor;
public DubboCodec(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
callbackServiceCodec = new CallbackServiceCodec(frameworkModel);
+ customByteAccessor = Optional.ofNullable(System.getProperty(BYTE_ACCESSOR_KEY))
+ .filter(StringUtils::isNotBlank)
+ .map(key -> frameworkModel.getExtensionLoader(ByteAccessor.class).getExtension(key))
+ .orElse(null);
}
@Override
@@ -153,11 +160,20 @@ public class DubboCodec extends ExchangeCodec {
req = new HeartBeatRequest(id);
DecodeableRpcInvocation inv;
if (isDecodeDataInIoThread(channel)) {
- inv = new DecodeableRpcInvocation(frameworkModel, channel, req, is, proto);
+ if (customByteAccessor != null) {
+ inv = customByteAccessor.getRpcInvocation(channel, req, is, proto);
+ } else {
+ inv = new DecodeableRpcInvocation(frameworkModel, channel, req, is, proto);
+ }
inv.decode();
} else {
- inv = new DecodeableRpcInvocation(frameworkModel, channel, req,
- new UnsafeByteArrayInputStream(readMessageData(is)), proto);
+ if (customByteAccessor != null) {
+ inv = customByteAccessor.getRpcInvocation(channel, req,
+ new UnsafeByteArrayInputStream(readMessageData(is)), proto);
+ } else {
+ inv = new DecodeableRpcInvocation(frameworkModel, channel, req,
+ new UnsafeByteArrayInputStream(readMessageData(is)), proto);
+ }
}
data = inv;
}
From 8782df1ff7401eb45bcb6e0b14a5431a6ca63459 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Thu, 23 Mar 2023 20:09:26 +0800
Subject: [PATCH 007/122] Bump maven-release-plugin from 3.0.0-M7 to 3.0.0
(#11877)
Bumps [maven-release-plugin](https://github.com/apache/maven-release) from 3.0.0-M7 to 3.0.0.
- [Release notes](https://github.com/apache/maven-release/releases)
- [Commits](https://github.com/apache/maven-release/compare/maven-release-3.0.0-M7...maven-release-3.0.0)
---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-release-plugin
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pom.xml b/pom.xml
index 88c3e93d86..de2a872ac6 100644
--- a/pom.xml
+++ b/pom.xml
@@ -722,7 +722,7 @@
org.apache.maven.pluginsmaven-release-plugin
- 3.0.0-M7
+ 3.0.0truefalse
From a9362790a3cc643e58162723faec96d68c0bb370 Mon Sep 17 00:00:00 2001
From: wxbty <38374721+wxbty@users.noreply.github.com>
Date: Fri, 24 Mar 2023 10:47:09 +0800
Subject: [PATCH 008/122] Code opt (#11857)
* code opt
* code opt
* reuse rt stats
* bugfix
* bugfix
* fix comment
* reuse serviceKey
---------
Co-authored-by: x-shadow-man <1494445739@qq.com>
---
.../metrics/exception/MetricsException.java | 25 ++++++++
.../metrics/model/MetricsKeyWrapper.java | 22 +++++++
.../dubbo/metrics/model/MetricsSupport.java} | 56 ++++++-----------
.../metrics/model}/ServiceKeyMetric.java | 17 +++--
.../collector/stat/MetadataStatComposite.java | 1 +
.../collector/stat/RegistryStatComposite.java | 62 +++++++++----------
.../event/MetricsServiceRegisterListener.java | 2 +-
.../RegistryMetricsCollectorTest.java | 49 +++++++++++++++
.../collector/RegistryStatCompositeTest.java | 10 +--
9 files changed, 162 insertions(+), 82 deletions(-)
create mode 100644 dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/exception/MetricsException.java
rename dubbo-metrics/{dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/stat/ServiceKeyMetric.java => dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java} (55%)
rename dubbo-metrics/{dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/stat => dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model}/ServiceKeyMetric.java (89%)
diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/exception/MetricsException.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/exception/MetricsException.java
new file mode 100644
index 0000000000..20f238abde
--- /dev/null
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/exception/MetricsException.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.metrics.exception;
+
+public class MetricsException extends RuntimeException {
+
+ public MetricsException(String message) {
+ super(message);
+ }
+}
diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKeyWrapper.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKeyWrapper.java
index 54b791e5a8..b89a7e64fe 100644
--- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKeyWrapper.java
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKeyWrapper.java
@@ -17,17 +17,32 @@
package org.apache.dubbo.metrics.model;
+import java.util.Map;
+
/**
* Let {@link MetricsKey MetricsKey} output dynamic, custom string content
*/
public class MetricsKeyWrapper {
+ /**
+ * Register、subscribe、notify etc
+ */
private final String type;
+ /**
+ * Metrics key when exporting
+ */
private final MetricsKey metricsKey;
+ private final boolean serviceLevel;
+
public MetricsKeyWrapper(String type, MetricsKey metricsKey) {
+ this(type, metricsKey, false);
+ }
+
+ public MetricsKeyWrapper(String type, MetricsKey metricsKey, boolean serviceLevel) {
this.type = type;
this.metricsKey = metricsKey;
+ this.serviceLevel = serviceLevel;
}
public String getType() {
@@ -42,6 +57,10 @@ public class MetricsKeyWrapper {
return metricsKey == getMetricsKey() && registryOpType.equals(getType());
}
+ public boolean isServiceLevel() {
+ return serviceLevel;
+ }
+
public String targetKey() {
try {
return String.format(metricsKey.getName(), type);
@@ -58,4 +77,7 @@ public class MetricsKeyWrapper {
}
}
+ public Map tagName(String key) {
+ return isServiceLevel() ? MetricsSupport.serviceTags(key) : MetricsSupport.applicationTags(key);
+ }
}
diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/stat/ServiceKeyMetric.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java
similarity index 55%
rename from dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/stat/ServiceKeyMetric.java
rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java
index 7643d7368a..f6820a64b9 100644
--- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/stat/ServiceKeyMetric.java
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java
@@ -15,64 +15,44 @@
* limitations under the License.
*/
-package org.apache.dubbo.metrics.metadata.collector.stat;
+package org.apache.dubbo.metrics.model;
-import org.apache.dubbo.metrics.model.Metric;
+import org.apache.dubbo.common.Version;
+import org.apache.dubbo.metrics.exception.MetricsException;
import java.util.HashMap;
import java.util.Map;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_VERSION_KEY;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_INTERFACE_KEY;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP;
import static org.apache.dubbo.common.utils.NetUtils.getLocalHost;
import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName;
-/**
- * Metric class for interface.
- */
-public class ServiceKeyMetric implements Metric {
- private final String applicationName;
- private final String serviceKey;
+public class MetricsSupport {
- public ServiceKeyMetric(String applicationName, String serviceKey) {
- this.applicationName = applicationName;
- this.serviceKey = serviceKey;
- }
+ private static final String version = Version.getVersion();
+ private static final String commitId = Version.getLastCommitId();
- public Map getTags() {
+ public static Map applicationTags(String applicationName) {
Map tags = new HashMap<>();
tags.put(TAG_IP, getLocalHost());
tags.put(TAG_HOSTNAME, getLocalHostName());
tags.put(TAG_APPLICATION_NAME, applicationName);
- tags.put(TAG_INTERFACE_KEY, serviceKey);
+ tags.put(TAG_APPLICATION_VERSION_KEY, version);
+ tags.put(MetricsKey.METADATA_GIT_COMMITID_METRIC.getName(), commitId);
return tags;
}
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- ServiceKeyMetric that = (ServiceKeyMetric) o;
-
- if (!applicationName.equals(that.applicationName)) return false;
- return serviceKey.equals(that.serviceKey);
- }
-
- @Override
- public int hashCode() {
- int result = applicationName.hashCode();
- result = 31 * result + serviceKey.hashCode();
- return result;
- }
-
- @Override
- public String toString() {
- return "ServiceKeyMetric{" +
- "applicationName='" + applicationName + '\'' +
- ", serviceKey='" + serviceKey + '\'' +
- '}';
+ public static Map serviceTags(String appAndServiceName) {
+ String[] keys = appAndServiceName.split("_");
+ if (keys.length != 2) {
+ throw new MetricsException("Error service name: " + appAndServiceName);
+ }
+ Map tags = applicationTags(keys[0]);
+ tags.put(TAG_INTERFACE_KEY, keys[1]);
+ return tags;
}
}
diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/stat/ServiceKeyMetric.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ServiceKeyMetric.java
similarity index 89%
rename from dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/stat/ServiceKeyMetric.java
rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ServiceKeyMetric.java
index 9fa387418e..94eaa30edb 100644
--- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/stat/ServiceKeyMetric.java
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ServiceKeyMetric.java
@@ -15,9 +15,7 @@
* limitations under the License.
*/
-package org.apache.dubbo.metrics.registry.collector.stat;
-
-import org.apache.dubbo.metrics.model.Metric;
+package org.apache.dubbo.metrics.model;
import java.util.HashMap;
import java.util.Map;
@@ -41,6 +39,7 @@ public class ServiceKeyMetric implements Metric {
this.serviceKey = serviceKey;
}
+ @Override
public Map getTags() {
Map tags = new HashMap<>();
tags.put(TAG_IP, getLocalHost());
@@ -52,12 +51,18 @@ public class ServiceKeyMetric implements Metric {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
ServiceKeyMetric that = (ServiceKeyMetric) o;
- if (!applicationName.equals(that.applicationName)) return false;
+ if (!applicationName.equals(that.applicationName)) {
+ return false;
+ }
return serviceKey.equals(that.serviceKey);
}
diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/stat/MetadataStatComposite.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/stat/MetadataStatComposite.java
index 631176ee53..c58baab23a 100644
--- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/stat/MetadataStatComposite.java
+++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/stat/MetadataStatComposite.java
@@ -24,6 +24,7 @@ import org.apache.dubbo.metrics.model.ApplicationMetric;
import org.apache.dubbo.metrics.model.MetricsCategory;
import org.apache.dubbo.metrics.model.MetricsKey;
import org.apache.dubbo.metrics.model.MetricsKeyWrapper;
+import org.apache.dubbo.metrics.model.ServiceKeyMetric;
import org.apache.dubbo.metrics.model.container.AtomicLongContainer;
import org.apache.dubbo.metrics.model.container.LongAccumulatorContainer;
import org.apache.dubbo.metrics.model.container.LongContainer;
diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/stat/RegistryStatComposite.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/stat/RegistryStatComposite.java
index 864499bbc3..2c78106b66 100644
--- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/stat/RegistryStatComposite.java
+++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/stat/RegistryStatComposite.java
@@ -19,10 +19,11 @@ package org.apache.dubbo.metrics.registry.collector.stat;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.metrics.collector.MetricsCollector;
-import org.apache.dubbo.metrics.model.ApplicationMetric;
import org.apache.dubbo.metrics.model.MetricsCategory;
import org.apache.dubbo.metrics.model.MetricsKey;
import org.apache.dubbo.metrics.model.MetricsKeyWrapper;
+import org.apache.dubbo.metrics.model.MetricsSupport;
+import org.apache.dubbo.metrics.model.ServiceKeyMetric;
import org.apache.dubbo.metrics.model.container.AtomicLongContainer;
import org.apache.dubbo.metrics.model.container.LongAccumulatorContainer;
import org.apache.dubbo.metrics.model.container.LongContainer;
@@ -36,7 +37,6 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAccumulator;
-import java.util.function.Function;
import java.util.stream.Collectors;
/**
@@ -49,9 +49,7 @@ public class RegistryStatComposite implements MetricsExport {
public Map> applicationNumStats = new ConcurrentHashMap<>();
public Map> serviceNumStats = new ConcurrentHashMap<>();
- public Map> skStats = new ConcurrentHashMap<>();
- public List> appRtStats = new ArrayList<>();
- public List> serviceRtStats = new ArrayList<>();
+ public List> rtStats = new ArrayList<>();
public static String OP_TYPE_REGISTER = "register";
public static String OP_TYPE_SUBSCRIBE = "subscribe";
public static String OP_TYPE_NOTIFY = "notify";
@@ -66,28 +64,29 @@ public class RegistryStatComposite implements MetricsExport {
for (RegistryEvent.ServiceType type : RegistryEvent.ServiceType.values()) {
// Service key
- skStats.put(type, new ConcurrentHashMap<>());
+ serviceNumStats.put(type, new ConcurrentHashMap<>());
}
+ // App-level
+ rtStats.addAll(initStats(OP_TYPE_REGISTER, false));
+ rtStats.addAll(initStats(OP_TYPE_SUBSCRIBE, false));
+ rtStats.addAll(initStats(OP_TYPE_NOTIFY, false));
- appRtStats.addAll(initStats(OP_TYPE_REGISTER));
- appRtStats.addAll(initStats(OP_TYPE_SUBSCRIBE));
- appRtStats.addAll(initStats(OP_TYPE_NOTIFY));
-
- serviceRtStats.addAll(initStats(OP_TYPE_REGISTER_SERVICE));
- serviceRtStats.addAll(initStats(OP_TYPE_SUBSCRIBE_SERVICE));
+ // Service-level
+ rtStats.addAll(initStats(OP_TYPE_REGISTER_SERVICE, true));
+ rtStats.addAll(initStats(OP_TYPE_SUBSCRIBE_SERVICE, true));
}
- private List> initStats(String registryOpType) {
+ private List> initStats(String registryOpType, boolean isServiceLevel) {
List> singleRtStats = new ArrayList<>();
- singleRtStats.add(new AtomicLongContainer(new MetricsKeyWrapper(registryOpType, MetricsKey.METRIC_RT_LAST)));
- singleRtStats.add(new LongAccumulatorContainer(new MetricsKeyWrapper(registryOpType, MetricsKey.METRIC_RT_MIN), new LongAccumulator(Long::min, Long.MAX_VALUE)));
- singleRtStats.add(new LongAccumulatorContainer(new MetricsKeyWrapper(registryOpType, MetricsKey.METRIC_RT_MAX), new LongAccumulator(Long::max, Long.MIN_VALUE)));
- singleRtStats.add(new AtomicLongContainer(new MetricsKeyWrapper(registryOpType, MetricsKey.METRIC_RT_SUM), (responseTime, longAccumulator) -> longAccumulator.addAndGet(responseTime)));
+ singleRtStats.add(new AtomicLongContainer(new MetricsKeyWrapper(registryOpType, MetricsKey.METRIC_RT_LAST, isServiceLevel)));
+ singleRtStats.add(new LongAccumulatorContainer(new MetricsKeyWrapper(registryOpType, MetricsKey.METRIC_RT_MIN, isServiceLevel), new LongAccumulator(Long::min, Long.MAX_VALUE)));
+ singleRtStats.add(new LongAccumulatorContainer(new MetricsKeyWrapper(registryOpType, MetricsKey.METRIC_RT_MAX, isServiceLevel), new LongAccumulator(Long::max, Long.MIN_VALUE)));
+ singleRtStats.add(new AtomicLongContainer(new MetricsKeyWrapper(registryOpType, MetricsKey.METRIC_RT_SUM, isServiceLevel), (responseTime, longAccumulator) -> longAccumulator.addAndGet(responseTime)));
// AvgContainer is a special counter that stores the number of times but outputs function of sum/times
- AtomicLongContainer avgContainer = new AtomicLongContainer(new MetricsKeyWrapper(registryOpType, MetricsKey.METRIC_RT_AVG), (k, v) -> v.incrementAndGet());
+ AtomicLongContainer avgContainer = new AtomicLongContainer(new MetricsKeyWrapper(registryOpType, MetricsKey.METRIC_RT_AVG, isServiceLevel), (k, v) -> v.incrementAndGet());
avgContainer.setValueSupplier(applicationName -> {
- LongContainer extends Number> totalContainer = appRtStats.stream().filter(longContainer -> longContainer.isKeyWrapper(MetricsKey.METRIC_RT_SUM, registryOpType)).findFirst().get();
+ LongContainer extends Number> totalContainer = rtStats.stream().filter(longContainer -> longContainer.isKeyWrapper(MetricsKey.METRIC_RT_SUM, registryOpType)).findFirst().get();
AtomicLong totalRtTimes = avgContainer.get(applicationName);
AtomicLong totalRtSum = (AtomicLong) totalContainer.get(applicationName);
return totalRtSum.get() / totalRtTimes.get();
@@ -104,10 +103,10 @@ public class RegistryStatComposite implements MetricsExport {
}
public void setServiceKey(RegistryEvent.ServiceType type, String applicationName, String serviceKey, int num) {
- if (!skStats.containsKey(type)) {
+ if (!serviceNumStats.containsKey(type)) {
return;
}
- skStats.get(type).computeIfAbsent(new ServiceKeyMetric(applicationName, serviceKey), k -> new AtomicLong(0L)).set(num);
+ serviceNumStats.get(type).computeIfAbsent(new ServiceKeyMetric(applicationName, serviceKey), k -> new AtomicLong(0L)).set(num);
}
public void increment(RegistryEvent.ApplicationType type, String applicationName) {
@@ -115,10 +114,10 @@ public class RegistryStatComposite implements MetricsExport {
}
public void incrementServiceKey(RegistryEvent.ServiceType type, String applicationName, String serviceKey, int size) {
- if (!skStats.containsKey(type)) {
+ if (!serviceNumStats.containsKey(type)) {
return;
}
- skStats.get(type).computeIfAbsent(new ServiceKeyMetric(applicationName, serviceKey), k -> new AtomicLong(0L)).getAndAdd(size);
+ serviceNumStats.get(type).computeIfAbsent(new ServiceKeyMetric(applicationName, serviceKey), k -> new AtomicLong(0L)).getAndAdd(size);
}
public void incrementSize(RegistryEvent.ApplicationType type, String applicationName, int size) {
@@ -130,7 +129,7 @@ public class RegistryStatComposite implements MetricsExport {
@SuppressWarnings({"rawtypes", "unchecked"})
public void calcApplicationRt(String applicationName, String registryOpType, Long responseTime) {
- for (LongContainer container : appRtStats.stream().filter(longContainer -> longContainer.specifyType(registryOpType)).collect(Collectors.toList())) {
+ for (LongContainer container : rtStats.stream().filter(longContainer -> longContainer.specifyType(registryOpType)).collect(Collectors.toList())) {
Number current = (Number) ConcurrentHashMapUtils.computeIfAbsent(container, applicationName, container.getInitFunc());
container.getConsumerFunc().accept(responseTime, current);
}
@@ -138,7 +137,7 @@ public class RegistryStatComposite implements MetricsExport {
@SuppressWarnings({"rawtypes", "unchecked"})
public void calcServiceKeyRt(String applicationName, String serviceKey, String registryOpType, Long responseTime) {
- for (LongContainer container : serviceRtStats.stream().filter(longContainer -> longContainer.specifyType(registryOpType)).collect(Collectors.toList())) {
+ for (LongContainer container : rtStats.stream().filter(longContainer -> longContainer.specifyType(registryOpType)).collect(Collectors.toList())) {
Number current = (Number) ConcurrentHashMapUtils.computeIfAbsent(container, applicationName + "_" + serviceKey, container.getInitFunc());
container.getConsumerFunc().accept(responseTime, current);
}
@@ -161,17 +160,16 @@ public class RegistryStatComposite implements MetricsExport {
@SuppressWarnings({"rawtypes"})
public List exportRtMetrics() {
List result = new ArrayList<>();
- doExportRt(result, appRtStats, ApplicationMetric::getTagsByName);
- doExportRt(result, serviceRtStats, ApplicationMetric::getServiceTags);
+ doExportRt(result, rtStats);
return result;
}
@SuppressWarnings({"rawtypes"})
- private void doExportRt(List list, List> rtStats, Function> tagNameFunc) {
+ private void doExportRt(List list, List> rtStats) {
for (LongContainer extends Number> rtContainer : rtStats) {
MetricsKeyWrapper metricsKeyWrapper = rtContainer.getMetricsKeyWrapper();
for (Map.Entry entry : rtContainer.entrySet()) {
- list.add(new GaugeMetricSample<>(metricsKeyWrapper.targetKey(), metricsKeyWrapper.targetDesc(), tagNameFunc.apply(entry.getKey()), MetricsCategory.RT, entry.getKey().intern(), value -> rtContainer.getValueSupplier().apply(value.intern())));
+ list.add(new GaugeMetricSample<>(metricsKeyWrapper.targetKey(), metricsKeyWrapper.targetDesc(), metricsKeyWrapper.tagName(entry.getKey()), MetricsCategory.RT, entry.getKey().intern(), value -> rtContainer.getValueSupplier().apply(value.intern())));
}
}
}
@@ -179,8 +177,8 @@ public class RegistryStatComposite implements MetricsExport {
@SuppressWarnings({"rawtypes"})
public List exportSkMetrics() {
List list = new ArrayList<>();
- for (RegistryEvent.ServiceType type : skStats.keySet()) {
- Map stringAtomicLongMap = skStats.get(type);
+ for (RegistryEvent.ServiceType type : serviceNumStats.keySet()) {
+ Map stringAtomicLongMap = serviceNumStats.get(type);
for (ServiceKeyMetric serviceKeyMetric : stringAtomicLongMap.keySet()) {
list.add(new GaugeMetricSample<>(type.getMetricsKey(), serviceKeyMetric.getTags(), MetricsCategory.REGISTRY, stringAtomicLongMap, value -> value.get(serviceKeyMetric).get()));
}
@@ -190,6 +188,6 @@ public class RegistryStatComposite implements MetricsExport {
@SuppressWarnings({"rawtypes"})
public GaugeMetricSample convertToSample(String applicationName, RegistryEvent.ApplicationType type, MetricsCategory category, AtomicLong targetNumber) {
- return new GaugeMetricSample<>(type.getMetricsKey(), ApplicationMetric.getTagsByName(applicationName), category, targetNumber, AtomicLong::get);
+ return new GaugeMetricSample<>(type.getMetricsKey(), MetricsSupport.applicationTags(applicationName), category, targetNumber, AtomicLong::get);
}
}
diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/MetricsServiceRegisterListener.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/MetricsServiceRegisterListener.java
index e99ce7a75d..45aba8c226 100644
--- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/MetricsServiceRegisterListener.java
+++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/MetricsServiceRegisterListener.java
@@ -46,6 +46,6 @@ public class MetricsServiceRegisterListener implements MetricsLifeListener metricSamples = collector.collect();
+
+ // push success +1
+ Assertions.assertEquals(1, metricSamples.size());
+ Assertions.assertTrue(metricSamples.get(0) instanceof GaugeMetricSample);
+
+ eventMulticaster.publishFinishEvent(new RegistryEvent.MetricsServiceRegisterEvent(applicationModel, timePair,serviceName,2));
+ // push finish rt +1
+ metricSamples = collector.collect();
+ //num(total+success) + rt(5) = 7
+ Assertions.assertEquals(7, metricSamples.size());
+ long c1 = timePair.calc();
+ TimePair lastTimePair = TimePair.start();
+ eventMulticaster.publishEvent(new RegistryEvent.MetricsServiceRegisterEvent(applicationModel, lastTimePair,serviceName,2));
+ Thread.sleep(50);
+ // push error rt +1
+ eventMulticaster.publishErrorEvent(new RegistryEvent.MetricsServiceRegisterEvent(applicationModel, lastTimePair,serviceName,2));
+ long c2 = lastTimePair.calc();
+ metricSamples = collector.collect();
+
+ // num(total+success+error) + rt(5)
+ Assertions.assertEquals(8, metricSamples.size());
+
+ // calc rt
+ for (MetricSample sample : metricSamples) {
+ Map tags = sample.getTags();
+ Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName());
+ }
+
+ @SuppressWarnings("rawtypes")
+ Map sampleMap = metricSamples.stream().collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong()));
+
+ Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(OP_TYPE_REGISTER_SERVICE, MetricsKey.METRIC_RT_LAST).targetKey()), lastTimePair.calc());
+ Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(OP_TYPE_REGISTER_SERVICE, MetricsKey.METRIC_RT_MIN).targetKey()), Math.min(c1, c2));
+ Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(OP_TYPE_REGISTER_SERVICE, MetricsKey.METRIC_RT_MAX).targetKey()), Math.max(c1, c2));
+ Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(OP_TYPE_REGISTER_SERVICE, MetricsKey.METRIC_RT_AVG).targetKey()), (c1 + c2) / 2);
+ Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(OP_TYPE_REGISTER_SERVICE, MetricsKey.METRIC_RT_SUM).targetKey()), c1 + c2);
+ }
}
diff --git a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryStatCompositeTest.java b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryStatCompositeTest.java
index 7d4753aa1b..036f8ae4e5 100644
--- a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryStatCompositeTest.java
+++ b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryStatCompositeTest.java
@@ -37,11 +37,11 @@ public class RegistryStatCompositeTest {
void testInit() {
RegistryStatComposite statComposite = new RegistryStatComposite();
Assertions.assertEquals(statComposite.applicationNumStats.size(), RegistryEvent.ApplicationType.values().length);
- //(rt)5 * (register,subscribe,notify)3
- Assertions.assertEquals(5 * 3, statComposite.appRtStats.size());
+ //(rt)5 * (register,subscribe,notify,register.service,subscribe.service)5
+ Assertions.assertEquals(5 * 5, statComposite.rtStats.size());
statComposite.applicationNumStats.values().forEach((v ->
Assertions.assertEquals(v, new ConcurrentHashMap<>())));
- statComposite.appRtStats.forEach(rtContainer ->
+ statComposite.rtStats.forEach(rtContainer ->
{
for (Map.Entry entry : rtContainer.entrySet()) {
Assertions.assertEquals(0L, rtContainer.getValueSupplier().apply(entry.getKey()));
@@ -60,8 +60,8 @@ public class RegistryStatCompositeTest {
void testCalcRt() {
RegistryStatComposite statComposite = new RegistryStatComposite();
statComposite.calcApplicationRt(applicationName, OP_TYPE_NOTIFY, 10L);
- Assertions.assertTrue(statComposite.appRtStats.stream().anyMatch(longContainer -> longContainer.specifyType(OP_TYPE_NOTIFY)));
- Optional> subContainer = statComposite.appRtStats.stream().filter(longContainer -> longContainer.specifyType(OP_TYPE_NOTIFY)).findFirst();
+ Assertions.assertTrue(statComposite.rtStats.stream().anyMatch(longContainer -> longContainer.specifyType(OP_TYPE_NOTIFY)));
+ Optional> subContainer = statComposite.rtStats.stream().filter(longContainer -> longContainer.specifyType(OP_TYPE_NOTIFY)).findFirst();
subContainer.ifPresent(v -> Assertions.assertEquals(10L, v.get(applicationName).longValue()));
}
}
From 95865b04616c7d8b4d6b20ac4232b9499006d7eb Mon Sep 17 00:00:00 2001
From: icodening
Date: Fri, 24 Mar 2023 11:15:25 +0800
Subject: [PATCH 009/122] optimize performance. decode in user thread (#11879)
* optimize performance: decode in user thread
* optimize performance: decode in user thread
* optimize performance: decode in user thread
---
.../common/function/ThrowableSupplier.java | 27 +++++++++++++
.../dubbo/common/utils/ExecutorUtil.java | 6 +++
.../rpc/protocol/tri/DeadlineFuture.java | 11 ++++--
.../dubbo/rpc/protocol/tri/TripleInvoker.java | 3 ++
.../rpc/protocol/tri/call/ClientCall.java | 10 ++++-
.../ObserverToClientCallListenerAdapter.java | 12 ++++--
.../protocol/tri/call/TripleClientCall.java | 21 ++++++----
.../tri/call/TripleMessageProducer.java | 39 +++++++++++++++++++
.../tri/call/UnaryClientCallListener.java | 33 +++++++++-------
.../rpc/protocol/tri/DeadlineFutureTest.java | 2 +-
10 files changed, 132 insertions(+), 32 deletions(-)
create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableSupplier.java
create mode 100644 dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleMessageProducer.java
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableSupplier.java b/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableSupplier.java
new file mode 100644
index 0000000000..84befaf9f7
--- /dev/null
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableSupplier.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.common.function;
+
+public interface ThrowableSupplier {
+
+ /**
+ * Gets a result.
+ *
+ * @return a result
+ */
+ T get() throws Throwable;
+}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java
index 6c0bc148a1..714c8ae4fa 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java
@@ -37,6 +37,8 @@ public class ExecutorUtil {
new LinkedBlockingQueue(100),
new NamedThreadFactory("Close-ExecutorService-Timer", true));
+ private static final Executor DIRECT_EXECUTOR = Runnable::run;
+
public static boolean isTerminated(Executor executor) {
if (executor instanceof ExecutorService) {
if (((ExecutorService) executor).isTerminated()) {
@@ -135,4 +137,8 @@ public class ExecutorUtil {
future.cancel(true);
}
}
+
+ public static Executor directExecutor() {
+ return DIRECT_EXECUTOR;
+ }
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFuture.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFuture.java
index f2985759fd..34097752a8 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFuture.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFuture.java
@@ -36,6 +36,7 @@ import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
public class DeadlineFuture extends CompletableFuture {
@@ -80,7 +81,7 @@ public class DeadlineFuture extends CompletableFuture {
return future;
}
- public void received(TriRpcStatus status, AppResponse appResponse) {
+ public void received(TriRpcStatus status, Supplier appResponse) {
if (status.code != TriRpcStatus.Code.DEADLINE_EXCEEDED) {
// decrease Time
if (!timeoutTask.isCancelled()) {
@@ -88,11 +89,13 @@ public class DeadlineFuture extends CompletableFuture {
}
}
if (getExecutor() != null) {
- getExecutor().execute(() -> doReceived(status, appResponse));
+ getExecutor().execute(() -> doReceived(status, appResponse.get()));
} else {
- doReceived(status, appResponse);
+ doReceived(status, appResponse.get());
}
- } private static final GlobalResourceInitializer TIME_OUT_TIMER = new GlobalResourceInitializer<>(
+ }
+
+ private static final GlobalResourceInitializer TIME_OUT_TIMER = new GlobalResourceInitializer<>(
() -> new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 30,
TimeUnit.MILLISECONDS), DeadlineFuture::destroy);
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java
index 6c11a1061a..d3e7ec4f48 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java
@@ -24,6 +24,7 @@ import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.stream.StreamObserver;
+import org.apache.dubbo.common.utils.ExecutorUtil;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
@@ -132,6 +133,8 @@ public class TripleInvoker extends AbstractInvoker {
try {
switch (methodDescriptor.getRpcType()) {
case UNARY:
+ call = new TripleClientCall(connectionClient, ExecutorUtil.directExecutor(),
+ getUrl().getOrDefaultFrameworkModel(), writeQueue);
result = invokeUnary(methodDescriptor, invocation, call);
break;
case SERVER_STREAM:
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java
index 4936f54409..a54e7b8df1 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java
@@ -43,9 +43,9 @@ public interface ClientCall {
/**
* Callback when message received.
*
- * @param message message received
+ * @param messageProducer message producer
*/
- void onMessage(Object message);
+ void onMessage(MessageProducer messageProducer);
/**
* Callback when call is finished.
@@ -110,4 +110,10 @@ public interface ClientCall {
*/
void setCompression(String compression);
+ interface MessageProducer {
+
+ Object getMessage() throws Throwable;
+
+ }
+
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java
index 1c934ce970..40125cdb8d 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java
@@ -38,10 +38,14 @@ public class ObserverToClientCallListenerAdapter implements ClientCall.Listener
}
@Override
- public void onMessage(Object message) {
- delegate.onNext(message);
- if (call.isAutoRequest()) {
- call.request(1);
+ public void onMessage(ClientCall.MessageProducer messageProducer) {
+ try {
+ delegate.onNext(messageProducer.getMessage());
+ if (call.isAutoRequest()) {
+ call.request(1);
+ }
+ } catch (Throwable e) {
+ delegate.onError(e);
}
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java
index f1d0a60f6a..f54cd4844a 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java
@@ -77,18 +77,23 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener {
return;
}
try {
- final Object unpacked = requestMetadata.packableMethod.parseResponse(message);
- listener.onMessage(unpacked);
+ TripleMessageProducer messageProducer = TripleMessageProducer.withSupplier(() ->
+ requestMetadata.packableMethod.parseResponse(message));
+ listener.onMessage(messageProducer);
} catch (Throwable t) {
- TriRpcStatus status = TriRpcStatus.INTERNAL.withDescription("Deserialize response failed")
- .withCause(t);
- cancelByLocal(status.asException());
- listener.onClose(status,null);
- LOGGER.error(PROTOCOL_FAILED_RESPONSE, "", "", String.format("Failed to deserialize triple response, service=%s, method=%s,connection=%s",
- connectionClient, requestMetadata.service, requestMetadata.method.getMethodName()), t);
+ onDeserializeError(t);
}
}
+ private void onDeserializeError(Throwable t){
+ TriRpcStatus status = TriRpcStatus.INTERNAL.withDescription("Deserialize response failed")
+ .withCause(t);
+ cancelByLocal(status.asException());
+ listener.onClose(status,null);
+ LOGGER.error(PROTOCOL_FAILED_RESPONSE, "", "", String.format("Failed to deserialize triple response, service=%s, method=%s,connection=%s",
+ connectionClient, requestMetadata.service, requestMetadata.method.getMethodName()), t);
+ }
+
@Override
public void onCancelByRemote(TriRpcStatus status) {
if (canceled) {
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleMessageProducer.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleMessageProducer.java
new file mode 100644
index 0000000000..e40f03cce9
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleMessageProducer.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.call;
+
+import org.apache.dubbo.common.function.ThrowableSupplier;
+
+
+class TripleMessageProducer implements ClientCall.MessageProducer {
+
+ private final ThrowableSupplier
+
+ org.apache.dubbo
+ dubbo-metrics-default
+ ${project.parent.version}
+ true
+
+
+ io.micrometer
+ micrometer-tracing-integration-test
+ test
+
diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsClusterFilter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java
similarity index 95%
rename from dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsClusterFilter.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java
index 4fa30ee0b2..2a4d36dcfc 100644
--- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsClusterFilter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java
@@ -15,7 +15,8 @@
* limitations under the License.
*/
-package org.apache.dubbo.metrics.filter;
+package org.apache.dubbo.rpc.cluster.filter.support;
+
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metrics.collector.DefaultMetricsCollector;
@@ -29,12 +30,13 @@ import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
+
import java.util.Optional;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
-@Activate(group = CONSUMER)
+@Activate(group = CONSUMER,onClass = "org.apache.dubbo.metrics.collector.DefaultMetricsCollector")
public class MetricsClusterFilter implements ClusterFilter, BaseFilter.Listener, ScopeModelAware {
private DefaultMetricsCollector collector;
diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/observation/ObservationSenderFilter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ObservationSenderFilter.java
similarity index 90%
rename from dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/observation/ObservationSenderFilter.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ObservationSenderFilter.java
index 6e0e099e48..fcd8b124a0 100644
--- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/observation/ObservationSenderFilter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ObservationSenderFilter.java
@@ -14,12 +14,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.metrics.observation;
+package org.apache.dubbo.rpc.cluster.filter.support;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
-
import org.apache.dubbo.common.extension.Activate;
+import org.apache.dubbo.metrics.observation.DefaultDubboClientObservationConvention;
+import org.apache.dubbo.metrics.observation.DubboClientContext;
+import org.apache.dubbo.metrics.observation.DubboClientObservationConvention;
+import org.apache.dubbo.metrics.observation.DubboObservation;
import org.apache.dubbo.rpc.BaseFilter;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
diff --git a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.Cluster b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.Cluster
index 5ff23dc553..f7f5debebf 100644
--- a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.Cluster
+++ b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.Cluster
@@ -9,3 +9,6 @@ available=org.apache.dubbo.rpc.cluster.support.AvailableCluster
mergeable=org.apache.dubbo.rpc.cluster.support.MergeableCluster
broadcast=org.apache.dubbo.rpc.cluster.support.BroadcastCluster
zone-aware=org.apache.dubbo.rpc.cluster.support.registry.ZoneAwareCluster
+observationsender=org.apache.dubbo.metrics.observation.ObservationSenderFilter
+metricsClusterFilter=org.apache.dubbo.metrics.filter.MetricsClusterFilter
+
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/AbstractObservationFilterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/AbstractObservationFilterTest.java
new file mode 100644
index 0000000000..131225f44f
--- /dev/null
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/AbstractObservationFilterTest.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter;
+
+import io.micrometer.tracing.test.SampleTestRunner;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.rpc.AppResponse;
+import org.apache.dubbo.rpc.BaseFilter;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.RpcInvocation;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+import org.junit.jupiter.api.AfterEach;
+
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Mockito.mock;
+
+abstract class AbstractObservationFilterTest extends SampleTestRunner {
+
+ ApplicationModel applicationModel;
+ RpcInvocation invocation;
+
+ BaseFilter filter;
+
+ Invoker> invoker = mock(Invoker.class);
+
+ static final String INTERFACE_NAME = "org.apache.dubbo.MockInterface";
+ static final String METHOD_NAME = "mockMethod";
+ static final String GROUP = "mockGroup";
+ static final String VERSION = "1.0.0";
+
+ @AfterEach
+ public void teardown() {
+ if (applicationModel != null) {
+ applicationModel.destroy();
+ }
+ }
+
+ abstract BaseFilter createFilter(ApplicationModel applicationModel);
+
+ void setupConfig() {
+ ApplicationConfig config = new ApplicationConfig();
+ config.setName("MockObservations");
+
+ applicationModel = ApplicationModel.defaultModel();
+ applicationModel.getApplicationConfigManager().setApplication(config);
+
+ invocation = new RpcInvocation(new MockInvocation());
+ invocation.addInvokedInvoker(invoker);
+
+ applicationModel.getBeanFactory().registerBean(getObservationRegistry());
+
+ filter = createFilter(applicationModel);
+
+ given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
+
+ initParam();
+ }
+
+ private void initParam() {
+ invocation.setTargetServiceUniqueName(GROUP + "/" + INTERFACE_NAME + ":" + VERSION);
+ invocation.setMethodName(METHOD_NAME);
+ invocation.setParameterTypes(new Class[] {String.class});
+ }
+
+}
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilderTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilderTest.java
index 7f0bb6ff07..3a173c2ceb 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilderTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilderTest.java
@@ -49,7 +49,6 @@ class DefaultFilterChainBuilderTest {
};
Invoker> invokerAfterBuild = defaultFilterChainBuilder.buildInvokerChain(invokerWithoutFilter, REFERENCE_FILTER_KEY, CONSUMER);
- Assertions.assertTrue(invokerAfterBuild instanceof AbstractInvoker);
// verify that if LogFilter is configured, LogFilter should exist in the filter chain
URL urlWithFilter = URL.valueOf("injvm://127.0.0.1/DemoService")
@@ -64,8 +63,6 @@ class DefaultFilterChainBuilderTest {
};
invokerAfterBuild = defaultFilterChainBuilder.buildInvokerChain(invokerWithFilter, REFERENCE_FILTER_KEY, CONSUMER);
Assertions.assertTrue(invokerAfterBuild instanceof FilterChainBuilder.CallbackRegistrationInvoker);
- Assertions.assertEquals(1, ((FilterChainBuilder.CallbackRegistrationInvoker, ?>) invokerAfterBuild).filters.size());
-
}
@Test
@@ -84,7 +81,7 @@ class DefaultFilterChainBuilderTest {
};
Invoker> invokerAfterBuild = defaultFilterChainBuilder.buildInvokerChain(invokerWithoutFilter, REFERENCE_FILTER_KEY, CONSUMER);
- Assertions.assertTrue(invokerAfterBuild instanceof AbstractInvoker);
+// Assertions.assertTrue(invokerAfterBuild instanceof AbstractInvoker);
// verify that if LogFilter is configured, LogFilter should exist in the filter chain
URL urlWithFilter = URL.valueOf("dubbo://127.0.0.1:20880/DemoService")
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MetricsClusterFilterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MetricsClusterFilterTest.java
new file mode 100644
index 0000000000..fb8e46ed06
--- /dev/null
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MetricsClusterFilterTest.java
@@ -0,0 +1,183 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.constants.CommonConstants;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.metrics.collector.DefaultMetricsCollector;
+import org.apache.dubbo.metrics.filter.MetricsFilter;
+import org.apache.dubbo.metrics.model.MetricsKey;
+import org.apache.dubbo.metrics.model.sample.GaugeMetricSample;
+import org.apache.dubbo.metrics.model.sample.MetricSample;
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.Result;
+import org.apache.dubbo.rpc.RpcContext;
+import org.apache.dubbo.rpc.RpcException;
+import org.apache.dubbo.rpc.RpcInvocation;
+import org.apache.dubbo.rpc.cluster.filter.support.MetricsClusterFilter;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Mockito.mock;
+
+class MetricsClusterFilterTest {
+
+ private ApplicationModel applicationModel;
+ private MetricsFilter filter;
+ private MetricsClusterFilter metricsClusterFilter;
+ private DefaultMetricsCollector collector;
+ private RpcInvocation invocation;
+ private final Invoker> invoker = mock(Invoker.class);
+
+ private static final String INTERFACE_NAME = "org.apache.dubbo.MockInterface";
+ private static final String METHOD_NAME = "mockMethod";
+ private static final String GROUP = "mockGroup";
+ private static final String VERSION = "1.0.0";
+ private String side;
+
+ private AtomicBoolean initApplication = new AtomicBoolean(false);
+
+
+ @BeforeEach
+ public void setup() {
+ ApplicationConfig config = new ApplicationConfig();
+ config.setName("MockMetrics");
+ //RpcContext.getContext().setAttachment("MockMetrics","MockMetrics");
+
+ applicationModel = ApplicationModel.defaultModel();
+ applicationModel.getApplicationConfigManager().setApplication(config);
+
+ invocation = new RpcInvocation();
+ filter = new MetricsFilter();
+
+ collector = applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class);
+ if(!initApplication.get()) {
+ collector.collectApplication(applicationModel);
+ initApplication.set(true);
+ }
+ filter.setApplicationModel(applicationModel);
+ side = CommonConstants.CONSUMER;
+ invocation.setInvoker(new TestMetricsInvoker(side));
+ RpcContext.getServiceContext().setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side));
+
+ metricsClusterFilter = new MetricsClusterFilter();
+ metricsClusterFilter.setApplicationModel(applicationModel);
+ }
+
+ @AfterEach
+ public void teardown() {
+ applicationModel.destroy();
+ }
+
+ @Test
+ public void testNoProvider(){
+ testClusterFilterError(RpcException.FORBIDDEN_EXCEPTION,
+ MetricsKey.METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED.getNameByType(CommonConstants.CONSUMER));
+ }
+
+ private void testClusterFilterError(int errorCode,String name){
+ collector.setCollectEnabled(true);
+ given(invoker.invoke(invocation)).willThrow(new RpcException(errorCode));
+ initParam();
+
+ Long count = 1L;
+
+ for (int i = 0; i < count; i++) {
+ try {
+ metricsClusterFilter.invoke(invoker, invocation);
+ } catch (Exception e) {
+ Assertions.assertTrue(e instanceof RpcException);
+ metricsClusterFilter.onError(e, invoker, invocation);
+ }
+ }
+ Map metricsMap = getMetricsMap();
+ Assertions.assertTrue(metricsMap.containsKey(name));
+
+ MetricSample sample = metricsMap.get(name);
+
+ Assertions.assertSame(((GaugeMetricSample) sample).applyAsLong(), count);
+ teardown();
+ }
+
+
+
+ private void initParam() {
+ invocation.setTargetServiceUniqueName(GROUP + "/" + INTERFACE_NAME + ":" + VERSION);
+ invocation.setMethodName(METHOD_NAME);
+ invocation.setParameterTypes(new Class[]{String.class});
+ }
+
+ private Map getMetricsMap() {
+ List samples = collector.collect();
+ List samples1 = new ArrayList<>();
+ for (MetricSample sample : samples) {
+ if (sample.getName().contains("dubbo.thread.pool")) {
+ continue;
+ }
+ samples1.add(sample);
+ }
+ return samples1.stream().collect(Collectors.toMap(MetricSample::getName, Function.identity()));
+ }
+
+ public class TestMetricsInvoker implements Invoker {
+
+ private String side;
+
+ public TestMetricsInvoker(String side) {
+ this.side = side;
+ }
+
+ @Override
+ public Class getInterface() {
+ return null;
+ }
+
+ @Override
+ public Result invoke(Invocation invocation) throws RpcException {
+ return null;
+ }
+
+ @Override
+ public URL getUrl() {
+ return URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side="+side);
+ }
+
+ @Override
+ public boolean isAvailable() {
+ return true;
+ }
+
+ @Override
+ public void destroy() {
+
+ }
+ }
+}
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java
new file mode 100644
index 0000000000..9bd89552e3
--- /dev/null
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter;
+
+import org.apache.dubbo.rpc.AttachmentsAdapter;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.RpcInvocation;
+import org.apache.dubbo.rpc.model.ServiceModel;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
+import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
+import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
+
+/**
+ * MockInvocation.java
+ */
+public class MockInvocation extends RpcInvocation {
+
+ private Map attachments;
+
+ public MockInvocation() {
+ attachments = new HashMap<>();
+ attachments.put(PATH_KEY, "dubbo");
+ attachments.put(GROUP_KEY, "dubbo");
+ attachments.put(VERSION_KEY, "1.0.0");
+ attachments.put(DUBBO_VERSION_KEY, "1.0.0");
+ attachments.put(TOKEN_KEY, "sfag");
+ attachments.put(TIMEOUT_KEY, "1000");
+ }
+
+ @Override
+ public String getTargetServiceUniqueName() {
+ return null;
+ }
+
+ @Override
+ public String getProtocolServiceKey() {
+ return null;
+ }
+
+ public String getMethodName() {
+ return "echo";
+ }
+
+ @Override
+ public String getServiceName() {
+ return "DemoService";
+ }
+
+ public Class>[] getParameterTypes() {
+ return new Class[] {String.class};
+ }
+
+ public Object[] getArguments() {
+ return new Object[] {"aa"};
+ }
+
+ public Map getAttachments() {
+ return new AttachmentsAdapter.ObjectToStringMap(attachments);
+ }
+
+ @Override
+ public Map getObjectAttachments() {
+ return attachments;
+ }
+
+ @Override
+ public void setAttachment(String key, String value) {
+ setObjectAttachment(key, value);
+ }
+
+ @Override
+ public void setAttachment(String key, Object value) {
+ setObjectAttachment(key, value);
+ }
+
+ @Override
+ public void setObjectAttachment(String key, Object value) {
+ attachments.put(key, value);
+ }
+
+ @Override
+ public void setAttachmentIfAbsent(String key, String value) {
+ setObjectAttachmentIfAbsent(key, value);
+ }
+
+ @Override
+ public void setAttachmentIfAbsent(String key, Object value) {
+ setObjectAttachmentIfAbsent(key, value);
+ }
+
+ @Override
+ public void setObjectAttachmentIfAbsent(String key, Object value) {
+ attachments.put(key, value);
+ }
+
+ public Invoker> getInvoker() {
+ return null;
+ }
+
+ @Override
+ public void setServiceModel(ServiceModel serviceModel) {
+
+ }
+
+ @Override
+ public ServiceModel getServiceModel() {
+ return null;
+ }
+
+ @Override
+ public Object put(Object key, Object value) {
+ return null;
+ }
+
+ @Override
+ public Object get(Object key) {
+ return null;
+ }
+
+ @Override
+ public Map getAttributes() {
+ return null;
+ }
+
+ public String getAttachment(String key) {
+ return (String) getObjectAttachments().get(key);
+ }
+
+ @Override
+ public Object getObjectAttachment(String key) {
+ return attachments.get(key);
+ }
+
+ public String getAttachment(String key, String defaultValue) {
+ return (String) getObjectAttachments().get(key);
+ }
+
+ @Override
+ public Object getObjectAttachment(String key, Object defaultValue) {
+ Object result = attachments.get(key);
+ if (result == null) {
+ return defaultValue;
+ }
+ return result;
+ }
+
+}
diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/ObservationSenderFilterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/ObservationSenderFilterTest.java
similarity index 92%
rename from dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/ObservationSenderFilterTest.java
rename to dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/ObservationSenderFilterTest.java
index e25c2412b6..8166203400 100644
--- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/ObservationSenderFilterTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/ObservationSenderFilterTest.java
@@ -15,21 +15,22 @@
* limitations under the License.
*/
-package org.apache.dubbo.metrics.observation;
+package org.apache.dubbo.rpc.cluster.filter;
import io.micrometer.common.KeyValues;
import io.micrometer.core.tck.MeterRegistryAssert;
+import io.micrometer.tracing.test.SampleTestRunner;
import io.micrometer.tracing.test.simple.SpansAssert;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.RpcContext;
-import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
+import org.apache.dubbo.rpc.cluster.filter.support.ObservationSenderFilter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.assertj.core.api.BDDAssertions;
class ObservationSenderFilterTest extends AbstractObservationFilterTest {
@Override
- public SampleTestRunnerConsumer yourCode() {
+ public SampleTestRunner.SampleTestRunnerConsumer yourCode() {
return (buildingBlocks, meterRegistry) -> {
setupConfig();
setupAttachments();
diff --git a/dubbo-metrics/dubbo-metrics-default/pom.xml b/dubbo-metrics/dubbo-metrics-default/pom.xml
index bc4165d765..87ec6a3b9b 100644
--- a/dubbo-metrics/dubbo-metrics-default/pom.xml
+++ b/dubbo-metrics/dubbo-metrics-default/pom.xml
@@ -46,11 +46,6 @@
micrometer-tracing-integration-testtest
-
- org.apache.dubbo
- dubbo-cluster
- ${project.parent.version}
- compile
-
+
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
deleted file mode 100644
index 5714fefb30..0000000000
--- a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter
+++ /dev/null
@@ -1,2 +0,0 @@
-observationsender=org.apache.dubbo.metrics.observation.ObservationSenderFilter
-metricsClusterFilter=org.apache.dubbo.metrics.filter.MetricsClusterFilter
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 a50fd29dc6..be10b9fd7a 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
@@ -45,12 +45,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_PARAMETER_DESC;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY;
@@ -64,7 +58,6 @@ class MetricsFilterTest {
private ApplicationModel applicationModel;
private MetricsFilter filter;
- private MetricsClusterFilter metricsClusterFilter;
private DefaultMetricsCollector collector;
private RpcInvocation invocation;
private final Invoker> invoker = mock(Invoker.class);
@@ -99,9 +92,6 @@ class MetricsFilterTest {
side = CommonConstants.CONSUMER;
invocation.setInvoker(new TestMetricsInvoker(side));
RpcContext.getServiceContext().setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side));
-
- metricsClusterFilter = new MetricsClusterFilter();
- metricsClusterFilter.setApplicationModel(applicationModel);
}
@AfterEach
@@ -281,37 +271,6 @@ class MetricsFilterTest {
MetricsKey.METRIC_REQUESTS_NETWORK_FAILED.getNameByType(side));
}
- @Test
- public void testNoProvider() {
- testClusterFilterError(RpcException.FORBIDDEN_EXCEPTION,
- MetricsKey.METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED.getNameByType(CommonConstants.CONSUMER));
- }
-
- private void testClusterFilterError(int errorCode, String name) {
-// setup();
- collector.setCollectEnabled(true);
- given(invoker.invoke(invocation)).willThrow(new RpcException(errorCode));
- initParam();
-
- Long count = 1L;
-
- for (int i = 0; i < count; i++) {
- try {
- metricsClusterFilter.invoke(invoker, invocation);
- } catch (Exception e) {
- Assertions.assertTrue(e instanceof RpcException);
- metricsClusterFilter.onError(e, invoker, invocation);
- }
- }
- Map metricsMap = getMetricsMap();
- Assertions.assertTrue(metricsMap.containsKey(name));
-
- MetricSample sample = metricsMap.get(name);
-
- Assertions.assertSame(((GaugeMetricSample) sample).applyAsLong(), count);
- teardown();
- }
-
private void testFilterError(int errorCode, String name) {
setup();
collector.setCollectEnabled(true);
diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java
index dc5b1b609a..dc4ef5937f 100644
--- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java
+++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java
@@ -450,7 +450,6 @@ public class NettyBackedChannelBuffer implements ChannelBuffer {
return ChannelBuffers.compare(this, o);
}
- @Override
public void release() {
ReferenceCountUtil.safeRelease(buffer);
}
From c91affe875a7fc500500d2e5f874caed945afde7 Mon Sep 17 00:00:00 2001
From: fomeiherz
Date: Mon, 27 Mar 2023 09:48:38 +0800
Subject: [PATCH 016/122] Add metrics for configcenter (#11602)
* Add ConfigCenter metrics.
* Modifying the obtaining mode for ConfigCenterMetricsCollector.
* Modify method name.
* Add metrics when configCenter initialized.
* Add UnitTest
* Add License.
* bugfix: config test not pass.
* 1.delete author
2.unuse imported
* fix configcenter metrics zk factory
* Get 'dubbo.metrics.configcenter.enable' config from property, get config before startup.
* resolve conflict
---------
Co-authored-by: Albumen Kevin
Co-authored-by: songxiaosheng
---
.../common/constants/CommonConstants.java | 2 +
.../common/constants/MetricsConstants.java | 6 +
.../deploy/DefaultApplicationDeployer.java | 26 ++++-
.../dubbo-configcenter-apollo/pom.xml | 15 +++
.../apollo/ApolloDynamicConfiguration.java | 10 +-
.../ApolloDynamicConfigurationFactory.java | 10 +-
.../ApolloDynamicConfigurationTest.java | 11 +-
.../dubbo-configcenter-nacos/pom.xml | 15 +++
.../nacos/NacosDynamicConfiguration.java | 13 ++-
.../NacosDynamicConfigurationFactory.java | 9 +-
.../nacos/NacosDynamicConfigurationTest.java | 12 +-
.../configcenter/support/nacos/RetryTest.java | 13 ++-
.../dubbo-configcenter-zookeeper/pom.xml | 15 +++
.../support/zookeeper/CacheListener.java | 5 +-
.../zookeeper/ZookeeperDataListener.java | 19 +++-
.../ZookeeperDynamicConfiguration.java | 7 +-
.../ZookeeperDynamicConfigurationFactory.java | 5 +-
dubbo-metrics/dubbo-metrics-api/pom.xml | 5 +
.../metrics/model/ConfigCenterMetric.java | 88 +++++++++++++++
.../dubbo/metrics/model/MetricsCategory.java | 3 +-
.../dubbo/metrics/model/MetricsKey.java | 2 +
.../ConfigCenterMetricsCollector.java | 99 +++++++++++++++++
.../ConfigCenterMetricsCollectorTest.java | 104 ++++++++++++++++++
23 files changed, 457 insertions(+), 37 deletions(-)
create mode 100644 dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ConfigCenterMetric.java
create mode 100644 dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollector.java
create mode 100644 dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java
index 6a723f78a4..c8f1ab7a9e 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java
@@ -626,4 +626,6 @@ public interface CommonConstants {
String BYTE_ACCESSOR_KEY = "byte.accessor";
String PAYLOAD = "payload";
+
+ String DUBBO_METRICS_CONFIGCENTER_ENABLE = "dubbo.metrics.configcenter.enable";
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetricsConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetricsConstants.java
index 89e0333b36..58b6b39887 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetricsConstants.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetricsConstants.java
@@ -37,6 +37,12 @@ public interface MetricsConstants {
String TAG_VERSION_KEY = "version";
String TAG_APPLICATION_VERSION_KEY = "application.version";
+
+ String TAG_KEY_KEY = "key";
+
+ String TAG_CONFIG_CENTER = "config.center";
+
+ String TAG_CHANGE_TYPE = "change.type";
String ENABLE_JVM_METRICS_KEY = "enable.jvm.metrics";
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 12d29ff2e5..c933e43b42 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
@@ -50,6 +50,7 @@ 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.ConfigCenterMetricsCollector;
import org.apache.dubbo.metrics.collector.DefaultMetricsCollector;
import org.apache.dubbo.metrics.event.GlobalMetricsEventMulticaster;
import org.apache.dubbo.metrics.model.TimePair;
@@ -782,20 +783,33 @@ public class DefaultApplicationDeployer extends AbstractDeployer configMap = parseProperties(configContent);
+ Map appConfigMap = parseProperties(appConfigContent);
+
+ environment.updateExternalConfigMap(configMap);
+ environment.updateAppExternalConfigMap(appConfigMap);
+
+ // Add metrics
+ collector.increase4Initialized(configCenter.getConfigFile(), configCenter.getGroup(),
+ configCenter.getProtocol(), applicationModel.getApplicationName(), configMap.size());
+ if (isNotEmpty(appGroup)) {
+ collector.increase4Initialized(appConfigFile, appGroup,
+ configCenter.getProtocol(), applicationModel.getApplicationName(), appConfigMap.size());
+ }
} catch (IOException e) {
throw new IllegalStateException("Failed to parse configurations from Config Center.", e);
}
diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml
index d31dc785be..5b86955599 100644
--- a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml
+++ b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml
@@ -38,6 +38,21 @@
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.apolloapollo-client
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 9525f7ce7e..1b33e85781 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
@@ -33,6 +33,8 @@ import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
import com.ctrip.framework.apollo.model.ConfigChange;
+import org.apache.dubbo.metrics.collector.ConfigCenterMetricsCollector;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Arrays;
import java.util.Collections;
@@ -76,9 +78,11 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration {
private final Config dubboConfig;
private final ConfigFile dubboConfigFile;
private final ConcurrentMap listeners = new ConcurrentHashMap<>();
+ private final ApplicationModel applicationModel;
- ApolloDynamicConfiguration(URL url) {
+ ApolloDynamicConfiguration(URL url, ApplicationModel applicationModel) {
this.url = url;
+ this.applicationModel = applicationModel;
// Instead of using Dubbo's configuration, I would suggest use the original configuration method Apollo provides.
String configEnv = url.getParameter(APOLLO_ENV_KEY);
String configAddr = getAddressWithProtocolPrefix(url);
@@ -245,6 +249,10 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration {
ConfigChangedEvent event = new ConfigChangedEvent(key, change.getNamespace(), change.getNewValue(), getChangeType(change));
listeners.forEach(listener -> listener.process(event));
+
+ ConfigCenterMetricsCollector collector =
+ applicationModel.getBeanFactory().getBean(ConfigCenterMetricsCollector.class);
+ collector.increaseUpdated("apollo", applicationModel.getApplicationName(), event);
}
}
diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java
index 6a8ce304f4..64331d886b 100644
--- a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java
+++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java
@@ -19,13 +19,21 @@ package org.apache.dubbo.configcenter.support.apollo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
+import org.apache.dubbo.rpc.model.ApplicationModel;
/**
*
*/
public class ApolloDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory {
+
+ private ApplicationModel applicationModel;
+
+ public ApolloDynamicConfigurationFactory(ApplicationModel applicationModel) {
+ this.applicationModel = applicationModel;
+ }
+
@Override
protected DynamicConfiguration createDynamicConfiguration(URL url) {
- return new ApolloDynamicConfiguration(url);
+ return new ApolloDynamicConfiguration(url, applicationModel);
}
}
diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationTest.java
index a54ffd37ad..07aa131e67 100644
--- a/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationTest.java
+++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationTest.java
@@ -21,6 +21,7 @@ import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import com.google.common.util.concurrent.SettableFuture;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -46,6 +47,7 @@ class ApolloDynamicConfigurationTest {
private static final String DEFAULT_NAMESPACE = "dubbo";
private static ApolloDynamicConfiguration apolloDynamicConfiguration;
private static URL url;
+ private static ApplicationModel applicationModel;
/**
* The constant embeddedApollo.
@@ -61,6 +63,7 @@ class ApolloDynamicConfigurationTest {
String apolloUrl = System.getProperty("apollo.configService");
String urlForDubbo = "apollo://" + apolloUrl.substring(apolloUrl.lastIndexOf("/") + 1) + "/org.apache.dubbo.apollo.testService?namespace=dubbo&check=true";
url = URL.valueOf(urlForDubbo).addParameter(SESSION_TIMEOUT_KEY, 15000);
+ applicationModel = ApplicationModel.defaultModel();
}
// /**
@@ -88,7 +91,7 @@ class ApolloDynamicConfigurationTest {
String mockKey = "mockKey1";
String mockValue = String.valueOf(new Random().nextInt());
putMockRuleData(mockKey, mockValue, DEFAULT_NAMESPACE);
- apolloDynamicConfiguration = new ApolloDynamicConfiguration(url);
+ apolloDynamicConfiguration = new ApolloDynamicConfiguration(url, applicationModel);
assertEquals(mockValue, apolloDynamicConfiguration.getConfig(mockKey, DEFAULT_NAMESPACE, 3000L));
mockKey = "notExistKey";
@@ -106,7 +109,7 @@ class ApolloDynamicConfigurationTest {
String mockValue = String.valueOf(new Random().nextInt());
putMockRuleData(mockKey, mockValue, DEFAULT_NAMESPACE);
TimeUnit.MILLISECONDS.sleep(1000);
- apolloDynamicConfiguration = new ApolloDynamicConfiguration(url);
+ apolloDynamicConfiguration = new ApolloDynamicConfiguration(url, applicationModel);
assertEquals(mockValue, apolloDynamicConfiguration.getInternalProperty(mockKey));
mockValue = "mockValue2";
@@ -129,7 +132,7 @@ class ApolloDynamicConfigurationTest {
final SettableFuture future = SettableFuture.create();
- apolloDynamicConfiguration = new ApolloDynamicConfiguration(url);
+ apolloDynamicConfiguration = new ApolloDynamicConfiguration(url, applicationModel);
apolloDynamicConfiguration.addListener(mockKey, DEFAULT_NAMESPACE, new ConfigurationListener() {
@Override
@@ -187,4 +190,4 @@ class ApolloDynamicConfigurationTest {
}
-}
\ No newline at end of file
+}
diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml
index 65364b8bed..a6bc25f483 100644
--- a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml
+++ b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml
@@ -41,5 +41,20 @@
com.alibaba.nacosnacos-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}
+
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 359d33770a..9a8e42b2bb 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
@@ -43,6 +43,8 @@ import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractSharedListener;
import com.alibaba.nacos.api.exception.NacosException;
+import org.apache.dubbo.metrics.collector.ConfigCenterMetricsCollector;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import static com.alibaba.nacos.api.PropertyKeyConst.PASSWORD;
import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR;
@@ -80,6 +82,8 @@ public class NacosDynamicConfiguration implements DynamicConfiguration {
*/
private final NacosConfigServiceWrapper configService;
+ private ApplicationModel applicationModel;
+
/**
* The map store the key to {@link NacosConfigListener} mapping
*/
@@ -87,10 +91,11 @@ public class NacosDynamicConfiguration implements DynamicConfiguration {
private final MD5Utils md5Utils = new MD5Utils();
- NacosDynamicConfiguration(URL url) {
+ NacosDynamicConfiguration(URL url, ApplicationModel applicationModel) {
this.nacosProperties = buildNacosProperties(url);
this.configService = buildConfigService(url);
- watchListenerMap = new ConcurrentHashMap<>();
+ this.watchListenerMap = new ConcurrentHashMap<>();
+ this.applicationModel = applicationModel;
}
private NacosConfigServiceWrapper buildConfigService(URL url) {
@@ -339,6 +344,10 @@ public class NacosDynamicConfiguration implements DynamicConfiguration {
cacheData.put(dataId, configInfo);
}
listeners.forEach(listener -> listener.process(event));
+
+ ConfigCenterMetricsCollector collector =
+ applicationModel.getBeanFactory().getOrRegisterBean(ConfigCenterMetricsCollector.class);
+ collector.increaseUpdated("nacos", applicationModel.getApplicationName(), event);
}
void addListener(ConfigurationListener configurationListener) {
diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java
index 61c02b48cf..5d2196726d 100644
--- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java
+++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java
@@ -23,12 +23,19 @@ import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.constants.CommonConstants;
import com.alibaba.nacos.api.PropertyKeyConst;
+import org.apache.dubbo.rpc.model.ApplicationModel;
/**
* The nacos implementation of {@link AbstractDynamicConfigurationFactory}
*/
public class NacosDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory {
+ private ApplicationModel applicationModel;
+
+ public NacosDynamicConfigurationFactory(ApplicationModel applicationModel) {
+ this.applicationModel = applicationModel;
+ }
+
@Override
protected DynamicConfiguration createDynamicConfiguration(URL url) {
URL nacosURL = url;
@@ -36,6 +43,6 @@ public class NacosDynamicConfigurationFactory extends AbstractDynamicConfigurati
// Nacos use empty string as default name space, replace default namespace "dubbo" to ""
nacosURL = url.removeParameter(PropertyKeyConst.NAMESPACE);
}
- return new NacosDynamicConfiguration(nacosURL);
+ return new NacosDynamicConfiguration(nacosURL, applicationModel);
}
}
diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java
index 3f2bb525fd..831c74c833 100644
--- a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java
+++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java
@@ -17,14 +17,14 @@
package org.apache.dubbo.configcenter.support.nacos;
+import com.alibaba.nacos.api.NacosFactory;
+import com.alibaba.nacos.api.config.ConfigService;
+import com.alibaba.nacos.api.exception.NacosException;
import org.apache.dubbo.common.URL;
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 com.alibaba.nacos.api.NacosFactory;
-import com.alibaba.nacos.api.config.ConfigService;
-import com.alibaba.nacos.api.exception.NacosException;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
@@ -132,7 +132,7 @@ class NacosDynamicConfigurationTest {
// timeout in 15 seconds.
URL url = URL.valueOf(urlForDubbo)
.addParameter(SESSION_TIMEOUT_KEY, 15000);
- config = new NacosDynamicConfiguration(url);
+ config = new NacosDynamicConfiguration(url, ApplicationModel.defaultModel());
try {
@@ -184,4 +184,4 @@ class NacosDynamicConfigurationTest {
}
}
-}
\ No newline at end of file
+}
diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/RetryTest.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/RetryTest.java
index 3be9037380..32116ba247 100644
--- a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/RetryTest.java
+++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/RetryTest.java
@@ -20,6 +20,7 @@ import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
@@ -34,6 +35,8 @@ import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP;
import static org.mockito.ArgumentMatchers.any;
class RetryTest {
+
+ private static ApplicationModel applicationModel = ApplicationModel.defaultModel();
@Test
void testRetryCreate() {
@@ -51,10 +54,10 @@ class RetryTest {
URL url = URL.valueOf("nacos://127.0.0.1:8848")
.addParameter("nacos.retry", 5)
.addParameter("nacos.retry-wait", 10);
- Assertions.assertThrows(IllegalStateException.class, () -> new NacosDynamicConfiguration(url));
+ Assertions.assertThrows(IllegalStateException.class, () -> new NacosDynamicConfiguration(url, applicationModel));
try {
- new NacosDynamicConfiguration(url);
+ new NacosDynamicConfiguration(url, applicationModel);
} catch (Throwable t) {
Assertions.fail(t);
}
@@ -78,7 +81,7 @@ class RetryTest {
.addParameter("nacos.retry-wait", 10)
.addParameter("nacos.check", "false");
try {
- new NacosDynamicConfiguration(url);
+ new NacosDynamicConfiguration(url, applicationModel);
} catch (Throwable t) {
Assertions.fail(t);
}
@@ -110,10 +113,10 @@ class RetryTest {
URL url = URL.valueOf("nacos://127.0.0.1:8848")
.addParameter("nacos.retry", 5)
.addParameter("nacos.retry-wait", 10);
- Assertions.assertThrows(IllegalStateException.class, () -> new NacosDynamicConfiguration(url));
+ Assertions.assertThrows(IllegalStateException.class, () -> new NacosDynamicConfiguration(url, applicationModel));
try {
- new NacosDynamicConfiguration(url);
+ new NacosDynamicConfiguration(url, applicationModel);
} catch (Throwable t) {
Assertions.fail(t);
}
diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml b/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml
index 8166ca072d..825fbbb289 100644
--- a/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml
+++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml
@@ -60,6 +60,21 @@
org.apache.zookeeperzookeeper
+
+ 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}
+
diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java
index 7ae31afca0..df596926b7 100644
--- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java
+++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java
@@ -19,6 +19,7 @@ package org.apache.dubbo.configcenter.support.zookeeper;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -34,9 +35,9 @@ public class CacheListener {
public CacheListener() {
}
- public ZookeeperDataListener addListener(String pathKey, ConfigurationListener configurationListener, String key, String group) {
+ public ZookeeperDataListener addListener(String pathKey, ConfigurationListener configurationListener, String key, String group, ApplicationModel applicationModel) {
ZookeeperDataListener zookeeperDataListener = ConcurrentHashMapUtils.computeIfAbsent(pathKeyListeners, pathKey,
- _pathKey -> new ZookeeperDataListener(_pathKey, key, group));
+ _pathKey -> new ZookeeperDataListener(_pathKey, key, group, applicationModel));
zookeeperDataListener.addListener(configurationListener);
return zookeeperDataListener;
}
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 22243d55ed..a21babe2a2 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
@@ -20,8 +20,10 @@ 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.utils.CollectionUtils;
+import org.apache.dubbo.metrics.collector.ConfigCenterMetricsCollector;
import org.apache.dubbo.remoting.zookeeper.DataListener;
import org.apache.dubbo.remoting.zookeeper.EventType;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
@@ -30,16 +32,19 @@ import java.util.concurrent.CopyOnWriteArraySet;
* one path has multi configurationListeners
*/
public class ZookeeperDataListener implements DataListener {
- private final String path;
- private final String key;
- private final String group;
- private final Set listeners;
- public ZookeeperDataListener(String path, String key, String group) {
+ private String path;
+ private String key;
+ private String group;
+ private Set listeners;
+ private ApplicationModel applicationModel;
+
+ public ZookeeperDataListener(String path, String key, String group, ApplicationModel applicationModel) {
this.path = path;
this.key = key;
this.group = group;
this.listeners = new CopyOnWriteArraySet<>();
+ this.applicationModel = applicationModel;
}
public void addListener(ConfigurationListener configurationListener) {
@@ -71,6 +76,10 @@ public class ZookeeperDataListener implements DataListener {
if (CollectionUtils.isNotEmpty(listeners)) {
listeners.forEach(listener -> listener.process(configChangeEvent));
}
+
+ ConfigCenterMetricsCollector collector =
+ applicationModel.getBeanFactory().getBean(ConfigCenterMetricsCollector.class);
+ collector.increaseUpdated("zookeeper", applicationModel.getApplicationName(), configChangeEvent);
}
}
diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java
index 423c2834f6..e0bc325c4c 100644
--- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java
+++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java
@@ -26,6 +26,7 @@ import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.remoting.zookeeper.ZookeeperClient;
import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter;
+import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.zookeeper.data.Stat;
import java.util.Collection;
@@ -47,11 +48,13 @@ public class ZookeeperDynamicConfiguration extends TreePathDynamicConfiguration
private static final int DEFAULT_ZK_EXECUTOR_THREADS_NUM = 1;
private static final int DEFAULT_QUEUE = 10000;
private static final Long THREAD_KEEP_ALIVE_TIME = 0L;
+ private final ApplicationModel applicationModel;
- ZookeeperDynamicConfiguration(URL url, ZookeeperTransporter zookeeperTransporter) {
+ ZookeeperDynamicConfiguration(URL url, ZookeeperTransporter zookeeperTransporter, ApplicationModel applicationModel) {
super(url);
this.cacheListener = new CacheListener();
+ this.applicationModel = applicationModel;
final String threadName = this.getClass().getSimpleName();
this.executor = new ThreadPoolExecutor(DEFAULT_ZK_EXECUTOR_THREADS_NUM, DEFAULT_ZK_EXECUTOR_THREADS_NUM,
@@ -150,7 +153,7 @@ public class ZookeeperDynamicConfiguration extends TreePathDynamicConfiguration
if (cachedListener != null) {
cachedListener.addListener(listener);
} else {
- ZookeeperDataListener addedListener = cacheListener.addListener(pathKey, listener, key, group);
+ ZookeeperDataListener addedListener = cacheListener.addListener(pathKey, listener, key, group, applicationModel);
zkClient.addDataListener(pathKey, addedListener, executor);
}
}
diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationFactory.java
index f470654ca5..1ab7497379 100644
--- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationFactory.java
+++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationFactory.java
@@ -26,12 +26,15 @@ public class ZookeeperDynamicConfigurationFactory extends AbstractDynamicConfigu
private final ZookeeperTransporter zookeeperTransporter;
+ private final ApplicationModel applicationModel;
+
public ZookeeperDynamicConfigurationFactory(ApplicationModel applicationModel) {
+ this.applicationModel = applicationModel;
this.zookeeperTransporter = ZookeeperTransporter.getExtension(applicationModel);
}
@Override
protected DynamicConfiguration createDynamicConfiguration(URL url) {
- return new ZookeeperDynamicConfiguration(url, zookeeperTransporter);
+ return new ZookeeperDynamicConfiguration(url, zookeeperTransporter, applicationModel);
}
}
diff --git a/dubbo-metrics/dubbo-metrics-api/pom.xml b/dubbo-metrics/dubbo-metrics-api/pom.xml
index 3c31ae389c..a35c238395 100644
--- a/dubbo-metrics/dubbo-metrics-api/pom.xml
+++ b/dubbo-metrics/dubbo-metrics-api/pom.xml
@@ -49,5 +49,10 @@
com.tdunningt-digest
+
+ io.micrometer
+ micrometer-tracing-integration-test
+ test
+
diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ConfigCenterMetric.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ConfigCenterMetric.java
new file mode 100644
index 0000000000..a6f9987e03
--- /dev/null
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ConfigCenterMetric.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.dubbo.metrics.model;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_CHANGE_TYPE;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_CONFIG_CENTER;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_KEY_KEY;
+import static org.apache.dubbo.common.utils.NetUtils.getLocalHost;
+import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName;
+
+public class ConfigCenterMetric implements Metric {
+
+ private String applicationName;
+ private String key;
+ private String group;
+ private String configCenter;
+ private String changeType;
+
+ public ConfigCenterMetric() {
+
+ }
+
+ public ConfigCenterMetric(String applicationName, String key, String group, String configCenter, String changeType) {
+ this.applicationName = applicationName;
+ this.key = key;
+ this.group = group;
+ this.configCenter = configCenter;
+ this.changeType = changeType;
+ }
+
+ @Override
+ public Map getTags() {
+ Map tags = new HashMap<>();
+ tags.put(TAG_IP, getLocalHost());
+ tags.put(TAG_HOSTNAME, getLocalHostName());
+ tags.put(TAG_APPLICATION_NAME, applicationName);
+
+ tags.put(TAG_KEY_KEY, key);
+ tags.put(TAG_GROUP_KEY, group);
+ tags.put(TAG_CONFIG_CENTER, configCenter);
+ tags.put(TAG_CHANGE_TYPE, changeType.toLowerCase());
+
+ return tags;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ ConfigCenterMetric that = (ConfigCenterMetric) o;
+
+ if (!Objects.equals(applicationName, that.applicationName))
+ return false;
+ if (!Objects.equals(key, that.key)) return false;
+ if (!Objects.equals(group, that.group)) return false;
+ if (!Objects.equals(configCenter, that.configCenter)) return false;
+ return Objects.equals(changeType, that.changeType);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(applicationName, key, group, configCenter, changeType);
+ }
+}
diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsCategory.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsCategory.java
index 990044374b..0eecdda807 100644
--- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsCategory.java
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsCategory.java
@@ -24,8 +24,9 @@ public enum MetricsCategory {
RT,
QPS,
REQUESTS,
+ APPLICATION,
+ CONFIGCENTER,
REGISTRY,
METADATA,
THREAD_POOL,
- APPLICATION
}
diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
index 2592f706cd..6065ee5289 100644
--- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
@@ -20,6 +20,8 @@ package org.apache.dubbo.metrics.model;
public enum MetricsKey {
APPLICATION_METRIC_INFO("dubbo.application.info.total", "Total Application Info"),
+ CONFIGCENTER_METRIC_TOTAL("dubbo.configcenter.total", "Config Changed Total"),
+
// provider metrics key
METRIC_REQUESTS("dubbo.%s.requests.total", "Total Requests"),
METRIC_REQUESTS_SUCCEED("dubbo.%s.requests.succeed.total", "Total Succeed Requests"),
diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollector.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollector.java
new file mode 100644
index 0000000000..1170243e28
--- /dev/null
+++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollector.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.dubbo.metrics.collector;
+
+import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
+import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
+import org.apache.dubbo.metrics.model.ConfigCenterMetric;
+import org.apache.dubbo.metrics.model.MetricsKey;
+import org.apache.dubbo.metrics.model.sample.GaugeMetricSample;
+import org.apache.dubbo.metrics.model.sample.MetricSample;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_METRICS_CONFIGCENTER_ENABLE;
+import static org.apache.dubbo.metrics.model.MetricsCategory.CONFIGCENTER;
+
+public class ConfigCenterMetricsCollector implements MetricsCollector {
+
+ private boolean collectEnabled = true;
+ private final ApplicationModel applicationModel;
+
+ private final Map updatedMetrics = new ConcurrentHashMap<>();
+
+ public ConfigCenterMetricsCollector(ApplicationModel applicationModel) {
+ this.applicationModel = applicationModel;
+ // default is true, disable when config false
+ if ("false".equals(System.getProperty(DUBBO_METRICS_CONFIGCENTER_ENABLE))) {
+ collectEnabled = false;
+ }
+ }
+
+ public void setCollectEnabled(Boolean collectEnabled) {
+ if (collectEnabled != null) {
+ this.collectEnabled = collectEnabled;
+ }
+ }
+
+ @Override
+ public boolean isCollectEnabled() {
+ return collectEnabled;
+ }
+
+ public void increase4Initialized(String key, String group, String protocol, String applicationName, int count) {
+ if (!isCollectEnabled()) {
+ return;
+ }
+ if (count <= 0) {
+ return;
+ }
+ ConfigCenterMetric metric = new ConfigCenterMetric(applicationName, key, group, protocol, ConfigChangeType.ADDED.name());
+ AtomicLong aLong = updatedMetrics.computeIfAbsent(metric, k -> new AtomicLong(0L));
+ aLong.addAndGet(count);
+ }
+
+ public void increaseUpdated(String protocol, String applicationName, ConfigChangedEvent event) {
+ if (!isCollectEnabled()) {
+ return;
+ }
+ ConfigCenterMetric metric = new ConfigCenterMetric(applicationName, event.getKey(), event.getGroup(), protocol, event.getChangeType().name());
+ AtomicLong count = updatedMetrics.computeIfAbsent(metric, k -> new AtomicLong(0L));
+ count.incrementAndGet();
+ }
+
+ @Override
+ public List collect() {
+ // Add metrics to reporter
+ List list = new ArrayList<>();
+ if (!isCollectEnabled()) {
+ return list;
+ }
+ collect(list);
+ return list;
+ }
+
+ private void collect(List list) {
+ updatedMetrics.forEach((k, v) -> list.add(new GaugeMetricSample<>(MetricsKey.CONFIGCENTER_METRIC_TOTAL, k.getTags(), CONFIGCENTER, v, AtomicLong::get)));
+ }
+
+}
diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java
new file mode 100644
index 0000000000..e234279339
--- /dev/null
+++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.dubbo.metrics.collector;
+
+import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
+import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.metrics.model.ConfigCenterMetric;
+import org.apache.dubbo.metrics.model.sample.GaugeMetricSample;
+import org.apache.dubbo.metrics.model.sample.MetricSample;
+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.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+import java.util.function.Supplier;
+
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_INTERFACE_KEY;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_METHOD_KEY;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_VERSION_KEY;
+import static org.junit.jupiter.api.Assertions.*;
+
+class ConfigCenterMetricsCollectorTest {
+
+ private FrameworkModel frameworkModel;
+ private ApplicationModel applicationModel;
+
+ @BeforeEach
+ public void setup() {
+ frameworkModel = FrameworkModel.defaultModel();
+ applicationModel = frameworkModel.newApplication();
+ ApplicationConfig config = new ApplicationConfig();
+ config.setName("MockMetrics");
+
+ applicationModel.getApplicationConfigManager().setApplication(config);
+ }
+
+ @AfterEach
+ public void teardown() {
+ applicationModel.destroy();
+ }
+
+ @Test
+ void increase4Initialized() {
+ ConfigCenterMetricsCollector collector = new ConfigCenterMetricsCollector(applicationModel);
+ collector.setCollectEnabled(true);
+ String applicationName = applicationModel.getApplicationName();
+ collector.increase4Initialized("key", "group", "nacos", applicationName, 1);
+ collector.increase4Initialized("key", "group", "nacos", applicationName, 1);
+
+ List samples = collector.collect();
+ for (MetricSample sample : samples) {
+ Assertions.assertTrue(sample instanceof GaugeMetricSample);
+ GaugeMetricSample gaugeSample = (GaugeMetricSample) sample;
+ Map tags = gaugeSample.getTags();
+
+ Assertions.assertEquals(gaugeSample.applyAsLong(), 2);
+ Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationName);
+ }
+ }
+
+ @Test
+ void increaseUpdated() {
+ ConfigCenterMetricsCollector collector = new ConfigCenterMetricsCollector(applicationModel);
+ collector.setCollectEnabled(true);
+ String applicationName = applicationModel.getApplicationName();
+
+ ConfigChangedEvent event = new ConfigChangedEvent("key", "group", null, ConfigChangeType.ADDED);
+
+ collector.increaseUpdated("nacos", applicationName, event);
+ collector.increaseUpdated("nacos", applicationName, event);
+
+ List samples = collector.collect();
+ for (MetricSample sample : samples) {
+ Assertions.assertTrue(sample instanceof GaugeMetricSample);
+ GaugeMetricSample gaugeSample = (GaugeMetricSample) sample;
+ Map tags = gaugeSample.getTags();
+
+ Assertions.assertEquals(gaugeSample.applyAsLong(), 2);
+ Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationName);
+ }
+ }
+}
From 6faf548e2463693e70274015bc8d11d624c12f19 Mon Sep 17 00:00:00 2001
From: gsralex
Date: Mon, 27 Mar 2023 09:49:09 +0800
Subject: [PATCH 017/122] Add histogram (#11632)
---
.../common/constants/MetricsConstants.java | 2 +
.../apache/dubbo/config/MetricsConfig.java | 12 +++
.../dubbo/config/nested/HistogramConfig.java | 93 +++++++++++++++++++
.../dubbo/config/MetricsConfigTest.java | 9 +-
.../schema/DubboBeanDefinitionParser.java | 5 +
.../src/main/resources/META-INF/dubbo.xsd | 15 +++
.../SpringBootConfigPropsTest.java | 4 +-
.../SpringBootMultipleConfigPropsTest.java | 4 +-
.../metrics/SpringBootConfigMetricsTest.java | 2 +
.../dubbo/metrics/model/MetricsKey.java | 6 ++
.../apache/dubbo/metrics/DubboMetrics.java | 3 +-
.../dubbo/metrics/MetricsGlobalRegistry.java | 29 ++++++
.../collector/HistogramMetricsCollector.java | 88 ++++++++++++++++++
.../register/HistogramMetricRegister.java | 81 ++++++++++++++++
.../metrics/register/MetricRegister.java | 27 ++++++
.../report/AbstractMetricsReporter.java | 6 +-
.../metrics/sample/HistogramMetricSample.java | 34 +++++++
17 files changed, 413 insertions(+), 7 deletions(-)
create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/config/nested/HistogramConfig.java
create mode 100644 dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java
create mode 100644 dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java
create mode 100644 dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/HistogramMetricRegister.java
create mode 100644 dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/MetricRegister.java
create mode 100644 dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/sample/HistogramMetricSample.java
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetricsConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetricsConstants.java
index 58b6b39887..b41e716bd2 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetricsConstants.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetricsConstants.java
@@ -54,6 +54,8 @@ public interface MetricsConstants {
String AGGREGATION_TIME_WINDOW_SECONDS_KEY = "aggregation.time.window.seconds";
+ String HISTOGRAM_ENABLED_KEY = "histogram.enabled";
+
String PROMETHEUS_EXPORTER_ENABLED_KEY = "prometheus.exporter.enabled";
String PROMETHEUS_EXPORTER_ENABLE_HTTP_SERVICE_DISCOVERY_KEY = "prometheus.exporter.enable.http.service.discovery";
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/MetricsConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/MetricsConfig.java
index 07a1e5f425..d915f53d6b 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/config/MetricsConfig.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/config/MetricsConfig.java
@@ -20,6 +20,7 @@ import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.config.nested.AggregationConfig;
import org.apache.dubbo.config.nested.PrometheusConfig;
+import org.apache.dubbo.config.nested.HistogramConfig;
import org.apache.dubbo.config.support.Nested;
import org.apache.dubbo.rpc.model.ApplicationModel;
@@ -69,6 +70,9 @@ public class MetricsConfig extends AbstractConfig {
@Nested
private AggregationConfig aggregation;
+ @Nested
+ private HistogramConfig histogram;
+
private String exportServiceProtocol;
private Integer exportServicePort;
@@ -140,6 +144,14 @@ public class MetricsConfig extends AbstractConfig {
this.aggregation = aggregation;
}
+ public HistogramConfig getHistogram() {
+ return histogram;
+ }
+
+ public void setHistogram(HistogramConfig histogram) {
+ this.histogram = histogram;
+ }
+
public String getExportServiceProtocol() {
return exportServiceProtocol;
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/nested/HistogramConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/nested/HistogramConfig.java
new file mode 100644
index 0000000000..53ef9ac9e4
--- /dev/null
+++ b/dubbo-common/src/main/java/org/apache/dubbo/config/nested/HistogramConfig.java
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.nested;
+
+import java.io.Serializable;
+
+public class HistogramConfig implements Serializable {
+
+ private Boolean enabled;
+
+ private Integer[] bucketsMs;
+
+ private Integer minExpectedMs;
+
+ private Integer maxExpectedMs;
+
+ private Boolean enabledPercentiles;
+
+ private double[] percentiles;
+
+ private Integer distributionStatisticExpiryMin;
+
+ public Boolean getEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(Boolean enabled) {
+ this.enabled = enabled;
+ }
+
+ public Integer[] getBucketsMs() {
+ return bucketsMs;
+ }
+
+ public void setBucketsMs(Integer[] bucketsMs) {
+ this.bucketsMs = bucketsMs;
+ }
+
+ public Integer getMinExpectedMs() {
+ return minExpectedMs;
+ }
+
+ public void setMinExpectedMs(Integer minExpectedMs) {
+ this.minExpectedMs = minExpectedMs;
+ }
+
+ public Integer getMaxExpectedMs() {
+ return maxExpectedMs;
+ }
+
+ public void setMaxExpectedMs(Integer maxExpectedMs) {
+ this.maxExpectedMs = maxExpectedMs;
+ }
+
+ public Boolean getEnabledPercentiles() {
+ return enabledPercentiles;
+ }
+
+ public void setEnabledPercentiles(Boolean enabledPercentiles) {
+ this.enabledPercentiles = enabledPercentiles;
+ }
+
+ public double[] getPercentiles() {
+ return percentiles;
+ }
+
+ public void setPercentiles(double[] percentiles) {
+ this.percentiles = percentiles;
+ }
+
+ public Integer getDistributionStatisticExpiryMin() {
+ return distributionStatisticExpiryMin;
+ }
+
+ public void setDistributionStatisticExpiryMin(Integer distributionStatisticExpiryMin) {
+ this.distributionStatisticExpiryMin = distributionStatisticExpiryMin;
+ }
+}
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetricsConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetricsConfigTest.java
index f752b7e86c..13a29b8966 100644
--- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetricsConfigTest.java
+++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetricsConfigTest.java
@@ -19,7 +19,7 @@ package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.nested.AggregationConfig;
import org.apache.dubbo.config.nested.PrometheusConfig;
-
+import org.apache.dubbo.config.nested.HistogramConfig;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS;
@@ -47,6 +47,10 @@ class MetricsConfigTest {
aggregation.setEnabled(true);
metrics.setAggregation(aggregation);
+ HistogramConfig histogram = new HistogramConfig();
+ histogram.setEnabled(true);
+ metrics.setHistogram(histogram);
+
URL url = metrics.toUrl();
assertThat(url.getProtocol(), equalTo(PROTOCOL_PROMETHEUS));
@@ -56,6 +60,7 @@ class MetricsConfigTest {
assertThat(url.getParameter("prometheus.exporter.enabled"), equalTo("true"));
assertThat(url.getParameter("prometheus.pushgateway.enabled"), equalTo("true"));
assertThat(url.getParameter("aggregation.enabled"), equalTo("true"));
+ assertThat(url.getParameter("histogram.enabled"), equalTo("true"));
}
@Test
@@ -117,4 +122,4 @@ class MetricsConfigTest {
assertThat(metrics.getAggregation().getBucketNum(), equalTo(5));
assertThat(metrics.getAggregation().getTimeWindowSeconds(), equalTo(120));
}
-}
\ No newline at end of file
+}
diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java
index 832c91f0c4..8f63565b21 100644
--- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java
+++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java
@@ -33,6 +33,7 @@ import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.nested.AggregationConfig;
import org.apache.dubbo.config.nested.PrometheusConfig;
+import org.apache.dubbo.config.nested.HistogramConfig;
import org.apache.dubbo.config.spring.Constants;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.ServiceBean;
@@ -265,6 +266,10 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser {
AggregationConfig aggregation = new AggregationConfig();
assignProperties(aggregation, child, parserContext);
beanDefinition.getPropertyValues().addPropertyValue("aggregation", aggregation);
+ }else if("histogram".equals(child.getNodeName()) || "histogram".equals(child.getLocalName())){
+ HistogramConfig histogram = new HistogramConfig();
+ assignProperties(histogram, child, parserContext);
+ beanDefinition.getPropertyValues().addPropertyValue("histogram", histogram);
} else if ("prometheus-exporter".equals(child.getNodeName()) || "prometheus-exporter".equals(child.getLocalName())) {
if (prometheus == null) {
prometheus = new PrometheusConfig();
diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd
index d801ffefc3..e1f272f402 100644
--- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd
+++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd
@@ -1044,6 +1044,7 @@
+
@@ -1155,6 +1156,14 @@
+
+
+
+
+
+
+
+
@@ -2045,4 +2054,10 @@
+
+
+
+
+
+
diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootConfigPropsTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootConfigPropsTest.java
index 9ce1a7f5aa..2eaa56b828 100644
--- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootConfigPropsTest.java
+++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootConfigPropsTest.java
@@ -64,6 +64,7 @@ import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMET
"dubbo.metrics.aggregation.enabled=true",
"dubbo.metrics.aggregation.bucket-num=5",
"dubbo.metrics.aggregation.time-window-seconds=120",
+ "dubbo.metrics.histogram.enabled=true",
"dubbo.monitor.address=zookeeper://127.0.0.1:32770",
"dubbo.Config-center.address=${zookeeper.connection.address.1}",
"dubbo.config-Center.group=group1",
@@ -116,6 +117,7 @@ class SpringBootConfigPropsTest {
Assertions.assertEquals(5, metricsConfig.getAggregation().getBucketNum());
Assertions.assertEquals(120, metricsConfig.getAggregation().getTimeWindowSeconds());
Assertions.assertTrue(metricsConfig.getAggregation().getEnabled());
+ Assertions.assertTrue(metricsConfig.getHistogram().getEnabled());
List defaultProtocols = configManager.getDefaultProtocols();
Assertions.assertEquals(1, defaultProtocols.size());
@@ -153,4 +155,4 @@ class SpringBootConfigPropsTest {
}
-}
\ No newline at end of file
+}
diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootMultipleConfigPropsTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootMultipleConfigPropsTest.java
index 9bb31c119c..482cd054cd 100644
--- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootMultipleConfigPropsTest.java
+++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootMultipleConfigPropsTest.java
@@ -63,6 +63,7 @@ import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMET
"dubbo.metricses.my-metrics.aggregation.enabled=true",
"dubbo.metricses.my-metrics.aggregation.bucket-num=5",
"dubbo.metricses.my-metrics.aggregation.time-window-seconds=120",
+ "dubbo.metricses.my-metrics.histogram.enabled=true",
"dubbo.monitors.my-monitor.address=zookeeper://127.0.0.1:32770",
"dubbo.config-centers.my-configcenter.address=${zookeeper.connection.address.1}",
"dubbo.config-centers.my-configcenter.group=group1",
@@ -116,6 +117,7 @@ class SpringBootMultipleConfigPropsTest {
Assertions.assertEquals(5, metricsConfig.getAggregation().getBucketNum());
Assertions.assertEquals(120, metricsConfig.getAggregation().getTimeWindowSeconds());
Assertions.assertTrue(metricsConfig.getAggregation().getEnabled());
+ Assertions.assertTrue(metricsConfig.getHistogram().getEnabled());
List defaultProtocols = configManager.getDefaultProtocols();
Assertions.assertEquals(1, defaultProtocols.size());
@@ -154,4 +156,4 @@ class SpringBootMultipleConfigPropsTest {
}
-}
\ No newline at end of file
+}
diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/metrics/SpringBootConfigMetricsTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/metrics/SpringBootConfigMetricsTest.java
index 3b54f09bd0..089e691af2 100644
--- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/metrics/SpringBootConfigMetricsTest.java
+++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/metrics/SpringBootConfigMetricsTest.java
@@ -50,6 +50,7 @@ import org.springframework.context.annotation.Configuration;
"dubbo.metrics.aggregation.enabled=true",
"dubbo.metrics.aggregation.bucket-num=5",
"dubbo.metrics.aggregation.time-window-seconds=120",
+ "dubbo.metrics.histogram.enabled=true",
"dubbo.metadata-report.address=${zookeeper.connection.address.2}"
},
classes = {
@@ -90,6 +91,7 @@ public class SpringBootConfigMetricsTest {
Assertions.assertEquals(5, metricsConfig.getAggregation().getBucketNum());
Assertions.assertEquals(120, metricsConfig.getAggregation().getTimeWindowSeconds());
Assertions.assertTrue(metricsConfig.getAggregation().getEnabled());
+ Assertions.assertTrue(metricsConfig.getHistogram().getEnabled());
}
}
diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
index 6065ee5289..adc558ef9c 100644
--- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
@@ -61,6 +61,12 @@ public enum MetricsKey {
REGISTER_METRIC_REQUESTS("dubbo.registry.register.requests.total", "Total Register Requests"),
REGISTER_METRIC_REQUESTS_SUCCEED("dubbo.registry.register.requests.succeed.total", "Succeed Register Requests"),
REGISTER_METRIC_REQUESTS_FAILED("dubbo.registry.register.requests.failed.total", "Failed Register Requests"),
+ METRIC_RT_HISTOGRAM("dubbo.%s.rt.milliseconds.histogram", "Response Time Histogram"),
+
+
+ GENERIC_METRIC_REQUESTS("dubbo.%s.requests.total", "Total %s Requests"),
+ GENERIC_METRIC_REQUESTS_SUCCEED("dubbo.%s.requests.succeed.total", "Succeed %s Requests"),
+ GENERIC_METRIC_REQUESTS_FAILED("dubbo.%s.requests.failed.total", "Failed %s Requests"),
// subscribe metrics key
SUBSCRIBE_METRIC_NUM("dubbo.registry.subscribe.num.total", "Total Subscribe Num"),
diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DubboMetrics.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DubboMetrics.java
index 00351aedcc..ab38c121a5 100644
--- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DubboMetrics.java
+++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DubboMetrics.java
@@ -19,7 +19,6 @@ package org.apache.dubbo.metrics;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
-import org.apache.dubbo.metrics.report.AbstractMetricsReporter;
public class DubboMetrics implements MeterBinder {
@@ -29,7 +28,7 @@ public class DubboMetrics implements MeterBinder {
@Override
public void bindTo(MeterRegistry registry) {
globalRegistry = registry;
- CompositeMeterRegistry compositeRegistry = AbstractMetricsReporter.compositeRegistry;
+ CompositeMeterRegistry compositeRegistry = MetricsGlobalRegistry.getCompositeRegistry();
if (compositeRegistry != null) {
compositeRegistry.add(registry);
}
diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java
new file mode 100644
index 0000000000..cc6c824c18
--- /dev/null
+++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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 io.micrometer.core.instrument.composite.CompositeMeterRegistry;
+
+public class MetricsGlobalRegistry {
+
+ private static final CompositeMeterRegistry compositeRegistry = new CompositeMeterRegistry();
+
+ public static CompositeMeterRegistry getCompositeRegistry() {
+ return compositeRegistry;
+ }
+}
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
new file mode 100644
index 0000000000..9fc57059ac
--- /dev/null
+++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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 io.micrometer.core.instrument.Timer;
+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.MetricsGlobalRegistry;
+import org.apache.dubbo.metrics.event.MetricsEvent;
+import org.apache.dubbo.metrics.event.RTEvent;
+import org.apache.dubbo.metrics.listener.MetricsListener;
+import org.apache.dubbo.metrics.model.MethodMetric;
+import org.apache.dubbo.metrics.model.MetricsKey;
+import org.apache.dubbo.metrics.register.HistogramMetricRegister;
+import org.apache.dubbo.metrics.sample.HistogramMetricSample;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.dubbo.metrics.model.MetricsCategory.RT;
+
+public class HistogramMetricsCollector implements MetricsListener {
+
+ private final ConcurrentHashMap rt = new ConcurrentHashMap<>();
+ private HistogramMetricRegister metricRegister;
+ private final ApplicationModel applicationModel;
+
+ private static final Integer[] DEFAULT_BUCKETS_MS = new Integer[]{100, 300, 500, 1000, 3000, 5000, 10000};
+
+ public HistogramMetricsCollector(ApplicationModel applicationModel) {
+ this.applicationModel = applicationModel;
+
+ ConfigManager configManager = applicationModel.getApplicationConfigManager();
+ MetricsConfig config = configManager.getMetrics().orElse(null);
+ if (config != null && config.getHistogram() != null && Boolean.TRUE.equals(config.getHistogram().getEnabled())) {
+ registerListener();
+
+ HistogramConfig histogram = config.getHistogram();
+ if (!Boolean.TRUE.equals(histogram.getEnabledPercentiles()) && histogram.getBucketsMs() == null) {
+ histogram.setBucketsMs(DEFAULT_BUCKETS_MS);
+ }
+
+ metricRegister = new HistogramMetricRegister(MetricsGlobalRegistry.getCompositeRegistry(), histogram);
+ }
+ }
+
+ private void registerListener() {
+ applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class).addListener(this);
+ }
+
+ @Override
+ public void onEvent(MetricsEvent event) {
+ if (event instanceof RTEvent) {
+ onRTEvent((RTEvent) event);
+ }
+ }
+
+ private void onRTEvent(RTEvent event) {
+ if (metricRegister != null) {
+ MethodMetric metric = (MethodMetric) event.getSource();
+ Long responseTime = event.getRt();
+
+ HistogramMetricSample sample = new HistogramMetricSample(MetricsKey.METRIC_RT_HISTOGRAM.getNameByType(metric.getSide()),
+ MetricsKey.METRIC_RT_HISTOGRAM.getDescription(), metric.getTags(), RT);
+
+ Timer timer = ConcurrentHashMapUtils.computeIfAbsent(rt, metric, k -> metricRegister.register(sample));
+ timer.record(responseTime, TimeUnit.MILLISECONDS);
+ }
+ }
+}
diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/HistogramMetricRegister.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/HistogramMetricRegister.java
new file mode 100644
index 0000000000..04a173cdee
--- /dev/null
+++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/HistogramMetricRegister.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.register;
+
+import io.micrometer.core.instrument.MeterRegistry;
+import io.micrometer.core.instrument.Tag;
+import io.micrometer.core.instrument.Timer;
+import org.apache.dubbo.config.nested.HistogramConfig;
+import org.apache.dubbo.metrics.sample.HistogramMetricSample;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class HistogramMetricRegister implements MetricRegister {
+
+ private final MeterRegistry registry;
+ private final HistogramConfig config;
+
+ public HistogramMetricRegister(MeterRegistry registry, HistogramConfig config) {
+ this.registry = registry;
+ this.config = config;
+ }
+
+ @Override
+ public Timer register(HistogramMetricSample sample) {
+ List tags = new ArrayList<>();
+ sample.getTags().forEach((k, v) -> {
+ if (v == null) {
+ v = "";
+ }
+
+ tags.add(Tag.of(k, v));
+ });
+
+ Timer.Builder builder = Timer.builder(sample.getName()).description(sample.getDescription()).tags(tags);
+
+ if (Boolean.TRUE.equals(config.getEnabledPercentiles())) {
+ builder.publishPercentileHistogram(true);
+ }
+
+ if (config.getPercentiles() != null) {
+ builder.publishPercentiles(config.getPercentiles());
+ }
+
+ if (config.getBucketsMs() != null) {
+ builder.serviceLevelObjectives(Arrays.stream(config.getBucketsMs())
+ .map(Duration::ofMillis).toArray(Duration[]::new));
+ }
+
+ if (config.getMinExpectedMs() != null) {
+ builder.minimumExpectedValue(Duration.ofMillis(config.getMinExpectedMs()));
+ }
+
+ if (config.getMaxExpectedMs() != null) {
+ builder.maximumExpectedValue(Duration.ofMillis(config.getMaxExpectedMs()));
+ }
+
+ if (config.getDistributionStatisticExpiryMin() != null) {
+ builder.distributionStatisticExpiry(Duration.ofMinutes(config.getDistributionStatisticExpiryMin()));
+ }
+
+ return builder.register(registry);
+ }
+}
diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/MetricRegister.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/MetricRegister.java
new file mode 100644
index 0000000000..fbf6c5eeb0
--- /dev/null
+++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/MetricRegister.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.metrics.register;
+
+import io.micrometer.core.instrument.Meter;
+import org.apache.dubbo.metrics.model.sample.MetricSample;
+
+public interface MetricRegister {
+
+ M register(S sample);
+
+}
diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporter.java
index 4a0558b387..78215624e9 100644
--- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporter.java
+++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporter.java
@@ -24,9 +24,11 @@ import org.apache.dubbo.common.constants.MetricsConstants;
import org.apache.dubbo.common.lang.ShutdownHookCallbacks;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.metrics.MetricsGlobalRegistry;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.metrics.collector.AggregateMetricsCollector;
import org.apache.dubbo.metrics.collector.MetricsCollector;
+import org.apache.dubbo.metrics.collector.HistogramMetricsCollector;
import org.apache.dubbo.metrics.model.sample.GaugeMetricSample;
import org.apache.dubbo.metrics.model.sample.MetricSample;
import org.apache.dubbo.rpc.model.ApplicationModel;
@@ -68,7 +70,7 @@ public abstract class AbstractMetricsReporter implements MetricsReporter {
protected final List collectors = new ArrayList<>();
// Avoid instances being gc due to weak references
protected final List instanceHolder = new ArrayList<>();
- public static final CompositeMeterRegistry compositeRegistry = new CompositeMeterRegistry();
+ protected final CompositeMeterRegistry compositeRegistry;
private final ApplicationModel applicationModel;
@@ -80,6 +82,7 @@ public abstract class AbstractMetricsReporter implements MetricsReporter {
protected AbstractMetricsReporter(URL url, ApplicationModel applicationModel) {
this.url = url;
this.applicationModel = applicationModel;
+ this.compositeRegistry = MetricsGlobalRegistry.getCompositeRegistry();
}
@Override
@@ -134,6 +137,7 @@ public abstract class AbstractMetricsReporter implements MetricsReporter {
private void initCollectors() {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.getOrRegisterBean(AggregateMetricsCollector.class);
+ beanFactory.getOrRegisterBean(HistogramMetricsCollector.class);
List otherCollectors = beanFactory.getBeansOfType(MetricsCollector.class);
collectors.addAll(otherCollectors);
}
diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/sample/HistogramMetricSample.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/sample/HistogramMetricSample.java
new file mode 100644
index 0000000000..8f8149c1b5
--- /dev/null
+++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/sample/HistogramMetricSample.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.sample;
+
+import org.apache.dubbo.metrics.model.MetricsCategory;
+import org.apache.dubbo.metrics.model.sample.MetricSample;
+
+import java.util.Map;
+
+public class HistogramMetricSample extends MetricSample {
+
+ public HistogramMetricSample(String name, String description, Map tags, MetricsCategory category) {
+ super(name, description, tags, Type.TIMER, category);
+ }
+
+ public HistogramMetricSample(String name, String description, Map tags, Type type, MetricsCategory category, String baseUnit) {
+ super(name, description, tags, type, category, baseUnit);
+ }
+}
From e7d3cf8ce639e47b90b70ac73a49865d9a91f0ef Mon Sep 17 00:00:00 2001
From: wxbty <38374721+wxbty@users.noreply.github.com>
Date: Mon, 27 Mar 2023 09:50:18 +0800
Subject: [PATCH 018/122] dubbo-starter import metrics dep (#11921)
* add stater
* fix starter path
* opt obserable dep
---------
Co-authored-by: x-shadow-man <1494445739@qq.com>
---
.../dubbo-spring-boot-observability-starter/pom.xml | 12 +++++-------
1 file changed, 5 insertions(+), 7 deletions(-)
diff --git a/dubbo-spring-boot/dubbo-spring-boot-observability-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-observability-starter/pom.xml
index 7e4b5978f5..2237b229ba 100644
--- a/dubbo-spring-boot/dubbo-spring-boot-observability-starter/pom.xml
+++ b/dubbo-spring-boot/dubbo-spring-boot-observability-starter/pom.xml
@@ -65,6 +65,10 @@
io.micrometermicrometer-core
+
+ io.micrometer
+ micrometer-registry-prometheus
+ org.springframework.bootspring-boot-autoconfigure
@@ -75,12 +79,6 @@
spring-boot-configuration-processortrue
-
- org.apache.dubbo
- dubbo-common
- ${project.version}
- true
- io.micrometermicrometer-tracing-bridge-otel
@@ -93,7 +91,7 @@
org.apache.dubbo
- dubbo-metrics-default
+ dubbo-spring-boot-starter${project.version}
From 0e57e806a4994988f908efb01ecccf7dadfd85dc Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 27 Mar 2023 09:50:53 +0800
Subject: [PATCH 019/122] Bump spring-boot-maven-plugin from 2.7.9 to 2.7.10
(#11908)
Bumps [spring-boot-maven-plugin](https://github.com/spring-projects/spring-boot) from 2.7.9 to 2.7.10.
- [Release notes](https://github.com/spring-projects/spring-boot/releases)
- [Commits](https://github.com/spring-projects/spring-boot/compare/v2.7.9...v2.7.10)
---
updated-dependencies:
- dependency-name: org.springframework.boot:spring-boot-maven-plugin
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
dubbo-demo/dubbo-demo-annotation/pom.xml | 2 +-
dubbo-demo/dubbo-demo-api/pom.xml | 2 +-
dubbo-demo/dubbo-demo-spring-boot/pom.xml | 2 +-
dubbo-demo/dubbo-demo-xml/pom.xml | 2 +-
4 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/dubbo-demo/dubbo-demo-annotation/pom.xml b/dubbo-demo/dubbo-demo-annotation/pom.xml
index b3991acd71..b84ceb28f7 100644
--- a/dubbo-demo/dubbo-demo-annotation/pom.xml
+++ b/dubbo-demo/dubbo-demo-annotation/pom.xml
@@ -30,7 +30,7 @@
true
- 2.7.9
+ 2.7.10
diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml
index a4957977fe..c68afe43a4 100644
--- a/dubbo-demo/dubbo-demo-api/pom.xml
+++ b/dubbo-demo/dubbo-demo-api/pom.xml
@@ -36,7 +36,7 @@
true
- 2.7.9
+ 2.7.10dubbo-demo-api
diff --git a/dubbo-demo/dubbo-demo-spring-boot/pom.xml b/dubbo-demo/dubbo-demo-spring-boot/pom.xml
index 4ac5160226..c4340c654d 100644
--- a/dubbo-demo/dubbo-demo-spring-boot/pom.xml
+++ b/dubbo-demo/dubbo-demo-spring-boot/pom.xml
@@ -37,7 +37,7 @@
8true2.7.9
- 2.7.9
+ 2.7.101.10.5
diff --git a/dubbo-demo/dubbo-demo-xml/pom.xml b/dubbo-demo/dubbo-demo-xml/pom.xml
index b5b32d519c..6e4c678b2e 100644
--- a/dubbo-demo/dubbo-demo-xml/pom.xml
+++ b/dubbo-demo/dubbo-demo-xml/pom.xml
@@ -32,7 +32,7 @@
true
- 2.7.9
+ 2.7.10
From 28440f8dc5a2bb06156af775afd391f447b71481 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 27 Mar 2023 09:51:03 +0800
Subject: [PATCH 020/122] Bump commons-compress from 1.22 to 1.23.0 (#11907)
Bumps commons-compress from 1.22 to 1.23.0.
---
updated-dependencies:
- dependency-name: org.apache.commons:commons-compress
dependency-type: direct:production
update-type: version-update:semver-minor
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
dubbo-dependencies-bom/pom.xml | 2 +-
dubbo-test/dubbo-test-check/pom.xml | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml
index 77b590f7d8..935e5f7573 100644
--- a/dubbo-dependencies-bom/pom.xml
+++ b/dubbo-dependencies-bom/pom.xml
@@ -189,7 +189,7 @@
6.1.262.01.1.0
- 1.22
+ 1.23.03.2.0-beta.7-SNAPSHOT
diff --git a/dubbo-test/dubbo-test-check/pom.xml b/dubbo-test/dubbo-test-check/pom.xml
index 5b25342305..f3813644b0 100644
--- a/dubbo-test/dubbo-test-check/pom.xml
+++ b/dubbo-test/dubbo-test-check/pom.xml
@@ -35,7 +35,7 @@
4.2.03.4.144.2.0
- 1.22
+ 1.23.01.6.21.32.12.1
From a0524215e532e5b0a32638b300c76c34b253c5b1 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 27 Mar 2023 09:51:15 +0800
Subject: [PATCH 021/122] Bump spring-boot-starter-test from 2.7.9 to 2.7.10
(#11906)
Bumps [spring-boot-starter-test](https://github.com/spring-projects/spring-boot) from 2.7.9 to 2.7.10.
- [Release notes](https://github.com/spring-projects/spring-boot/releases)
- [Commits](https://github.com/spring-projects/spring-boot/compare/v2.7.9...v2.7.10)
---
updated-dependencies:
- dependency-name: org.springframework.boot:spring-boot-starter-test
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
dubbo-config/dubbo-config-spring/pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml
index e7264d158d..a1d6cb20d7 100644
--- a/dubbo-config/dubbo-config-spring/pom.xml
+++ b/dubbo-config/dubbo-config-spring/pom.xml
@@ -27,7 +27,7 @@
The spring config module of dubbo projectfalse
- 2.7.9
+ 2.7.10
From 7bf867eff50eaff6478e57741b0fdbdbef654151 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 27 Mar 2023 09:51:24 +0800
Subject: [PATCH 022/122] Bump spring-boot.version from 2.7.9 to 2.7.10
(#11905)
Bumps `spring-boot.version` from 2.7.9 to 2.7.10.
Updates `spring-boot-starter` from 2.7.9 to 2.7.10
- [Release notes](https://github.com/spring-projects/spring-boot/releases)
- [Commits](https://github.com/spring-projects/spring-boot/compare/v2.7.9...v2.7.10)
Updates `spring-boot-autoconfigure` from 2.7.9 to 2.7.10
- [Release notes](https://github.com/spring-projects/spring-boot/releases)
- [Commits](https://github.com/spring-projects/spring-boot/compare/v2.7.9...v2.7.10)
Updates `spring-boot-starter-logging` from 2.7.9 to 2.7.10
- [Release notes](https://github.com/spring-projects/spring-boot/releases)
- [Commits](https://github.com/spring-projects/spring-boot/compare/v2.7.9...v2.7.10)
---
updated-dependencies:
- dependency-name: org.springframework.boot:spring-boot-starter
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: org.springframework.boot:spring-boot-autoconfigure
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: org.springframework.boot:spring-boot-starter-logging
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
.../dubbo-demo-spring-boot-consumer/pom.xml | 2 +-
.../dubbo-demo-spring-boot-provider/pom.xml | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/pom.xml b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/pom.xml
index 90616e8f9d..57bef1d50b 100644
--- a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/pom.xml
+++ b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/pom.xml
@@ -31,7 +31,7 @@
881.7.33
- 2.7.9
+ 2.7.10true
diff --git a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/pom.xml b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/pom.xml
index da3de4b5e7..bd13f1a633 100644
--- a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/pom.xml
+++ b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/pom.xml
@@ -31,7 +31,7 @@
881.7.33
- 2.7.9
+ 2.7.10true
From 5d21a06e97f031b76bc74e38ee330a2bb53e1cd5 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 27 Mar 2023 10:03:04 +0800
Subject: [PATCH 023/122] Bump spring-boot-dependencies from 2.7.9 to 2.7.10
(#11904)
Bumps [spring-boot-dependencies](https://github.com/spring-projects/spring-boot) from 2.7.9 to 2.7.10.
- [Release notes](https://github.com/spring-projects/spring-boot/releases)
- [Commits](https://github.com/spring-projects/spring-boot/compare/v2.7.9...v2.7.10)
---
updated-dependencies:
- dependency-name: org.springframework.boot:spring-boot-dependencies
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
dubbo-demo/dubbo-demo-spring-boot/pom.xml | 2 +-
dubbo-spring-boot/pom.xml | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/dubbo-demo/dubbo-demo-spring-boot/pom.xml b/dubbo-demo/dubbo-demo-spring-boot/pom.xml
index c4340c654d..c59df3139b 100644
--- a/dubbo-demo/dubbo-demo-spring-boot/pom.xml
+++ b/dubbo-demo/dubbo-demo-spring-boot/pom.xml
@@ -36,7 +36,7 @@
88true
- 2.7.9
+ 2.7.102.7.101.10.5
diff --git a/dubbo-spring-boot/pom.xml b/dubbo-spring-boot/pom.xml
index 8eebf37be6..b8d192df77 100644
--- a/dubbo-spring-boot/pom.xml
+++ b/dubbo-spring-boot/pom.xml
@@ -40,7 +40,7 @@
- 2.7.9
+ 2.7.10${revision}2.20.0
From 35751cbfae8e6543f312bd3244448ed1d4df9eb4 Mon Sep 17 00:00:00 2001
From: Mengyang Tang
Date: Mon, 27 Mar 2023 10:04:14 +0800
Subject: [PATCH 024/122] Remove logic to simplify ConstraintViolationException
to ValidationException. (#11883)
---
.../support/jvalidation/JValidator.java | 70 +++++++++----------
.../support/jvalidation/JValidatorNew.java | 70 +++++++++----------
2 files changed, 64 insertions(+), 76 deletions(-)
diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java
index f5c06a7bba..7051ab2176 100644
--- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java
+++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java
@@ -51,7 +51,6 @@ import javax.validation.Constraint;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
-import javax.validation.ValidationException;
import javax.validation.ValidatorFactory;
import javax.validation.groups.Default;
import java.lang.annotation.Annotation;
@@ -126,8 +125,8 @@ public class JValidator implements Validator {
/**
* try to generate methodParameterClass.
*
- * @param clazz interface class
- * @param method invoke method
+ * @param clazz interface class
+ * @param method invoke method
* @param parameterClassName generated parameterClassName
* @return Class> generated methodParameterClass
* @throws Exception
@@ -188,9 +187,9 @@ public class JValidator implements Validator {
private static String generateMethodParameterClassName(Class> clazz, Method method) {
StringBuilder builder = new StringBuilder().append(clazz.getName())
- .append('_')
- .append(toUpperMethoName(method.getName()))
- .append("Parameter");
+ .append('_')
+ .append(toUpperMethoName(method.getName()))
+ .append("Parameter");
Class>[] parameterTypes = method.getParameterTypes();
for (Class> parameterType : parameterTypes) {
@@ -259,42 +258,37 @@ public class JValidator implements Validator {
@Override
public void validate(String methodName, Class>[] parameterTypes, Object[] arguments) throws Exception {
- try {
- List> groups = new ArrayList<>();
- Class> methodClass = methodClass(methodName);
- if (methodClass != null) {
- groups.add(methodClass);
- }
- Set> violations = new HashSet<>();
- Method method = clazz.getMethod(methodName, parameterTypes);
- Class>[] methodClasses;
- if (method.isAnnotationPresent(MethodValidated.class)){
- methodClasses = method.getAnnotation(MethodValidated.class).value();
- groups.addAll(Arrays.asList(methodClasses));
- }
- // add into default group
- groups.add(0, Default.class);
- groups.add(1, clazz);
+ List> groups = new ArrayList<>();
+ Class> methodClass = methodClass(methodName);
+ if (methodClass != null) {
+ groups.add(methodClass);
+ }
+ Set> violations = new HashSet<>();
+ Method method = clazz.getMethod(methodName, parameterTypes);
+ Class>[] methodClasses;
+ if (method.isAnnotationPresent(MethodValidated.class)) {
+ methodClasses = method.getAnnotation(MethodValidated.class).value();
+ groups.addAll(Arrays.asList(methodClasses));
+ }
+ // add into default group
+ groups.add(0, Default.class);
+ groups.add(1, clazz);
- // convert list to array
- Class>[] classgroups = groups.toArray(new Class[groups.size()]);
+ // convert list to array
+ Class>[] classgroups = groups.toArray(new Class[groups.size()]);
- Object parameterBean = getMethodParameterBean(clazz, method, arguments);
- if (parameterBean != null) {
- violations.addAll(validator.validate(parameterBean, classgroups ));
- }
+ Object parameterBean = getMethodParameterBean(clazz, method, arguments);
+ if (parameterBean != null) {
+ violations.addAll(validator.validate(parameterBean, classgroups));
+ }
- for (Object arg : arguments) {
- validate(violations, arg, classgroups);
- }
+ for (Object arg : arguments) {
+ validate(violations, arg, classgroups);
+ }
- if (!violations.isEmpty()) {
- logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations);
- throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
- }
- } catch (ValidationException e) {
- // only use exception's message to avoid potential serialization issue
- throw new ValidationException(e.getMessage());
+ if (!violations.isEmpty()) {
+ logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations);
+ throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
}
}
diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java
index c52d1a85c1..fca479c76f 100644
--- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java
+++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java
@@ -28,7 +28,6 @@ import jakarta.validation.Constraint;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validation;
-import jakarta.validation.ValidationException;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.groups.Default;
import javassist.ClassPool;
@@ -126,8 +125,8 @@ public class JValidatorNew implements Validator {
/**
* try to generate methodParameterClass.
*
- * @param clazz interface class
- * @param method invoke method
+ * @param clazz interface class
+ * @param method invoke method
* @param parameterClassName generated parameterClassName
* @return Class> generated methodParameterClass
* @throws Exception
@@ -188,9 +187,9 @@ public class JValidatorNew implements Validator {
private static String generateMethodParameterClassName(Class> clazz, Method method) {
StringBuilder builder = new StringBuilder().append(clazz.getName())
- .append('_')
- .append(toUpperMethoName(method.getName()))
- .append("Parameter");
+ .append('_')
+ .append(toUpperMethoName(method.getName()))
+ .append("Parameter");
Class>[] parameterTypes = method.getParameterTypes();
for (Class> parameterType : parameterTypes) {
@@ -259,42 +258,37 @@ public class JValidatorNew implements Validator {
@Override
public void validate(String methodName, Class>[] parameterTypes, Object[] arguments) throws Exception {
- try {
- List> groups = new ArrayList<>();
- Class> methodClass = methodClass(methodName);
- if (methodClass != null) {
- groups.add(methodClass);
- }
- Set> violations = new HashSet<>();
- Method method = clazz.getMethod(methodName, parameterTypes);
- Class>[] methodClasses;
- if (method.isAnnotationPresent(MethodValidated.class)){
- methodClasses = method.getAnnotation(MethodValidated.class).value();
- groups.addAll(Arrays.asList(methodClasses));
- }
- // add into default group
- groups.add(0, Default.class);
- groups.add(1, clazz);
+ List> groups = new ArrayList<>();
+ Class> methodClass = methodClass(methodName);
+ if (methodClass != null) {
+ groups.add(methodClass);
+ }
+ Set> violations = new HashSet<>();
+ Method method = clazz.getMethod(methodName, parameterTypes);
+ Class>[] methodClasses;
+ if (method.isAnnotationPresent(MethodValidated.class)) {
+ methodClasses = method.getAnnotation(MethodValidated.class).value();
+ groups.addAll(Arrays.asList(methodClasses));
+ }
+ // add into default group
+ groups.add(0, Default.class);
+ groups.add(1, clazz);
- // convert list to array
- Class>[] classgroups = groups.toArray(new Class[groups.size()]);
+ // convert list to array
+ Class>[] classgroups = groups.toArray(new Class[groups.size()]);
- Object parameterBean = getMethodParameterBean(clazz, method, arguments);
- if (parameterBean != null) {
- violations.addAll(validator.validate(parameterBean, classgroups ));
- }
+ Object parameterBean = getMethodParameterBean(clazz, method, arguments);
+ if (parameterBean != null) {
+ violations.addAll(validator.validate(parameterBean, classgroups));
+ }
- for (Object arg : arguments) {
- validate(violations, arg, classgroups);
- }
+ for (Object arg : arguments) {
+ validate(violations, arg, classgroups);
+ }
- if (!violations.isEmpty()) {
- logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations);
- throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
- }
- } catch (ValidationException e) {
- // only use exception's message to avoid potential serialization issue
- throw new ValidationException(e.getMessage());
+ if (!violations.isEmpty()) {
+ logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations);
+ throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
}
}
From 58d97e5b73d5f9f4353dc26afaf1e50d0ce22981 Mon Sep 17 00:00:00 2001
From: huazhongming
Date: Mon, 27 Mar 2023 12:23:53 +0800
Subject: [PATCH 025/122] fix native ci for scheduled (#11932)
Signed-off-by: crazyhzm
---
.github/workflows/build-and-test-scheduled-3.2.yml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/.github/workflows/build-and-test-scheduled-3.2.yml b/.github/workflows/build-and-test-scheduled-3.2.yml
index b133e06502..1b48ecfc9e 100644
--- a/.github/workflows/build-and-test-scheduled-3.2.yml
+++ b/.github/workflows/build-and-test-scheduled-3.2.yml
@@ -380,7 +380,7 @@ jobs:
run: |
cd ${{ github.workspace }}/dubbo/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider
${{ github.workspace }}/dubbo/mvnw --batch-mode --no-snapshot-updates -e --no-transfer-progress --fail-fast -T 2C clean package -P native -Dmaven.test.skip=true
- nohup ./target/demo-native-provider &
+ nohup ./target/dubbo-demo-native-provider &
cd ${{ github.workspace }}/dubbo/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer
${{ github.workspace }}/dubbo/mvnw --batch-mode --no-snapshot-updates -e --no-transfer-progress --fail-fast -T 2C clean package -P native -Dmaven.test.skip=true
- ./target/demo-native-consumer
+ ./target/dubbo-demo-native-consumer
From 26e59adea98ab61a9dca294f3ba33d6f503a3c70 Mon Sep 17 00:00:00 2001
From: huazhongming
Date: Mon, 27 Mar 2023 12:24:24 +0800
Subject: [PATCH 026/122] fix native ci (#11933)
Signed-off-by: crazyhzm
---
.github/workflows/build-and-test-scheduled-3.1.yml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/.github/workflows/build-and-test-scheduled-3.1.yml b/.github/workflows/build-and-test-scheduled-3.1.yml
index 7b1d67449f..8d56ddc30b 100644
--- a/.github/workflows/build-and-test-scheduled-3.1.yml
+++ b/.github/workflows/build-and-test-scheduled-3.1.yml
@@ -396,7 +396,7 @@ jobs:
run: |
cd ${{ github.workspace }}/dubbo/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider
${{ github.workspace }}/dubbo/mvnw --batch-mode --no-snapshot-updates -e --no-transfer-progress --fail-fast -T 2C clean package -P native -Dmaven.test.skip=true native:compile
- nohup ./target/dubbo-demo-native-provider &
+ nohup ./target/demo-native-provider &
cd ${{ github.workspace }}/dubbo/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer
${{ github.workspace }}/dubbo/mvnw --batch-mode --no-snapshot-updates -e --no-transfer-progress --fail-fast -T 2C clean package -P native -Dmaven.test.skip=true native:compile
- ./target/dubbo-demo-native-consumer
+ ./target/demo-native-consumer
From 5a2114d1406882c1d2859bcc692fd22190a957e0 Mon Sep 17 00:00:00 2001
From: Albumen Kevin
Date: Mon, 27 Mar 2023 17:22:10 +0800
Subject: [PATCH 027/122] Fix if isolated service not implemented (#11938)
* Fix if isolated service not implemented
* Add uts
* Fix license
---
...efaultIsolationExecutorSupportFactory.java | 26 ++++++++++++++
.../IsolationExecutorSupportFactory.java | 8 ++---
...c.executor.IsolationExecutorSupportFactory | 1 +
.../IsolationExecutorSupportFactoryTest.java | 34 +++++++++++++++++++
.../rpc/executor/Mock1ExecutorSupport.java | 26 ++++++++++++++
.../Mock1IsolationExecutorSupportFactory.java | 26 ++++++++++++++
.../rpc/executor/Mock2ExecutorSupport.java | 26 ++++++++++++++
.../Mock2IsolationExecutorSupportFactory.java | 26 ++++++++++++++
...c.executor.IsolationExecutorSupportFactory | 2 ++
9 files changed, 169 insertions(+), 6 deletions(-)
create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultIsolationExecutorSupportFactory.java
create mode 100644 dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory
create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactoryTest.java
create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock1ExecutorSupport.java
create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock1IsolationExecutorSupportFactory.java
create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock2ExecutorSupport.java
create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock2IsolationExecutorSupportFactory.java
create mode 100644 dubbo-common/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultIsolationExecutorSupportFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultIsolationExecutorSupportFactory.java
new file mode 100644
index 0000000000..0cdfd26f16
--- /dev/null
+++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultIsolationExecutorSupportFactory.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.rpc.executor;
+
+import org.apache.dubbo.common.URL;
+
+public class DefaultIsolationExecutorSupportFactory implements IsolationExecutorSupportFactory {
+ @Override
+ public ExecutorSupport createIsolationExecutorSupport(URL url) {
+ return new DefaultExecutorSupport(url);
+ }
+}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactory.java
index b610e9ac93..b3f4a551d8 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactory.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactory.java
@@ -17,23 +17,19 @@
package org.apache.dubbo.rpc.executor;
import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.ApplicationModel;
-import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
-
-@SPI
+@SPI("default")
public interface IsolationExecutorSupportFactory {
- @Adaptive(PROTOCOL_KEY)
ExecutorSupport createIsolationExecutorSupport(URL url);
static ExecutorSupport getIsolationExecutorSupport(URL url) {
ApplicationModel applicationModel = url.getOrDefaultApplicationModel();
ExtensionLoader extensionLoader = applicationModel.getExtensionLoader(IsolationExecutorSupportFactory.class);
- IsolationExecutorSupportFactory factory = extensionLoader.getAdaptiveExtension();
+ IsolationExecutorSupportFactory factory = extensionLoader.getOrDefaultExtension(url.getProtocol());
return factory.createIsolationExecutorSupport(url);
}
diff --git a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory
new file mode 100644
index 0000000000..8cf24fbe2d
--- /dev/null
+++ b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory
@@ -0,0 +1 @@
+default=org.apache.dubbo.rpc.executor.DefaultIsolationExecutorSupportFactory
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactoryTest.java
new file mode 100644
index 0000000000..a0608064ed
--- /dev/null
+++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactoryTest.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.executor;
+
+import org.apache.dubbo.common.URL;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class IsolationExecutorSupportFactoryTest {
+ @Test
+ void test() {
+ Assertions.assertInstanceOf(DefaultExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("dubbo://")));
+ Assertions.assertInstanceOf(DefaultExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("empty://")));
+ Assertions.assertInstanceOf(DefaultExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("exchange://")));
+ Assertions.assertInstanceOf(Mock1ExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("mock1://")));
+ Assertions.assertInstanceOf(Mock2ExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("mock2://")));
+ Assertions.assertInstanceOf(DefaultExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("mock3://")));
+ }
+}
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock1ExecutorSupport.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock1ExecutorSupport.java
new file mode 100644
index 0000000000..7e0182dce1
--- /dev/null
+++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock1ExecutorSupport.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.rpc.executor;
+
+import java.util.concurrent.Executor;
+
+public class Mock1ExecutorSupport implements ExecutorSupport {
+ @Override
+ public Executor getExecutor(Object data) {
+ return null;
+ }
+}
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock1IsolationExecutorSupportFactory.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock1IsolationExecutorSupportFactory.java
new file mode 100644
index 0000000000..015fe5e4fb
--- /dev/null
+++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock1IsolationExecutorSupportFactory.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.rpc.executor;
+
+import org.apache.dubbo.common.URL;
+
+public class Mock1IsolationExecutorSupportFactory implements IsolationExecutorSupportFactory {
+ @Override
+ public ExecutorSupport createIsolationExecutorSupport(URL url) {
+ return new Mock1ExecutorSupport();
+ }
+}
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock2ExecutorSupport.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock2ExecutorSupport.java
new file mode 100644
index 0000000000..93e130de60
--- /dev/null
+++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock2ExecutorSupport.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.rpc.executor;
+
+import java.util.concurrent.Executor;
+
+public class Mock2ExecutorSupport implements ExecutorSupport {
+ @Override
+ public Executor getExecutor(Object data) {
+ return null;
+ }
+}
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock2IsolationExecutorSupportFactory.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock2IsolationExecutorSupportFactory.java
new file mode 100644
index 0000000000..f416813641
--- /dev/null
+++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/Mock2IsolationExecutorSupportFactory.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.rpc.executor;
+
+import org.apache.dubbo.common.URL;
+
+public class Mock2IsolationExecutorSupportFactory implements IsolationExecutorSupportFactory {
+ @Override
+ public ExecutorSupport createIsolationExecutorSupport(URL url) {
+ return new Mock2ExecutorSupport();
+ }
+}
diff --git a/dubbo-common/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory b/dubbo-common/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory
new file mode 100644
index 0000000000..e743289f83
--- /dev/null
+++ b/dubbo-common/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory
@@ -0,0 +1,2 @@
+mock1=org.apache.dubbo.rpc.executor.Mock1IsolationExecutorSupportFactory
+mock2=org.apache.dubbo.rpc.executor.Mock2IsolationExecutorSupportFactory
From 89e271408d73256c3d99b43cbe1e89cade0c7737 Mon Sep 17 00:00:00 2001
From: fan
Date: Mon, 27 Mar 2023 19:14:20 +0800
Subject: [PATCH 028/122] [ISSUE #10020] test efficiency of
MemorySafeLinkedBlockingQueue (#11841)
---
.../MemorySafeLinkedBlockingQueueTest.java | 60 ++++++++++++++++++-
1 file changed, 58 insertions(+), 2 deletions(-)
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueueTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueueTest.java
index e678cbd14b..2a2372db05 100644
--- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueueTest.java
+++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueueTest.java
@@ -17,13 +17,14 @@
package org.apache.dubbo.common.threadpool;
+import net.bytebuddy.agent.ByteBuddyAgent;
import org.apache.dubbo.common.concurrent.AbortPolicy;
import org.apache.dubbo.common.concurrent.RejectException;
-
-import net.bytebuddy.agent.ByteBuddyAgent;
+import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.instrument.Instrumentation;
+import java.util.concurrent.LinkedBlockingQueue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@@ -55,4 +56,59 @@ class MemorySafeLinkedBlockingQueueTest {
assertThrows(RejectException.class, () -> queue.offer(() -> {
}));
}
+
+ @Test
+ void testEfficiency() throws InterruptedException {
+ // if length is vert large(unit test may runs for a long time), so you may need to modify JVM param such as : -Xms=1024m -Xmx=2048m
+ // if you want to test efficiency of MemorySafeLinkedBlockingQueue, you may modify following param: length and times
+ int length = 1000, times = 1;
+
+ // LinkedBlockingQueue insert Integer: 500W * 20 times
+ long spent1 = spend(new LinkedBlockingQueue<>(), length, times);
+
+ // MemorySafeLinkedBlockingQueue insert Integer: 500W * 20 times
+ long spent2 = spend(newMemorySafeLinkedBlockingQueue(), length, times);
+ System.gc();
+
+ System.out.println(String.format("LinkedBlockingQueue spent %s millis, MemorySafeLinkedBlockingQueue spent %s millis", spent1, spent2));
+ // efficiency between LinkedBlockingQueue and MemorySafeLinkedBlockingQueue is very nearly the same
+ Assertions.assertTrue(spent1 - spent2 <= 1);
+ }
+
+ private static long spend(LinkedBlockingQueue lbq, int length, int times) throws InterruptedException {
+ // new Queue
+ if (lbq instanceof MemorySafeLinkedBlockingQueue) {
+ lbq = newMemorySafeLinkedBlockingQueue();
+ } else {
+ lbq = new LinkedBlockingQueue<>();
+ }
+
+ long total = 0L;
+ for (int i = 0; i < times; i++) {
+ long start = System.currentTimeMillis();
+ for (int j = 0; j < length; j++) {
+ lbq.offer(j);
+ }
+ long end = System.currentTimeMillis();
+ long spent = end - start;
+ total += spent;
+ }
+ long result = total / times;
+
+ // gc
+ System.gc();
+
+ return result;
+ }
+
+ private static MemorySafeLinkedBlockingQueue newMemorySafeLinkedBlockingQueue() {
+ ByteBuddyAgent.install();
+ final Instrumentation instrumentation = ByteBuddyAgent.getInstrumentation();
+ final long objectSize = instrumentation.getObjectSize((Runnable) () -> { });
+ int maxFreeMemory = (int) MemoryLimitCalculator.maxAvailable();
+ MemorySafeLinkedBlockingQueue queue = new MemorySafeLinkedBlockingQueue<>(maxFreeMemory);
+ queue.setMaxFreeMemory((int) (MemoryLimitCalculator.maxAvailable() - objectSize));
+ queue.setRejector(new AbortPolicy<>());
+ return queue;
+ }
}
From 88853e0177ab252ea49cd3bf814b79c69f2de042 Mon Sep 17 00:00:00 2001
From: icodening
Date: Tue, 28 Mar 2023 11:05:25 +0800
Subject: [PATCH 029/122] fix BatchExecutorQueue bug (#11927)
Co-authored-by: earthchen
---
.../main/java/org/apache/dubbo/common/BatchExecutorQueue.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/BatchExecutorQueue.java b/dubbo-common/src/main/java/org/apache/dubbo/common/BatchExecutorQueue.java
index 4718f21feb..c958f56508 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/BatchExecutorQueue.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/BatchExecutorQueue.java
@@ -62,7 +62,7 @@ public class BatchExecutorQueue {
boolean flushedOnce = false;
while ((item = snapshot.poll()) != null) {
if (snapshot.size() == 0) {
- i = 0;
+ flushedOnce = false;
break;
}
if (i == chunkSize) {
@@ -74,7 +74,7 @@ public class BatchExecutorQueue {
i++;
}
}
- if ((i != 0 || !flushedOnce) && item != null) {
+ if (!flushedOnce && item != null) {
flush(item);
}
} finally {
From 16c031a68c9d6a42c56e71e69ecab03b6962c290 Mon Sep 17 00:00:00 2001
From: conghuhu <56248584+conghuhu@users.noreply.github.com>
Date: Tue, 28 Mar 2023 14:10:41 +0800
Subject: [PATCH 030/122] chore: some tracing-related optimizations (#11924)
* chore: some tracing-related optimizations
* fix: fix conflict
* fix: fix observability-starter miss dubbo-common
---
.../support/ObservationSenderFilter.java | 22 ++++++++----
...ractDefaultDubboObservationConvention.java | 6 ++--
...faultDubboClientObservationConvention.java | 17 +++++----
...faultDubboServerObservationConvention.java | 6 +++-
...ava => DubboObservationDocumentation.java} | 4 ++-
.../ObservationReceiverFilter.java | 21 +++++++----
.../pom.xml | 6 ++++
.../otel/OpenTelemetryAutoConfiguration.java | 35 ++++++++++---------
8 files changed, 75 insertions(+), 42 deletions(-)
rename dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/{DubboObservation.java => DubboObservationDocumentation.java} (96%)
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ObservationSenderFilter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ObservationSenderFilter.java
index fcd8b124a0..dea6528922 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ObservationSenderFilter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ObservationSenderFilter.java
@@ -16,13 +16,11 @@
*/
package org.apache.dubbo.rpc.cluster.filter.support;
-import io.micrometer.observation.Observation;
-import io.micrometer.observation.ObservationRegistry;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metrics.observation.DefaultDubboClientObservationConvention;
import org.apache.dubbo.metrics.observation.DubboClientContext;
import org.apache.dubbo.metrics.observation.DubboClientObservationConvention;
-import org.apache.dubbo.metrics.observation.DubboObservation;
+import org.apache.dubbo.metrics.observation.DubboObservationDocumentation;
import org.apache.dubbo.rpc.BaseFilter;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
@@ -33,6 +31,9 @@ import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
+import io.micrometer.observation.Observation;
+import io.micrometer.observation.ObservationRegistry;
+
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
/**
@@ -55,15 +56,18 @@ public class ObservationSenderFilter implements ClusterFilter, BaseFilter.Listen
if (observationRegistry == null) {
return invoker.invoke(invocation);
}
- DubboClientContext senderContext = new DubboClientContext(invoker, invocation);
- Observation observation = DubboObservation.CLIENT.observation(this.clientObservationConvention, DefaultDubboClientObservationConvention.INSTANCE, () -> senderContext, observationRegistry);
+ final DubboClientContext senderContext = new DubboClientContext(invoker, invocation);
+ final Observation observation = DubboObservationDocumentation.CLIENT.observation(
+ this.clientObservationConvention,
+ DefaultDubboClientObservationConvention.getInstance(),
+ () -> senderContext, observationRegistry);
invocation.put(Observation.class, observation.start());
return observation.scoped(() -> invoker.invoke(invocation));
}
@Override
public void onResponse(Result appResponse, Invoker> invoker, Invocation invocation) {
- Observation observation = (Observation) invocation.get(Observation.class);
+ final Observation observation = getObservation(invocation);
if (observation == null) {
return;
}
@@ -72,11 +76,15 @@ public class ObservationSenderFilter implements ClusterFilter, BaseFilter.Listen
@Override
public void onError(Throwable t, Invoker> invoker, Invocation invocation) {
- Observation observation = (Observation) invocation.get(Observation.class);
+ final Observation observation = getObservation(invocation);
if (observation == null) {
return;
}
observation.error(t);
observation.stop();
}
+
+ private Observation getObservation(Invocation invocation) {
+ return (Observation) invocation.get(Observation.class);
+ }
}
diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/AbstractDefaultDubboObservationConvention.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/AbstractDefaultDubboObservationConvention.java
index 3a542fef86..8d8e963868 100644
--- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/AbstractDefaultDubboObservationConvention.java
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/AbstractDefaultDubboObservationConvention.java
@@ -25,9 +25,9 @@ import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.support.RpcUtils;
-import static org.apache.dubbo.metrics.observation.DubboObservation.LowCardinalityKeyNames.RPC_METHOD;
-import static org.apache.dubbo.metrics.observation.DubboObservation.LowCardinalityKeyNames.RPC_SERVICE;
-import static org.apache.dubbo.metrics.observation.DubboObservation.LowCardinalityKeyNames.RPC_SYSTEM;
+import static org.apache.dubbo.metrics.observation.DubboObservationDocumentation.LowCardinalityKeyNames.RPC_METHOD;
+import static org.apache.dubbo.metrics.observation.DubboObservationDocumentation.LowCardinalityKeyNames.RPC_SERVICE;
+import static org.apache.dubbo.metrics.observation.DubboObservationDocumentation.LowCardinalityKeyNames.RPC_SYSTEM;
class AbstractDefaultDubboObservationConvention {
KeyValues getLowCardinalityKeyValues(Invocation invocation) {
diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConvention.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConvention.java
index ea31a526a5..91e88da2a3 100644
--- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConvention.java
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConvention.java
@@ -16,16 +16,17 @@
*/
package org.apache.dubbo.metrics.observation;
-import java.util.List;
-
-import io.micrometer.common.KeyValues;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcContextAttachment;
-import static org.apache.dubbo.metrics.observation.DubboObservation.LowCardinalityKeyNames.NET_PEER_NAME;
-import static org.apache.dubbo.metrics.observation.DubboObservation.LowCardinalityKeyNames.NET_PEER_PORT;
+import io.micrometer.common.KeyValues;
+
+import java.util.List;
+
+import static org.apache.dubbo.metrics.observation.DubboObservationDocumentation.LowCardinalityKeyNames.NET_PEER_NAME;
+import static org.apache.dubbo.metrics.observation.DubboObservationDocumentation.LowCardinalityKeyNames.NET_PEER_PORT;
/**
* Default implementation of the {@link DubboClientObservationConvention}.
@@ -34,7 +35,11 @@ public class DefaultDubboClientObservationConvention extends AbstractDefaultDubb
/**
* Singleton instance of {@link DefaultDubboClientObservationConvention}.
*/
- public static final DubboClientObservationConvention INSTANCE = new DefaultDubboClientObservationConvention();
+ private static final DubboClientObservationConvention INSTANCE = new DefaultDubboClientObservationConvention();
+
+ public static DubboClientObservationConvention getInstance() {
+ return INSTANCE;
+ }
@Override
public String getName() {
diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConvention.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConvention.java
index efb85f515e..adcebdbdac 100644
--- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConvention.java
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConvention.java
@@ -26,7 +26,11 @@ public class DefaultDubboServerObservationConvention extends AbstractDefaultDubb
/**
* Singleton instance of {@link DefaultDubboServerObservationConvention}.
*/
- public static final DubboServerObservationConvention INSTANCE = new DefaultDubboServerObservationConvention();
+ private static final DubboServerObservationConvention INSTANCE = new DefaultDubboServerObservationConvention();
+
+ public static DubboServerObservationConvention getInstance() {
+ return INSTANCE;
+ }
@Override
public String getName() {
diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboObservation.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboObservationDocumentation.java
similarity index 96%
rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboObservation.java
rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboObservationDocumentation.java
index ff4b1575ff..855a2e01e1 100644
--- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboObservation.java
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboObservationDocumentation.java
@@ -17,6 +17,7 @@
package org.apache.dubbo.metrics.observation;
import io.micrometer.common.docs.KeyName;
+import io.micrometer.common.lang.NonNullApi;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationConvention;
import io.micrometer.observation.docs.ObservationDocumentation;
@@ -24,7 +25,7 @@ import io.micrometer.observation.docs.ObservationDocumentation;
/**
* Documentation of Dubbo observations.
*/
-public enum DubboObservation implements ObservationDocumentation {
+public enum DubboObservationDocumentation implements ObservationDocumentation {
/**
* Server side Dubbo RPC Observation.
@@ -58,6 +59,7 @@ public enum DubboObservation implements ObservationDocumentation {
};
+ @NonNullApi
enum LowCardinalityKeyNames implements KeyName {
/**
diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilter.java
index a25cc92ed8..273a336160 100644
--- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilter.java
+++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilter.java
@@ -16,9 +16,6 @@
*/
package org.apache.dubbo.metrics.observation;
-import io.micrometer.observation.Observation;
-import io.micrometer.observation.ObservationRegistry;
-
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.BaseFilter;
import org.apache.dubbo.rpc.Filter;
@@ -29,6 +26,9 @@ import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
+import io.micrometer.observation.Observation;
+import io.micrometer.observation.ObservationRegistry;
+
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
/**
@@ -51,15 +51,18 @@ public class ObservationReceiverFilter implements Filter, BaseFilter.Listener, S
if (observationRegistry == null) {
return invoker.invoke(invocation);
}
- DubboServerContext receiverContext = new DubboServerContext(invoker, invocation);
- Observation observation = DubboObservation.SERVER.observation(this.serverObservationConvention, DefaultDubboServerObservationConvention.INSTANCE, () -> receiverContext, observationRegistry);
+ final DubboServerContext receiverContext = new DubboServerContext(invoker, invocation);
+ final Observation observation = DubboObservationDocumentation.SERVER.observation(
+ this.serverObservationConvention,
+ DefaultDubboServerObservationConvention.getInstance(),
+ () -> receiverContext, observationRegistry);
invocation.put(Observation.class, observation.start());
return observation.scoped(() -> invoker.invoke(invocation));
}
@Override
public void onResponse(Result appResponse, Invoker> invoker, Invocation invocation) {
- Observation observation = (Observation) invocation.get(Observation.class);
+ final Observation observation = getObservation(invocation);
if (observation == null) {
return;
}
@@ -68,11 +71,15 @@ public class ObservationReceiverFilter implements Filter, BaseFilter.Listener, S
@Override
public void onError(Throwable t, Invoker> invoker, Invocation invocation) {
- Observation observation = (Observation) invocation.get(Observation.class);
+ final Observation observation = getObservation(invocation);
if (observation == null) {
return;
}
observation.error(t);
observation.stop();
}
+
+ private Observation getObservation(Invocation invocation) {
+ return (Observation) invocation.get(Observation.class);
+ }
}
diff --git a/dubbo-spring-boot/dubbo-spring-boot-observability-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-observability-starter/pom.xml
index 2237b229ba..346953efe7 100644
--- a/dubbo-spring-boot/dubbo-spring-boot-observability-starter/pom.xml
+++ b/dubbo-spring-boot/dubbo-spring-boot-observability-starter/pom.xml
@@ -94,6 +94,12 @@
dubbo-spring-boot-starter${project.version}
+
+ org.apache.dubbo
+ dubbo-common
+ ${project.version}
+ true
+
diff --git a/dubbo-spring-boot/dubbo-spring-boot-observability-starter/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/otel/OpenTelemetryAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-observability-starter/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/otel/OpenTelemetryAutoConfiguration.java
index c2903fa46d..a15e6955c5 100644
--- a/dubbo-spring-boot/dubbo-spring-boot-observability-starter/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/otel/OpenTelemetryAutoConfiguration.java
+++ b/dubbo-spring-boot/dubbo-spring-boot-observability-starter/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/otel/OpenTelemetryAutoConfiguration.java
@@ -16,6 +16,11 @@
*/
package org.apache.dubbo.spring.boot.observability.autoconfigure.otel;
+import org.apache.dubbo.common.Version;
+import org.apache.dubbo.spring.boot.observability.annotation.ConditionalOnDubboTracingEnable;
+import org.apache.dubbo.spring.boot.observability.autoconfigure.DubboMicrometerTracingAutoConfiguration;
+import org.apache.dubbo.spring.boot.observability.config.DubboTracingProperties;
+
import io.micrometer.tracing.SpanCustomizer;
import io.micrometer.tracing.exporter.SpanExportingPredicate;
import io.micrometer.tracing.exporter.SpanFilter;
@@ -49,10 +54,6 @@ import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import io.opentelemetry.sdk.trace.samplers.Sampler;
import io.opentelemetry.semconv.resource.attributes.ResourceAttributes;
-import org.apache.dubbo.common.Version;
-import org.apache.dubbo.spring.boot.observability.annotation.ConditionalOnDubboTracingEnable;
-import org.apache.dubbo.spring.boot.observability.autoconfigure.DubboMicrometerTracingAutoConfiguration;
-import org.apache.dubbo.spring.boot.observability.config.DubboTracingProperties;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@@ -91,7 +92,7 @@ public class OpenTelemetryAutoConfiguration {
@ConditionalOnMissingBean
OpenTelemetry openTelemetry(SdkTracerProvider sdkTracerProvider, ContextPropagators contextPropagators) {
return OpenTelemetrySdk.builder().setTracerProvider(sdkTracerProvider).setPropagators(contextPropagators)
- .build();
+ .build();
}
@Bean
@@ -100,7 +101,7 @@ public class OpenTelemetryAutoConfiguration {
Sampler sampler) {
String applicationName = environment.getProperty("spring.application.name", DEFAULT_APPLICATION_NAME);
SdkTracerProviderBuilder builder = SdkTracerProvider.builder().setSampler(sampler)
- .setResource(Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, applicationName)));
+ .setResource(Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, applicationName)));
spanProcessors.orderedStream().forEach(builder::addSpanProcessor);
return builder.build();
}
@@ -124,8 +125,8 @@ public class OpenTelemetryAutoConfiguration {
ObjectProvider spanExportingPredicates, ObjectProvider spanReporters,
ObjectProvider spanFilters) {
return BatchSpanProcessor.builder(new CompositeSpanExporter(spanExporters.orderedStream().collect(Collectors.toList()),
- spanExportingPredicates.orderedStream().collect(Collectors.toList()), spanReporters.orderedStream().collect(Collectors.toList()),
- spanFilters.orderedStream().collect(Collectors.toList()))).build();
+ spanExportingPredicates.orderedStream().collect(Collectors.toList()), spanReporters.orderedStream().collect(Collectors.toList()),
+ spanFilters.orderedStream().collect(Collectors.toList()))).build();
}
@Bean
@@ -139,8 +140,8 @@ public class OpenTelemetryAutoConfiguration {
OtelTracer micrometerOtelTracer(Tracer tracer, OtelTracer.EventPublisher eventPublisher,
OtelCurrentTraceContext otelCurrentTraceContext) {
return new OtelTracer(tracer, otelCurrentTraceContext, eventPublisher,
- new OtelBaggageManager(otelCurrentTraceContext, this.dubboTracingProperties.getBaggage().getRemoteFields(),
- Collections.emptyList()));
+ new OtelBaggageManager(otelCurrentTraceContext, this.dubboTracingProperties.getBaggage().getRemoteFields(),
+ Collections.emptyList()));
}
@Bean
@@ -187,12 +188,12 @@ public class OpenTelemetryAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "dubbo.tracing.propagation", name = "type", havingValue = "W3C",
- matchIfMissing = true)
+ matchIfMissing = true)
TextMapPropagator w3cTextMapPropagatorWithBaggage(OtelCurrentTraceContext otelCurrentTraceContext) {
List remoteFields = this.tracingProperties.getBaggage().getRemoteFields();
return TextMapPropagator.composite(W3CTraceContextPropagator.getInstance(),
- W3CBaggagePropagator.getInstance(), new BaggageTextMapPropagator(remoteFields,
- new OtelBaggageManager(otelCurrentTraceContext, remoteFields, Collections.emptyList())));
+ W3CBaggagePropagator.getInstance(), new BaggageTextMapPropagator(remoteFields,
+ new OtelBaggageManager(otelCurrentTraceContext, remoteFields, Collections.emptyList())));
}
@Bean
@@ -201,14 +202,14 @@ public class OpenTelemetryAutoConfiguration {
TextMapPropagator b3BaggageTextMapPropagator(OtelCurrentTraceContext otelCurrentTraceContext) {
List remoteFields = this.tracingProperties.getBaggage().getRemoteFields();
return TextMapPropagator.composite(B3Propagator.injectingSingleHeader(),
- new BaggageTextMapPropagator(remoteFields,
- new OtelBaggageManager(otelCurrentTraceContext, remoteFields, Collections.emptyList())));
+ new BaggageTextMapPropagator(remoteFields,
+ new OtelBaggageManager(otelCurrentTraceContext, remoteFields, Collections.emptyList())));
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "dubbo.tracing.baggage.correlation", name = "enabled",
- matchIfMissing = true)
+ matchIfMissing = true)
Slf4JBaggageEventListener otelSlf4JBaggageEventListener() {
return new Slf4JBaggageEventListener(this.tracingProperties.getBaggage().getCorrelation().getFields());
}
@@ -229,7 +230,7 @@ public class OpenTelemetryAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "dubbo.tracing.propagation", name = "type", havingValue = "W3C",
- matchIfMissing = true)
+ matchIfMissing = true)
W3CTraceContextPropagator w3cTextMapPropagatorWithoutBaggage() {
return W3CTraceContextPropagator.getInstance();
}
From f57dbcfae3506d499600d255cfb044ff097324f8 Mon Sep 17 00:00:00 2001
From: ZhaoGZzzzzzzz <103230915+ZhaoGZzzzzzzz@users.noreply.github.com>
Date: Tue, 28 Mar 2023 15:29:24 +0800
Subject: [PATCH 031/122] Fix #11524 (#11524) (#11936)
---
.../metadata/ConfigurableMetadataServiceExporter.java | 9 ---------
1 file changed, 9 deletions(-)
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java
index fb6dab69c0..10f2ebf14f 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java
@@ -39,7 +39,6 @@ import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Collection;
import java.util.Collections;
-import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -49,12 +48,9 @@ import java.util.stream.Stream;
import static java.util.Collections.emptyList;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_PROTOCOL_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PROTOCOL_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_FIND_PROTOCOL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_METADATA_SERVICE_EXPORTED;
import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY;
@@ -282,11 +278,6 @@ public class ConfigurableMetadataServiceExporter {
serviceConfig.setMethods(generateMethodConfig());
serviceConfig.setConnections(1); // separate connection
serviceConfig.setExecutes(100); // max tasks running at the same time
- Map threadParams = new HashMap<>();
- threadParams.put(THREADPOOL_KEY, "cached");
- threadParams.put(THREADS_KEY, "100");
- threadParams.put(CORE_THREADS_KEY, "2");
- serviceConfig.setParameters(threadParams);
return serviceConfig;
}
From b967d3c1f83265f99b1b86303ccf4899ec4ee072 Mon Sep 17 00:00:00 2001
From: eye-gu <734164350@qq.com>
Date: Tue, 28 Mar 2023 15:34:45 +0800
Subject: [PATCH 032/122] binary search weights Fixes 11776 (#11886)
Co-authored-by: eye
---
.../loadbalance/RandomLoadBalance.java | 20 ++++++++++++++++---
1 file changed, 17 insertions(+), 3 deletions(-)
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java
index cc06c0d902..ce5bdaa16c 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java
@@ -22,6 +22,7 @@ import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
+import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
@@ -79,10 +80,23 @@ public class RandomLoadBalance extends AbstractLoadBalance {
// If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight.
int offset = ThreadLocalRandom.current().nextInt(totalWeight);
// Return an invoker based on the random value.
- for (int i = 0; i < length; i++) {
- if (offset < weights[i]) {
- return invokers.get(i);
+ if (length <= 4) {
+ for (int i = 0; i < length; i++) {
+ if (offset < weights[i]) {
+ return invokers.get(i);
+ }
}
+ } else {
+ int i = Arrays.binarySearch(weights, offset);
+ if (i < 0) {
+ i = -i - 1;
+ } else {
+ while (weights[i+1] == offset) {
+ i++;
+ }
+ i++;
+ }
+ return invokers.get(i);
}
}
// If all invokers have the same weight value or totalWeight=0, return evenly.
From a0f4c6dc338f0acfd59919b499fde4a16cf7384b Mon Sep 17 00:00:00 2001
From: Andy Cheung
Date: Tue, 28 Mar 2023 15:36:06 +0800
Subject: [PATCH 033/122] [3.2] Remove deprecated method invocation in tests
(Common Module). (#11925)
* Remove deprecated method invocation in EagerThreadPoolExecutorTest and ModuleServiceRepositoryTest.
* Reformat ExtensionLoaderTest.
* Optimize ApplicationModel, EnvironmentTest, JsonUtilsTest, JsonUtils.
* Optimize ReflectUtils.
* Remove test only methods in FileCacheStore, FileCacheStoreFactory.
* Optimize tests in common module.
* Optimize tests in common module (2).
* Optimize tests in common module (3).
* Remove setJson() method.
* Remove blank test.
* Revert "Remove setJson() method."
* Revert "Remove test only methods in FileCacheStore, FileCacheStoreFactory.".
* Revert "Remove blank test."
* Revert the commit to original JsonUtils.
---
.../dubbo/common/timer/HashedWheelTimer.java | 2 +-
.../org/apache/dubbo/common/utils/JRE.java | 2 +-
.../apache/dubbo/common/utils/PojoUtils.java | 43 +++++-----
.../dubbo/common/utils/ReflectUtils.java | 8 +-
.../dubbo/rpc/model/ApplicationModel.java | 2 +-
.../compiler/support/ClassUtilsTest.java | 34 ++++----
.../dubbo/common/config/EnvironmentTest.java | 4 +-
.../DynamicConfigurationFactoryTest.java | 9 ++-
.../dubbo/common/convert/ConverterTest.java | 9 ++-
.../convert/StringToLongConverterTest.java | 10 ++-
.../common/extension/ExtensionLoaderTest.java | 20 ++---
.../ExtensionLoader_Compatible_Test.java | 13 ++-
.../NamedInternalThreadFactoryTest.java | 8 +-
.../eager/EagerThreadPoolExecutorTest.java | 8 +-
.../apache/dubbo/common/utils/JRETest.java | 17 ++--
.../dubbo/common/utils/JsonUtilsTest.java | 2 +-
.../dubbo/common/utils/ReflectUtilsTest.java | 80 +++++++++++--------
.../config/context/ConfigManagerTest.java | 24 ++++--
.../model/ModuleServiceRepositoryTest.java | 12 +--
19 files changed, 174 insertions(+), 133 deletions(-)
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java
index b6589949d4..a5c255b2b8 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java
@@ -422,7 +422,7 @@ public class HashedWheelTimer implements Timer {
private static void reportTooManyInstances() {
String resourceType = ClassUtils.simpleClassName(HashedWheelTimer.class);
logger.error(COMMON_ERROR_TOO_MANY_INSTANCES, "", "", "You are creating too many " + resourceType + " instances. " +
- resourceType + " is a shared resource that must be reused across the JVM," +
+ resourceType + " is a shared resource that must be reused across the JVM, " +
"so that only a few instances are created.");
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JRE.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JRE.java
index 5bba8a70da..8bc095d61e 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JRE.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JRE.java
@@ -117,7 +117,7 @@ public enum JRE {
return OTHER;
}
} catch (Exception e) {
- logger.debug("can't determine current JRE version, if JRE version is 8 but java.version is null", e);
+ logger.debug("Can't determine current JRE version (maybe java.version is null), assuming that JRE version is 8.", e);
}
// default java 8
return JAVA_8;
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java
index 200aa7b1be..b290529ccb 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java
@@ -16,6 +16,12 @@
*/
package org.apache.dubbo.common.utils;
+import org.apache.dubbo.common.config.ConfigurationUtils;
+import org.apache.dubbo.common.constants.CommonConstants;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
@@ -53,11 +59,6 @@ import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.Consumer;
import java.util.function.Supplier;
-import org.apache.dubbo.common.config.ConfigurationUtils;
-import org.apache.dubbo.common.constants.CommonConstants;
-import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
-import org.apache.dubbo.common.logger.LoggerFactory;
-
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_REFLECTIVE_OPERATION_FAILED;
import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom;
@@ -78,13 +79,15 @@ import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom;
public class PojoUtils {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PojoUtils.class);
- private static final ConcurrentMap NAME_METHODS_CACHE = new ConcurrentHashMap();
- private static final ConcurrentMap, ConcurrentMap> CLASS_FIELD_CACHE = new ConcurrentHashMap, ConcurrentMap>();
+ private static final ConcurrentMap NAME_METHODS_CACHE = new ConcurrentHashMap<>();
+ private static final ConcurrentMap, ConcurrentMap> CLASS_FIELD_CACHE = new ConcurrentHashMap<>();
- private static final ConcurrentMap CLASS_NOT_FOUND_CACHE = new ConcurrentHashMap();
+ private static final ConcurrentMap CLASS_NOT_FOUND_CACHE = new ConcurrentHashMap<>();
private static final Object NOT_FOUND_VALUE = new Object();
- private static final boolean GENERIC_WITH_CLZ = Boolean.parseBoolean(ConfigurationUtils.getProperty(CommonConstants.GENERIC_WITH_CLZ_KEY, "true"));
+ private static final boolean GENERIC_WITH_CLZ = Boolean.parseBoolean(
+ ConfigurationUtils.getProperty(ApplicationModel.defaultModel(), CommonConstants.GENERIC_WITH_CLZ_KEY, "true"));
+
private static final List> CLASS_CAN_BE_STRING = Arrays.asList(Byte.class, Short.class, Integer.class,
Long.class, Float.class, Double.class, Boolean.class, Character.class);
@@ -121,7 +124,7 @@ public class PojoUtils {
}
public static Object generalize(Object pojo) {
- return generalize(pojo, new IdentityHashMap());
+ return generalize(pojo, new IdentityHashMap<>());
}
@SuppressWarnings("unchecked")
@@ -173,7 +176,7 @@ public class PojoUtils {
if (pojo instanceof Collection>) {
Collection src = (Collection) pojo;
int len = src.size();
- Collection dest = (pojo instanceof List>) ? new ArrayList(len) : new HashSet(len);
+ Collection dest = (pojo instanceof List>) ? new ArrayList<>(len) : new HashSet<>(len);
history.put(pojo, dest);
for (Object obj : src) {
dest.add(generalize(obj, history));
@@ -189,7 +192,7 @@ public class PojoUtils {
}
return dest;
}
- Map map = new HashMap();
+ Map map = new HashMap<>();
history.put(pojo, map);
if (GENERIC_WITH_CLZ) {
map.put("class", pojo.getClass().getName());
@@ -228,16 +231,16 @@ public class PojoUtils {
}
public static Object realize(Object pojo, Class> type) {
- return realize0(pojo, type, null, new IdentityHashMap());
+ return realize0(pojo, type, null, new IdentityHashMap<>());
}
public static Object realize(Object pojo, Class> type, Type genericType) {
- return realize0(pojo, type, genericType, new IdentityHashMap());
+ return realize0(pojo, type, genericType, new IdentityHashMap<>());
}
private static class PojoInvocationHandler implements InvocationHandler {
- private Map map;
+ private final Map map;
public PojoInvocationHandler(Map map) {
this.map = map;
@@ -259,7 +262,7 @@ public class PojoUtils {
value = map.get(methodName.substring(0, 1).toLowerCase() + methodName.substring(1));
}
if (value instanceof Map, ?> && !Map.class.isAssignableFrom(method.getReturnType())) {
- value = realize0((Map) value, method.getReturnType(), null, new IdentityHashMap());
+ value = realize0(value, method.getReturnType(), null, new IdentityHashMap<>());
}
return value;
}
@@ -268,10 +271,10 @@ public class PojoUtils {
@SuppressWarnings("unchecked")
private static Collection createCollection(Class> type, int len) {
if (type.isAssignableFrom(ArrayList.class)) {
- return new ArrayList(len);
+ return new ArrayList<>(len);
}
if (type.isAssignableFrom(HashSet.class)) {
- return new HashSet(len);
+ return new HashSet<>(len);
}
if (!type.isInterface() && !Modifier.isAbstract(type.getModifiers())) {
try {
@@ -280,7 +283,7 @@ public class PojoUtils {
// ignore
}
}
- return new ArrayList();
+ return new ArrayList<>();
}
private static Map createMap(Map src) {
@@ -318,7 +321,7 @@ public class PojoUtils {
}
if (result == null) {
- result = new HashMap();
+ result = new HashMap<>();
}
return result;
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java
index 8f7339bf8d..b32cf2d1e4 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java
@@ -872,7 +872,7 @@ public final class ReflectUtils {
return EMPTY_CLASS_ARRAY;
}
- List> cs = new ArrayList>();
+ List> cs = new ArrayList<>();
Matcher m = DESC_PATTERN.matcher(desc);
while (m.find()) {
cs.add(desc2class(cl, m.group()));
@@ -900,7 +900,7 @@ public final class ReflectUtils {
}
Method method;
if (parameterTypes == null) {
- List finded = new ArrayList();
+ List finded = new ArrayList<>();
for (Method m : clazz.getMethods()) {
if (m.getName().equals(methodName)) {
finded.add(m);
@@ -1140,7 +1140,7 @@ public final class ReflectUtils {
}
public static Map getBeanPropertyFields(Class cl) {
- Map properties = new HashMap();
+ Map properties = new HashMap<>();
for (; cl != null; cl = cl.getSuperclass()) {
Field[] fields = cl.getDeclaredFields();
for (Field field : fields) {
@@ -1159,7 +1159,7 @@ public final class ReflectUtils {
}
public static Map getBeanPropertyReadMethods(Class cl) {
- Map properties = new HashMap();
+ Map properties = new HashMap<>();
for (; cl != null; cl = cl.getSuperclass()) {
Method[] methods = cl.getDeclaredMethods();
for (Method method : methods) {
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 c0f1e3cf10..0978143257 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
@@ -43,7 +43,7 @@ import java.util.concurrent.locks.Lock;
* returned from them are of process scope. If you want to support multiple dubbo servers in one
* single process, you may need to refactor those three classes.
*
- * Represent a application which is using Dubbo and store basic metadata info for using
+ * Represent an application which is using Dubbo and store basic metadata info for using
* during the processing of RPC invoking.
*
* ApplicationModel includes many ProviderModel which is about published services
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java
index e2d990caf9..0e7c6b7a73 100644
--- a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java
+++ b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java
@@ -60,22 +60,22 @@ class ClassUtilsTest {
@Test
void testForName2() {
- ClassUtils.forName("boolean");
- ClassUtils.forName("byte");
- ClassUtils.forName("char");
- ClassUtils.forName("short");
- ClassUtils.forName("int");
- ClassUtils.forName("long");
- ClassUtils.forName("float");
- ClassUtils.forName("double");
- ClassUtils.forName("boolean[]");
- ClassUtils.forName("byte[]");
- ClassUtils.forName("char[]");
- ClassUtils.forName("short[]");
- ClassUtils.forName("int[]");
- ClassUtils.forName("long[]");
- ClassUtils.forName("float[]");
- ClassUtils.forName("double[]");
+ Assertions.assertEquals(boolean.class, ClassUtils.forName("boolean"));
+ Assertions.assertEquals(byte.class, ClassUtils.forName("byte"));
+ Assertions.assertEquals(char.class, ClassUtils.forName("char"));
+ Assertions.assertEquals(short.class, ClassUtils.forName("short"));
+ Assertions.assertEquals(int.class, ClassUtils.forName("int"));
+ Assertions.assertEquals(long.class, ClassUtils.forName("long"));
+ Assertions.assertEquals(float.class, ClassUtils.forName("float"));
+ Assertions.assertEquals(double.class, ClassUtils.forName("double"));
+ Assertions.assertEquals(boolean[].class, ClassUtils.forName("boolean[]"));
+ Assertions.assertEquals(byte[].class, ClassUtils.forName("byte[]"));
+ Assertions.assertEquals(char[].class, ClassUtils.forName("char[]"));
+ Assertions.assertEquals(short[].class, ClassUtils.forName("short[]"));
+ Assertions.assertEquals(int[].class, ClassUtils.forName("int[]"));
+ Assertions.assertEquals(long[].class, ClassUtils.forName("long[]"));
+ Assertions.assertEquals(float[].class, ClassUtils.forName("float[]"));
+ Assertions.assertEquals(double[].class, ClassUtils.forName("double[]"));
}
@Test
@@ -174,4 +174,4 @@ class ClassUtilsTest {
}
}
-}
\ No newline at end of file
+}
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentTest.java
index 75c88306fc..5d502fffaa 100644
--- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentTest.java
+++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentTest.java
@@ -77,11 +77,11 @@ class EnvironmentTest {
// test getConfigurationMaps(AbstractConfig config, String prefix)
List