You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dubbo.apache.org by me...@apache.org on 2019/08/14 03:41:19 UTC
[dubbo] branch cloud-native updated: Dubbo cloud native (#4817)
This is an automated email from the ASF dual-hosted git repository.
mercyblitz pushed a commit to branch cloud-native
in repository https://gitbox.apache.org/repos/asf/dubbo.git
The following commit(s) were added to refs/heads/cloud-native by this push:
new 12e1532 Dubbo cloud native (#4817)
12e1532 is described below
commit 12e1532a725dd8704a72b61090a98edc9da3fcbc
Author: Mercy Ma <me...@gmail.com>
AuthorDate: Wed Aug 14 11:41:13 2019 +0800
Dubbo cloud native (#4817)
* Polish apache/dubbo#4542 : [Enhancement] Adapt the Java standard Event/Listener mechanism
* Polish apache/dubbo#4541 : [Feature] Add local File System DynamicConfigurationFactory‘s extension
* Polish apache#4541 : Bugfix
* Polish apache/dubbo#4541 : Optimization
* Polish apache/dubbo#4541 : Add the compatibility for PollingWatchService on the some platforms
* Polish apache/dubbo#4541 : Add delay publish without ThreadPoolExecutor
* Polish apache/dubbo#4541 : Refactor the extension name
* Polish apache/dubbo#4541 : Add remove ops
* Polish apache/dubbo#4541 : Add testable constructor
* Polish apache/dubbo#4541 : Add getConfigGroups method
* Polish apache/dubbo#4610 : [Refactor] Refactor the bootstrap module
* Polish apache/dubbo#4541 : Fix the nulling URL issue
* Polish apache/dubbo#4622 : [Refactor] Refactor ConfigManager
* Polish apache/dubbo#4622 : [Refactor] Refactor ConfigManager
* Polish apache/dubbo#4622 : Support multiple configcenters
* Polish apache/dubbo#4671 : ServiceNameMapping will not map the group, version and protocol
* update referenceCount log (#4683)
Add comments to support multiple shared connections
* Polish /apache/dubbo#4687 : Remove the duplicated test code in dubbo-config-spring (#4688)
* #4685 修改代码if判断false问题 if (hasException == false)修改成if (!hasException) (#4695)
* Fixed Service annotation method parameters are not in effect (#4598)
* keep demo simple, and switch to use zookeeper as registry center (#4705)
* keep demo simple, and switch to use zookeeper as registry center
* remove comment
* @Reference auto-wires the instance of generic interface #4594 (#4677)
* try to shorten maven output to make travis build pass (#4710)
* use CountDownLatch to check zk registry if establish connection (#4589)
* Minor change
* Rename the extension name of WritableMetadataService
* Polish apache/dubbo#4759 : [Refactor] Change the signature of methods of MetadataService #4759
* Merge remote-tracking branch 'upstream/master' into dubbo-cloud-native
# Conflicts:
# dubbo-all/pom.xml
# dubbo-bom/pom.xml
# dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java
# dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java
# dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java
# dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
# dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java
# dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
# dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java
# dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java
# dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java
# dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java
# dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java
# dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java
# dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java
# dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java
# dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java
# dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifier.java
# dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java
# dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifierTest.java
# dubbo-metadata/dubbo-metadata-definition-protobuf/src/main/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilder.java
# dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilderTest.java
# dubbo-metadata/pom.xml
# dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java
# dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java
# dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java
# dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java
* Polish apache/dubbo#3984 : Add the implementation of Page<ServiceInstance> getInstances(String serviceName, int offset, int pageSize, boolean healthyOnly)
* Code merge
* Fix the cases
* Merge remote-tracking branch 'upstream/cloud-native' into dubbo-cloud-native
# Conflicts:
# dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java
# dubbo-metadata/dubbo-metadata-definition-protobuf/pom.xml
# dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java
# dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulServiceDiscoveryFactory.java
# dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdServiceDiscovery.java
* Refactor ConfigManager
* Refactor ConfigManager
* Resolve the issues on ConfigManager
* Refactor and add test-cases for ConfigManager
* Polish apache/dubbo#4774 : [Feature] Dubbo Cloud Native - To Support in Spring
* Polish apache/dubbo#4808 : [Feature] Add the registered/unregistered event mechanism ShutdownHook
* Polish apache/dubbo#4807 : [Feature] Add the callback mechanism ShutdownHook #4807
* Polish apache/dubbo#4813 : [Feature] add Prioritized implementation for ServiceInstanceCustomizer
* Polish apache/dubbo#4815 : [Feature] Add the ServiceLoader for Dubbo's services or components
* Polish apache/dubbo#4815 : [Feature] Add the ServiceLoader for Dubbo's services or components
---
.../org/apache/dubbo/bootstrap/DubboBootstrap.java | 93 +++++++--------
.../org.apache.dubbo.common.context.Lifecycle | 1 +
.../wrapper/CompositeDynamicConfiguration.java | 4 +-
.../org/apache/dubbo/common/context/Lifecycle.java | 78 +++++++++++++
.../org/apache/dubbo/common/lang/Prioritized.java | 71 ++++++++++++
.../dubbo/common/lang/ShutdownHookCallback.java | 18 +--
.../dubbo/common/utils/DubboServiceLoader.java | 100 +++++++++++++++++
.../apache/dubbo/common/lang/PrioritizedTest.java | 125 +++++++++++++++++++++
.../org/apache/dubbo/config/DubboShutdownHook.java | 66 ++++++++++-
.../event/DubboShutdownHookRegisteredEvent.java | 30 +++--
.../event/DubboShutdownHookUnregisteredEvent.java | 29 +++--
.../apache/dubbo/config/DubboShutdownHookTest.java | 62 ++++++++++
...g.apache.dubbo.common.lang.ShutdownHookCallback | 1 +
...ubboLifecycleComponentsApplicationListener.java | 115 +++++++++++++++++++
.../spring/context/annotation/EnableDubbo.java | 1 +
.../context/annotation/EnableDubboLifecycle.java | 34 +++---
.../dubbo/event/AbstractEventDispatcher.java | 31 ++---
.../java/org/apache/dubbo/event/EventListener.java | 17 +--
.../org/apache/dubbo/event/EchoEventListener2.java | 3 +-
.../registry/client/ServiceInstanceCustomizer.java | 3 +-
.../CustomizableServiceInstanceListener.java | 13 +--
21 files changed, 753 insertions(+), 142 deletions(-)
diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java
index 9b21751..8a4cc22 100644
--- a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java
+++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java
@@ -20,11 +20,11 @@ import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.config.configcenter.wrapper.CompositeDynamicConfiguration;
+import org.apache.dubbo.common.context.Lifecycle;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
-import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.ConsumerConfig;
@@ -38,7 +38,6 @@ import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
-import org.apache.dubbo.config.builders.AbstractBuilder;
import org.apache.dubbo.config.builders.ApplicationBuilder;
import org.apache.dubbo.config.builders.ConsumerBuilder;
import org.apache.dubbo.config.builders.ProtocolBuilder;
@@ -64,7 +63,6 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -90,7 +88,7 @@ import static org.apache.dubbo.remoting.Constants.CLIENT_KEY;
*
* @since 2.7.4
*/
-public class DubboBootstrap {
+public class DubboBootstrap implements Lifecycle {
public static final String DEFAULT_REGISTRY_ID = "REGISTRY#DEFAULT";
@@ -409,25 +407,26 @@ public class DubboBootstrap {
/**
* Initialize
*/
- public void init() {
+ public DubboBootstrap initialize() {
+ if (!isInitialized()) {
- if (isInitialized()) {
- return;
- }
+ startConfigCenter();
- startConfigCenter();
+ startMetadataReport();
- startMetadataReport();
+ loadRemoteConfigs();
- loadRemoteConfigs();
+ useRegistryAsConfigCenterIfNecessary();
- useRegistryAsConfigCenterIfNecessary();
+ initialized = true;
- initialized = true;
+ if (logger.isInfoEnabled()) {
+ logger.info(NAME + " has been initialized!");
+ }
- if (logger.isInfoEnabled()) {
- logger.info(NAME + " has been initialized!");
}
+
+ return this;
}
private void loadRemoteConfigs() {
@@ -505,12 +504,12 @@ public class DubboBootstrap {
/**
* Start the bootstrap
*/
+ @Override
public DubboBootstrap start() {
-
+ if (!isInitialized()) {
+ initialize();
+ }
if (!isStarted()) {
- if (!isInitialized()) {
- init();
- }
exportServices();
@@ -574,32 +573,26 @@ public class DubboBootstrap {
/**
* Stop the bootstrap
*/
- public void stop() {
-
- if (!isInitialized() || !isStarted()) {
- return;
+ @Override
+ public DubboBootstrap stop() {
+ if (isInitialized() && isStarted()) {
+ unregisterServiceInstance();
+ unexportServices();
+ started = false;
}
-
- unregisterServiceInstance();
-
- destroy();
-
- clear();
-
- release();
-
- shutdown();
+ return this;
}
+ @Override
public boolean isInitialized() {
return initialized;
}
+ @Override
public boolean isStarted() {
return started;
}
-
/* serve for builder apis, begin */
private ApplicationBuilder createApplicationBuilder(String name) {
return new ApplicationBuilder().name(name);
@@ -716,11 +709,11 @@ public class DubboBootstrap {
}
private void exportServices() {
- configManager.getServices().forEach(this::exportServiceConfig);
+ configManager.getServices().forEach(ServiceConfig::export);
}
- public void exportServiceConfig(ServiceConfig<?> serviceConfig) {
- serviceConfig.export();
+ private void unexportServices() {
+ configManager.getServices().forEach(ServiceConfig::unexport);
}
private void referServices() {
@@ -803,22 +796,29 @@ public class DubboBootstrap {
return this.serviceInstance;
}
- private void destroy() {
+ public void destroy() {
- destroyProtocolConfigs();
+ stop();
- destroyReferenceConfigs();
+ destroyProtocols();
+ destroyReferences();
+
+ clear();
+
+ release();
+
+ shutdown();
}
- private void destroyProtocolConfigs() {
+ private void destroyProtocols() {
configManager.getProtocols().forEach(ProtocolConfig::destroy);
if (logger.isDebugEnabled()) {
logger.debug(NAME + "'s all ProtocolConfigs have been destroyed.");
}
}
- private void destroyReferenceConfigs() {
+ private void destroyReferences() {
configManager.getReferences().forEach(ReferenceConfig::destroy);
if (logger.isDebugEnabled()) {
logger.debug(NAME + "'s all ReferenceConfigs have been destroyed.");
@@ -862,13 +862,4 @@ public class DubboBootstrap {
lock.unlock();
}
}
-
- private static <C extends AbstractConfig, B extends
- AbstractBuilder> List<C> buildConfigs(Map<String, B> map) {
- List<C> configs = new ArrayList<>();
- map.entrySet().forEach(entry -> {
- configs.add((C) entry.getValue().build());
- });
- return configs;
- }
}
diff --git a/dubbo-bootstrap/src/main/resources/META-INF/services/org.apache.dubbo.common.context.Lifecycle b/dubbo-bootstrap/src/main/resources/META-INF/services/org.apache.dubbo.common.context.Lifecycle
new file mode 100644
index 0000000..5c5dcfd
--- /dev/null
+++ b/dubbo-bootstrap/src/main/resources/META-INF/services/org.apache.dubbo.common.context.Lifecycle
@@ -0,0 +1 @@
+org.apache.dubbo.bootstrap.DubboBootstrap
\ No newline at end of file
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java
index 16484e7..8310827 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java
@@ -36,7 +36,9 @@ public class CompositeDynamicConfiguration implements DynamicConfiguration {
private Set<DynamicConfiguration> configurations = new HashSet<>();
public void addConfiguration(DynamicConfiguration configuration) {
- this.configurations.add(configuration);
+ if (configuration != null) {
+ this.configurations.add(configuration);
+ }
}
@Override
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/context/Lifecycle.java b/dubbo-common/src/main/java/org/apache/dubbo/common/context/Lifecycle.java
new file mode 100644
index 0000000..672ec2c
--- /dev/null
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/context/Lifecycle.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.common.context;
+
+/**
+ * The Lifecycle of Dubbo component
+ *
+ * @since 2.7.4
+ */
+public interface Lifecycle {
+
+ /**
+ * Initialize the component before {@link #start() start}
+ *
+ * @return current {@link Lifecycle}
+ * @throws IllegalStateException
+ */
+ Lifecycle initialize() throws IllegalStateException;
+
+ /**
+ * Initialized or not
+ *
+ * @return if initialized, return <code>true</code>, or <code>false</code>
+ */
+ boolean isInitialized();
+
+ /**
+ * Start the component
+ *
+ * @return current {@link Lifecycle}
+ * @throws IllegalStateException
+ */
+ Lifecycle start() throws IllegalStateException;
+
+ /**
+ * The component is started or not
+ *
+ * @return if started, return <code>true</code>, or <code>false</code>
+ */
+ boolean isStarted();
+
+ /**
+ * Stop the component
+ *
+ * @return current {@link Lifecycle}
+ */
+ Lifecycle stop() throws IllegalStateException;
+
+ /**
+ * The component is stopped or not
+ *
+ * @return if stopped, return <code>true</code>, or <code>false</code>
+ */
+ default boolean isStopped() {
+ return !isStarted();
+ }
+
+ /**
+ * Destroy the component
+ *
+ * @throws IllegalStateException
+ */
+ void destroy() throws IllegalStateException;
+}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/lang/Prioritized.java b/dubbo-common/src/main/java/org/apache/dubbo/common/lang/Prioritized.java
new file mode 100644
index 0000000..b25ff48
--- /dev/null
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/lang/Prioritized.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.lang;
+
+import java.util.Comparator;
+
+import static java.lang.Integer.compare;
+
+/**
+ * {@code Prioritized} interface can be implemented by objects that
+ * should be sorted, for example the tasks in executable queue.
+ *
+ * @since 2.7.4
+ */
+public interface Prioritized extends Comparable<Prioritized> {
+
+ /**
+ * The {@link Comparator} of {@link Prioritized}
+ */
+ Comparator<Object> COMPARATOR = (one, two) -> {
+ boolean b1 = one instanceof Prioritized;
+ boolean b2 = two instanceof Prioritized;
+ if (b1 && !b2) { // one is Prioritized, two is not
+ return -1;
+ } else if (b2 && !b1) { // two is Prioritized, one is not
+ return 1;
+ } else if (b1 && b2) { // one and two both Prioritized
+ return ((Prioritized) one).compareTo((Prioritized) two);
+ } else { // no different
+ return 0;
+ }
+ };
+
+ /**
+ * The maximum priority
+ */
+ int MAX_PRIORITY = Integer.MIN_VALUE;
+
+ /**
+ * The minimum priority
+ */
+ int MIN_PRIORITY = Integer.MAX_VALUE;
+
+ /**
+ * Get the priority
+ *
+ * @return the default is {@link #MIN_PRIORITY minimum one}
+ */
+ default int getPriority() {
+ return MIN_PRIORITY;
+ }
+
+ @Override
+ default int compareTo(Prioritized that) {
+ return compare(this.getPriority(), that.getPriority());
+ }
+}
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/lang/ShutdownHookCallback.java
similarity index 55%
copy from dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java
copy to dubbo-common/src/main/java/org/apache/dubbo/common/lang/ShutdownHookCallback.java
index f198b06..5bac3a0 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/lang/ShutdownHookCallback.java
@@ -14,25 +14,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.registry.client;
-
-import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent;
-import org.apache.dubbo.registry.client.event.listener.CustomizableServiceInstanceListener;
+package org.apache.dubbo.common.lang;
/**
- * The interface to customize {@link ServiceInstance the service instance} on {@link ServiceInstancePreRegisteredEvent}
+ * Dubbo ShutdownHook callback interface
*
- * @see CustomizableServiceInstanceListener
- * @see ServiceInstancePreRegisteredEvent
- * @see ServiceInstance#getMetadata()
* @since 2.7.4
*/
-public interface ServiceInstanceCustomizer {
+public interface ShutdownHookCallback extends Prioritized {
/**
- * Customizes {@link ServiceInstance the service instance}
+ * Callback execution
*
- * @param serviceInstance {@link ServiceInstance the service instance}
+ * @throws Throwable if met with some errors
*/
- void customize(ServiceInstance serviceInstance);
+ void callback() throws Throwable;
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DubboServiceLoader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DubboServiceLoader.java
new file mode 100644
index 0000000..a153494
--- /dev/null
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DubboServiceLoader.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.dubbo.common.utils;
+
+import org.apache.dubbo.common.lang.Prioritized;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.ServiceLoader;
+import java.util.stream.Stream;
+
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.StreamSupport.stream;
+
+/**
+ * An extension class of {@link ServiceLoader} to help the ease for use of Dubbo services/components
+ *
+ * @see ServiceLoader
+ * @see Prioritized
+ * @since 2.7.4
+ */
+public class DubboServiceLoader {
+
+ /**
+ * Load a {@link Stream stream} of services by the specified {@link Class type} and {@link ClassLoader}
+ *
+ * @param serviceClass {@link Class Service class}
+ * @param classLoader {@link ClassLoader}
+ * @param <S> {@link Class Service type}
+ * @return the {@link Stream} of services that has been sorted by {@link Prioritized#COMPARATOR}
+ * @throws NullPointerException if <code>serviceClass</code> is <code>null</code>
+ */
+ public static <S> Stream<S> load(Class<S> serviceClass, ClassLoader classLoader) throws NullPointerException {
+ if (serviceClass == null) {
+ throw new NullPointerException("The serviceClass must not be null");
+ }
+
+ ClassLoader actualClassLoader = classLoader;
+ if (actualClassLoader == null) {
+ actualClassLoader = DubboServiceLoader.class.getClassLoader();
+ }
+
+ ServiceLoader<S> serviceLoader = ServiceLoader.load(serviceClass, actualClassLoader);
+
+ return stream(serviceLoader.spliterator(), false).sorted(Prioritized.COMPARATOR);
+ }
+
+ /**
+ * Load a {@link Stream stream} of services by the specified {@link Class type} under
+ * {@link Thread#getContextClassLoader() the current thread context ClassLoader}
+ *
+ * @param serviceClass {@link Class Service class}
+ * @param <S> {@link Class Service type}
+ * @return the {@link Stream} of services that has been sorted by {@link Prioritized#COMPARATOR}
+ * @throws NullPointerException if <code>serviceClass</code> is <code>null</code>
+ */
+ public static <S> Stream<S> load(Class<S> serviceClass) throws NullPointerException {
+ return load(serviceClass, Thread.currentThread().getContextClassLoader());
+ }
+
+ /**
+ * Load a {@link List list} of services by the specified {@link Class type} and {@link ClassLoader}
+ *
+ * @param serviceClass {@link Class Service class}
+ * @param classLoader {@link ClassLoader}
+ * @param <S> {@link Class Service type}
+ * @return the {@link List list} of services that has been sorted by {@link Prioritized#COMPARATOR}
+ * @throws NullPointerException
+ */
+ public static <S> List<S> loadServices(Class<S> serviceClass, ClassLoader classLoader) throws NullPointerException {
+ return Collections.unmodifiableList(load(serviceClass, classLoader).collect(toList()));
+ }
+
+ /**
+ * Load a {@link List list} of services by the specified {@link Class type} under
+ * {@link Thread#getContextClassLoader() the current thread context ClassLoader}
+ *
+ * @param serviceClass {@link Class Service class}
+ * @param <S> {@link Class Service type}
+ * @return the {@link List list} of services that has been sorted by {@link Prioritized#COMPARATOR}
+ * @throws NullPointerException
+ */
+ public static <S> List<S> loadServices(Class<S> serviceClass) throws NullPointerException {
+ return loadServices(serviceClass, Thread.currentThread().getContextClassLoader());
+ }
+}
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/lang/PrioritizedTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/lang/PrioritizedTest.java
new file mode 100644
index 0000000..3ee027f
--- /dev/null
+++ b/dubbo-common/src/test/java/org/apache/dubbo/common/lang/PrioritizedTest.java
@@ -0,0 +1,125 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.lang;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+
+import static java.util.Arrays.asList;
+import static java.util.Collections.sort;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * {@link Prioritized} Test
+ *
+ * @since 2.7.4
+ */
+public class PrioritizedTest {
+
+ @Test
+ public void testConstants() {
+ assertEquals(Integer.MAX_VALUE, Prioritized.MIN_PRIORITY);
+ assertEquals(Integer.MIN_VALUE, Prioritized.MAX_PRIORITY);
+ }
+
+ @Test
+ public void testGetPriority() {
+ assertEquals(Prioritized.MIN_PRIORITY, new Prioritized() {
+ }.getPriority());
+ }
+
+ @Test
+ public void testComparator() {
+
+ List<Object> list = new LinkedList<>();
+
+ // All Prioritized
+ list.add(of(1));
+ list.add(of(2));
+ list.add(of(3));
+
+ List<Object> copy = new LinkedList<>(list);
+
+ sort(list, Prioritized.COMPARATOR);
+
+ assertEquals(copy, list);
+
+ // MIX non-Prioritized and Prioritized
+ list.clear();
+
+ list.add(1);
+ list.add(of(2));
+ list.add(of(1));
+
+ sort(list, Prioritized.COMPARATOR);
+
+ copy = asList(of(1), of(2), 1);
+
+ assertEquals(copy, list);
+
+ // All non-Prioritized
+ list.clear();
+ list.add(1);
+ list.add(2);
+ list.add(3);
+
+ sort(list, Prioritized.COMPARATOR);
+
+ copy = asList(1, 2, 3);
+
+ assertEquals(copy, list);
+
+ }
+
+ public static PrioritizedValue of(int value) {
+ return new PrioritizedValue(value);
+ }
+
+ static class PrioritizedValue implements Prioritized {
+
+ private final int value;
+
+ private PrioritizedValue(int value) {
+ this.value = value;
+ }
+
+ public int getPriority() {
+ return value;
+ }
+
+ @Override
+ public String toString() {
+ return String.valueOf(value);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof PrioritizedValue)) return false;
+ PrioritizedValue that = (PrioritizedValue) o;
+ return value == that.value;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(value);
+ }
+ }
+}
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java
index 19b97c1..321649d 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java
@@ -17,15 +17,25 @@
package org.apache.dubbo.config;
import org.apache.dubbo.common.extension.ExtensionLoader;
+import org.apache.dubbo.common.lang.ShutdownHookCallback;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.event.DubboServiceDestroyedEvent;
+import org.apache.dubbo.config.event.DubboShutdownHookRegisteredEvent;
+import org.apache.dubbo.config.event.DubboShutdownHookUnregisteredEvent;
+import org.apache.dubbo.event.Event;
import org.apache.dubbo.event.EventDispatcher;
import org.apache.dubbo.registry.support.AbstractRegistryFactory;
import org.apache.dubbo.rpc.Protocol;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
+import static java.util.Collections.sort;
+import static java.util.ServiceLoader.load;
+
/**
* The shutdown hook thread to do the clean up stuff.
* This is a singleton in order to ensure there is only one shutdown hook registered.
@@ -37,10 +47,12 @@ public class DubboShutdownHook extends Thread {
private static final Logger logger = LoggerFactory.getLogger(DubboShutdownHook.class);
private static final DubboShutdownHook DUBBO_SHUTDOWN_HOOK = new DubboShutdownHook("DubboShutdownHook");
+
/**
* Has it already been registered or not?
*/
private final AtomicBoolean registered = new AtomicBoolean(false);
+
/**
* Has it already been destroyed or not?
*/
@@ -48,8 +60,16 @@ public class DubboShutdownHook extends Thread {
private final EventDispatcher eventDispatcher = EventDispatcher.getDefaultExtension();
+ private final List<ShutdownHookCallback> callbacks = new LinkedList<>();
+
private DubboShutdownHook(String name) {
super(name);
+ loadCallbacks();
+ }
+
+ public DubboShutdownHook addCallback(ShutdownHookCallback callback) {
+ this.callbacks.add(callback);
+ return this;
}
public static DubboShutdownHook getDubboShutdownHook() {
@@ -61,15 +81,49 @@ public class DubboShutdownHook extends Thread {
if (logger.isInfoEnabled()) {
logger.info("Run shutdown hook now.");
}
+ callback();
doDestroy();
}
/**
+ * For testing purpose
+ */
+ Collection<ShutdownHookCallback> getCallbacks() {
+ sort(callbacks);
+ return callbacks;
+ }
+
+ /**
+ * For testing purpose
+ */
+ void clear() {
+ callbacks.clear();
+ }
+
+ private void loadCallbacks() {
+ load(ShutdownHookCallback.class).forEach(callbacks::add);
+ }
+
+ private void callback() {
+ getCallbacks().forEach(callback -> {
+ try {
+ callback.callback();
+ } catch (Throwable e) {
+ if (logger.isErrorEnabled()) {
+ logger.error(e.getMessage(), e);
+ }
+ }
+ });
+ }
+
+ /**
* Register the ShutdownHook
*/
public void register() {
if (!registered.get() && registered.compareAndSet(false, true)) {
- Runtime.getRuntime().addShutdownHook(getDubboShutdownHook());
+ DubboShutdownHook dubboShutdownHook = getDubboShutdownHook();
+ Runtime.getRuntime().addShutdownHook(dubboShutdownHook);
+ dispatch(new DubboShutdownHookRegisteredEvent(dubboShutdownHook));
}
}
@@ -78,7 +132,9 @@ public class DubboShutdownHook extends Thread {
*/
public void unregister() {
if (registered.get() && registered.compareAndSet(true, false)) {
- Runtime.getRuntime().removeShutdownHook(getDubboShutdownHook());
+ DubboShutdownHook dubboShutdownHook = getDubboShutdownHook();
+ Runtime.getRuntime().removeShutdownHook(dubboShutdownHook);
+ dispatch(new DubboShutdownHookUnregisteredEvent(dubboShutdownHook));
}
}
@@ -94,7 +150,11 @@ public class DubboShutdownHook extends Thread {
// destroy all the protocols
destroyProtocols();
// dispatch the DubboDestroyedEvent @since 2.7.4
- eventDispatcher.dispatch(new DubboServiceDestroyedEvent(this));
+ dispatch(new DubboServiceDestroyedEvent(this));
+ }
+
+ private void dispatch(Event event) {
+ eventDispatcher.dispatch(event);
}
/**
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/DubboShutdownHookRegisteredEvent.java
similarity index 50%
copy from dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java
copy to dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/DubboShutdownHookRegisteredEvent.java
index f198b06..6eca862 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/DubboShutdownHookRegisteredEvent.java
@@ -14,25 +14,33 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.registry.client;
+package org.apache.dubbo.config.event;
-import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent;
-import org.apache.dubbo.registry.client.event.listener.CustomizableServiceInstanceListener;
+import org.apache.dubbo.config.DubboShutdownHook;
+import org.apache.dubbo.event.Event;
/**
- * The interface to customize {@link ServiceInstance the service instance} on {@link ServiceInstancePreRegisteredEvent}
+ * An event raised when the {@link DubboShutdownHook} {@link java.lang.Runtime#addShutdownHook(Thread) registered} on
+ * {@link ApplicationShutdownHooks JVM ShutdownHooks}
*
- * @see CustomizableServiceInstanceListener
- * @see ServiceInstancePreRegisteredEvent
- * @see ServiceInstance#getMetadata()
+ * @see DubboShutdownHook
+ * @see ApplicationShutdownHooks
* @since 2.7.4
*/
-public interface ServiceInstanceCustomizer {
+public class DubboShutdownHookRegisteredEvent extends Event {
/**
- * Customizes {@link ServiceInstance the service instance}
+ * Constructs a prototypical Event.
*
- * @param serviceInstance {@link ServiceInstance the service instance}
+ * @param dubboShutdownHook The object on which the Event initially occurred.
+ * @throws IllegalArgumentException if source is null.
*/
- void customize(ServiceInstance serviceInstance);
+ public DubboShutdownHookRegisteredEvent(DubboShutdownHook dubboShutdownHook) {
+ super(dubboShutdownHook);
+ }
+
+ public DubboShutdownHook getDubboShutdownHook() {
+ return (DubboShutdownHook) getSource();
+ }
+
}
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/DubboShutdownHookUnregisteredEvent.java
similarity index 50%
copy from dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java
copy to dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/DubboShutdownHookUnregisteredEvent.java
index f198b06..621d7a2 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/DubboShutdownHookUnregisteredEvent.java
@@ -14,25 +14,32 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.registry.client;
+package org.apache.dubbo.config.event;
-import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent;
-import org.apache.dubbo.registry.client.event.listener.CustomizableServiceInstanceListener;
+import org.apache.dubbo.config.DubboShutdownHook;
+import org.apache.dubbo.event.Event;
/**
- * The interface to customize {@link ServiceInstance the service instance} on {@link ServiceInstancePreRegisteredEvent}
+ * An event raised when the {@link DubboShutdownHook} {@link Runtime#removeShutdownHook(Thread) unregistered} on
+ * {@link ApplicationShutdownHooks JVM ShutdownHooks}
*
- * @see CustomizableServiceInstanceListener
- * @see ServiceInstancePreRegisteredEvent
- * @see ServiceInstance#getMetadata()
+ * @see DubboShutdownHook
+ * @see ApplicationShutdownHooks
* @since 2.7.4
*/
-public interface ServiceInstanceCustomizer {
+public class DubboShutdownHookUnregisteredEvent extends Event {
/**
- * Customizes {@link ServiceInstance the service instance}
+ * Constructs a prototypical Event.
*
- * @param serviceInstance {@link ServiceInstance the service instance}
+ * @param dubboShutdownHook The object on which the Event initially occurred.
+ * @throws IllegalArgumentException if source is null.
*/
- void customize(ServiceInstance serviceInstance);
+ public DubboShutdownHookUnregisteredEvent(DubboShutdownHook dubboShutdownHook) {
+ super(dubboShutdownHook);
+ }
+
+ public DubboShutdownHook getDubboShutdownHook() {
+ return (DubboShutdownHook) getSource();
+ }
}
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboShutdownHookTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboShutdownHookTest.java
new file mode 100644
index 0000000..6142ce8
--- /dev/null
+++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboShutdownHookTest.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.dubbo.config;
+
+import org.apache.dubbo.common.lang.ShutdownHookCallback;
+import org.apache.dubbo.event.EventDispatcher;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * {@link DubboShutdownHook} Test
+ *
+ * @since 2.7.4
+ */
+public class DubboShutdownHookTest implements ShutdownHookCallback {
+
+ private final DubboShutdownHook dubboShutdownHook = DubboShutdownHook.getDubboShutdownHook();
+
+ private final EventDispatcher eventDispatcher = EventDispatcher.getDefaultExtension();
+
+
+ @BeforeEach
+ public void before() {
+
+ }
+
+ @AfterEach
+ public void after() {
+ eventDispatcher.removeAllEventListeners();
+ dubboShutdownHook.clear();
+ }
+
+ @Test
+ public void testCallback() {
+ assertEquals(this.getClass(), dubboShutdownHook.getCallbacks().iterator().next().getClass());
+ dubboShutdownHook.addCallback(this);
+ assertEquals(2, dubboShutdownHook.getCallbacks().size());
+ }
+
+ @Override
+ public void callback() throws Throwable {
+
+ }
+}
diff --git a/dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.common.lang.ShutdownHookCallback b/dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.common.lang.ShutdownHookCallback
new file mode 100644
index 0000000..8cad758
--- /dev/null
+++ b/dubbo-config/dubbo-config-api/src/test/resources/META-INF/services/org.apache.dubbo.common.lang.ShutdownHookCallback
@@ -0,0 +1 @@
+org.apache.dubbo.config.DubboShutdownHookTest
\ No newline at end of file
diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboLifecycleComponentsApplicationListener.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboLifecycleComponentsApplicationListener.java
new file mode 100644
index 0000000..19365d7
--- /dev/null
+++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboLifecycleComponentsApplicationListener.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.config.spring.context;
+
+
+import org.apache.dubbo.common.context.Lifecycle;
+
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationEvent;
+import org.springframework.context.ApplicationListener;
+import org.springframework.context.event.ApplicationContextEvent;
+import org.springframework.context.event.ContextClosedEvent;
+import org.springframework.context.event.ContextRefreshedEvent;
+import org.springframework.context.event.SmartApplicationListener;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ServiceLoader;
+
+import static java.util.Collections.emptyList;
+import static java.util.ServiceLoader.load;
+import static org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors;
+
+/**
+ * A {@link ApplicationListener listener} for the {@link Lifecycle Dubbo Lifecycle} components
+ *
+ * @see {@link Lifecycle Dubbo Lifecycle}
+ * @see SmartApplicationListener
+ * @since 2.7.4
+ */
+public class DubboLifecycleComponentsApplicationListener implements ApplicationListener {
+
+ private List<Lifecycle> lifecycleComponents = emptyList();
+
+ @Override
+ public void onApplicationEvent(ApplicationEvent event) {
+
+ if (!supportsEvent(event)) {
+ return;
+ }
+
+ if (event instanceof ContextRefreshedEvent) {
+ onContextRefreshedEvent((ContextRefreshedEvent) event);
+ } else if (event instanceof ContextClosedEvent) {
+ onContextClosedEvent((ContextClosedEvent) event);
+ }
+ }
+
+ protected void onContextRefreshedEvent(ContextRefreshedEvent event) {
+ initLifecycleComponents(event);
+ startLifecycleComponents();
+ }
+
+ protected void onContextClosedEvent(ContextClosedEvent event) {
+ destroyLifecycleComponents();
+ }
+
+ private void initLifecycleComponents(ContextRefreshedEvent event) {
+ ApplicationContext context = event.getApplicationContext();
+ ClassLoader classLoader = context.getClassLoader();
+ lifecycleComponents = new LinkedList<>();
+ // load the instances of Lifecycle from ServiceLoader
+ loadLifecycleComponents(lifecycleComponents, classLoader);
+ // load the Beans of Lifecycle from ApplicationContext
+ loadLifecycleComponents(lifecycleComponents, context);
+ }
+
+ private void loadLifecycleComponents(List<Lifecycle> lifecycleComponents, ClassLoader classLoader) {
+ ServiceLoader<Lifecycle> serviceLoader = load(Lifecycle.class, classLoader);
+ serviceLoader.forEach(lifecycleComponents::add);
+ }
+
+ private void loadLifecycleComponents(List<Lifecycle> lifecycleComponents, ApplicationContext context) {
+ lifecycleComponents.addAll(beansOfTypeIncludingAncestors(context, Lifecycle.class).values());
+ }
+
+ private void startLifecycleComponents() {
+ lifecycleComponents.forEach(Lifecycle::start);
+ }
+
+ private void destroyLifecycleComponents() {
+ lifecycleComponents.forEach(Lifecycle::destroy);
+ }
+
+ /**
+ * the specified {@link ApplicationEvent event} must be {@link ApplicationContextEvent} and
+ * its correlative {@link ApplicationContext} must be root
+ *
+ * @param event
+ * @return
+ */
+ private boolean supportsEvent(ApplicationEvent event) {
+ return event instanceof ApplicationContextEvent &&
+ isRootApplicationContext((ApplicationContextEvent) event);
+ }
+
+
+ private boolean isRootApplicationContext(ApplicationContextEvent event) {
+ return event.getApplicationContext().getParent() == null;
+ }
+}
diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java
index 706e288..e07c535 100644
--- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java
+++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java
@@ -43,6 +43,7 @@ import java.lang.annotation.Target;
@Documented
@EnableDubboConfig
@DubboComponentScan
+@EnableDubboLifecycle
public @interface EnableDubbo {
/**
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboLifecycle.java
similarity index 53%
copy from dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java
copy to dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboLifecycle.java
index f198b06..0abd18e 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java
+++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboLifecycle.java
@@ -14,25 +14,29 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.registry.client;
+package org.apache.dubbo.config.spring.context.annotation;
-import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent;
-import org.apache.dubbo.registry.client.event.listener.CustomizableServiceInstanceListener;
+import org.apache.dubbo.config.spring.context.DubboLifecycleComponentsApplicationListener;
+
+import org.springframework.context.Lifecycle;
+import org.springframework.context.annotation.Import;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
/**
- * The interface to customize {@link ServiceInstance the service instance} on {@link ServiceInstancePreRegisteredEvent}
+ * Enables Dubbo {@link Lifecycle} components
*
- * @see CustomizableServiceInstanceListener
- * @see ServiceInstancePreRegisteredEvent
- * @see ServiceInstance#getMetadata()
* @since 2.7.4
*/
-public interface ServiceInstanceCustomizer {
-
- /**
- * Customizes {@link ServiceInstance the service instance}
- *
- * @param serviceInstance {@link ServiceInstance the service instance}
- */
- void customize(ServiceInstance serviceInstance);
+@Target({ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+@Inherited
+@Documented
+@Import(DubboLifecycleComponentsApplicationListener.class)
+public @interface EnableDubboLifecycle {
}
diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/AbstractEventDispatcher.java b/dubbo-event/src/main/java/org/apache/dubbo/event/AbstractEventDispatcher.java
index add8f61..a2182eb 100644
--- a/dubbo-event/src/main/java/org/apache/dubbo/event/AbstractEventDispatcher.java
+++ b/dubbo-event/src/main/java/org/apache/dubbo/event/AbstractEventDispatcher.java
@@ -25,6 +25,8 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
import static java.util.Collections.sort;
import static java.util.Collections.unmodifiableList;
@@ -81,18 +83,25 @@ public abstract class AbstractEventDispatcher implements EventDispatcher {
public List<EventListener<?>> getAllEventListeners() {
List<EventListener<?>> listeners = new LinkedList<>();
- listenersCache
+ sortedListeners().forEach(listener -> {
+ addIfAbsent(listeners, listener);
+ });
+
+ return unmodifiableList(listeners);
+ }
+
+ protected Stream<EventListener> sortedListeners() {
+ return sortedListeners(e -> true);
+ }
+
+ protected Stream<EventListener> sortedListeners(Predicate<Map.Entry<Class<? extends Event>, List<EventListener>>> predicate) {
+ return listenersCache
.entrySet()
.stream()
+ .filter(predicate)
.map(Map.Entry::getValue)
.flatMap(Collection::stream)
- .forEach(listener -> {
- addIfAbsent(listeners, listener);
- });
-
- sort((List) listeners);
-
- return unmodifiableList(listeners);
+ .sorted();
}
private <E> void addIfAbsent(Collection<E> collection, E element) {
@@ -108,11 +117,7 @@ public abstract class AbstractEventDispatcher implements EventDispatcher {
// execute in sequential or parallel execution model
executor.execute(() -> {
- listenersCache.entrySet()
- .stream()
- .filter(entry -> entry.getKey().isAssignableFrom(event.getClass()))
- .map(Map.Entry::getValue)
- .flatMap(Collection::stream)
+ sortedListeners(entry -> entry.getKey().isAssignableFrom(event.getClass()))
.forEach(listener -> {
listener.onEvent(event);
});
diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/EventListener.java b/dubbo-event/src/main/java/org/apache/dubbo/event/EventListener.java
index edc0475..2d6d4d3 100644
--- a/dubbo-event/src/main/java/org/apache/dubbo/event/EventListener.java
+++ b/dubbo-event/src/main/java/org/apache/dubbo/event/EventListener.java
@@ -16,11 +16,12 @@
*/
package org.apache.dubbo.event;
+import org.apache.dubbo.common.lang.Prioritized;
+
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Objects;
-import static java.lang.Integer.compare;
import static org.apache.dubbo.common.utils.ReflectUtils.findParameterizedTypes;
/**
@@ -36,7 +37,7 @@ import static org.apache.dubbo.common.utils.ReflectUtils.findParameterizedTypes;
* @since 2.7.4
*/
@FunctionalInterface
-public interface EventListener<E extends Event> extends java.util.EventListener, Comparable<EventListener<E>> {
+public interface EventListener<E extends Event> extends java.util.EventListener, Prioritized {
/**
* Handle a {@link Event Dubbo Event} when it's be published
@@ -50,18 +51,10 @@ public interface EventListener<E extends Event> extends java.util.EventListener,
*
* @return the value is more greater, the priority is more lower.
* {@link Integer#MIN_VALUE} indicates the highest priority. The default value is {@link Integer#MAX_VALUE}.
- * The comparison rule , refer to {@link #compareTo(EventListener)}.
- * @see #compareTo(EventListener)
- * @see Integer#MAX_VALUE
- * @see Integer#MIN_VALUE
+ * The comparison rule , refer to {@link #compareTo}.
*/
default int getPriority() {
- return Integer.MAX_VALUE;
- }
-
- @Override
- default int compareTo(EventListener<E> another) {
- return compare(this.getPriority(), another.getPriority());
+ return MIN_PRIORITY;
}
/**
diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener2.java b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener2.java
index a6da23c..f9b291e 100644
--- a/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener2.java
+++ b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener2.java
@@ -25,8 +25,7 @@ import java.util.Vector;
*
* @since 2.7.4
*/
-public class EchoEventListener2 extends Vector<EventListener<Event>> implements Serializable, Comparable<EventListener<Event>>,
- EventListener<Event> {
+public class EchoEventListener2 extends Vector<EventListener<Event>> implements Serializable, EventListener<Event> {
private AbstractEventListener<Event> delegate = new AbstractEventListener<Event>() {
@Override
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java
index f198b06..eefbc42 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java
@@ -16,6 +16,7 @@
*/
package org.apache.dubbo.registry.client;
+import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent;
import org.apache.dubbo.registry.client.event.listener.CustomizableServiceInstanceListener;
@@ -27,7 +28,7 @@ import org.apache.dubbo.registry.client.event.listener.CustomizableServiceInstan
* @see ServiceInstance#getMetadata()
* @since 2.7.4
*/
-public interface ServiceInstanceCustomizer {
+public interface ServiceInstanceCustomizer extends Prioritized {
/**
* Customizes {@link ServiceInstance the service instance}
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/CustomizableServiceInstanceListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/CustomizableServiceInstanceListener.java
index ab22f9a..60bc23c 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/CustomizableServiceInstanceListener.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/CustomizableServiceInstanceListener.java
@@ -21,10 +21,9 @@ import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent;
-import java.util.Iterator;
import java.util.ServiceLoader;
-import static java.util.ServiceLoader.load;
+import static org.apache.dubbo.common.utils.DubboServiceLoader.load;
/**
@@ -40,15 +39,9 @@ public class CustomizableServiceInstanceListener implements EventListener<Servic
@Override
public void onEvent(ServiceInstancePreRegisteredEvent event) {
-
- ServiceLoader<ServiceInstanceCustomizer> customizers = load(ServiceInstanceCustomizer.class);
-
- Iterator<ServiceInstanceCustomizer> iterator = customizers.iterator();
-
- while (iterator.hasNext()) {
- ServiceInstanceCustomizer customizer = iterator.next();
+ load(ServiceInstanceCustomizer.class).forEach(customizer -> {
// customizes
customizer.customize(event.getServiceInstance());
- }
+ });
}
}