You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dubbo.apache.org by li...@apache.org on 2018/12/17 06:57:06 UTC

[incubator-dubbo] branch dev-metadata updated (368a59e -> f92f00f)

This is an automated email from the ASF dual-hosted git repository.

liujun pushed a change to branch dev-metadata
in repository https://gitbox.apache.org/repos/asf/incubator-dubbo.git.


    from 368a59e  Release resource after use in ConfigParserTest (#2905)
     new b01e251  fix problem when creating router chain for StaticDirectory (consume multi groups)
     new c94ac7a  Optimize ConfigCenter api and implementation 1. add group to api definition. 2. add removeListener implementation. 3. fix Zookeeper implementation
     new 6007fd3  Optimize service governance: 1. avoid duplicate notification of application level override rule 2. remove route cache 3. support sub menu in ops for router and configurator
     new 0a2aab8  support using multi registries/protocols in config center.
     new e425767  fix problem of governance: configurator & router
     new e86b89c  resolve conflicts
     new f92f00f  use asyncInterfaceClass

The 7 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 ...rFactory.java => AbstractAppRouterFactory.java} |  77 ++--
 ...uterFactory.java => AbstractRouterFactory.java} |  74 ++--
 .../java/org/apache/dubbo/rpc/cluster/Router.java  |  44 ++-
 .../org/apache/dubbo/rpc/cluster/RouterChain.java  | 112 ++----
 .../apache/dubbo/rpc/cluster/RouterFactory.java    |  14 +-
 .../cluster/configurator/AbstractConfigurator.java |   4 +-
 .../cluster/configurator/parser/ConfigParser.java  |  77 ++--
 .../configurator/parser/model/ConfigItem.java      |  23 ++
 .../parser/model/ConfiguratorConfig.java           |  16 +-
 .../rpc/cluster/directory/StaticDirectory.java     |  11 +-
 .../dubbo/rpc/cluster/router/AbstractRouter.java   |  52 ++-
 .../dubbo/rpc/cluster/router/InvokerTreeCache.java | 127 -------
 .../apache/dubbo/rpc/cluster/router/TreeNode.java  | 113 ------
 .../cluster/router/condition/ConditionRouter.java  |  11 +-
 .../config/AbstractConfigConditionRouter.java      | 145 ++++++++
 ...rFactory.java => AppConfigConditionRouter.java} |  26 +-
 ...y.java => AppConfigConditionRouterFactory.java} |  13 +-
 .../condition/config/ConfigConditionRouter.java    | 227 ------------
 ...tory.java => ServiceConfigConditionRouter.java} |  26 +-
 ...va => ServiceConfigConditionRouterFactory.java} |  17 +-
 ...tionRouterRule.java => BlackWhiteListRule.java} |   5 +-
 .../config/model/ConditionRouterRule.java          |   9 +
 .../config/model/ConditionRuleParser.java          |   6 +
 .../cluster/router/mock/MockInvokersSelector.java  |   5 -
 .../rpc/cluster/router/mock/MockRouterFactory.java |   5 -
 .../rpc/cluster/router/script/ScriptRouter.java    |   5 -
 .../dubbo/rpc/cluster/router/tag/TagRouter.java    | 187 +++-------
 .../rpc/cluster/router/tag/TagRouterFactory.java   |  17 +-
 .../org.apache.dubbo.rpc.cluster.RouterFactory     |   3 +-
 .../configurator/parser/ConfigParserTest.java      | 182 +++++----
 .../cluster/router/file/FileRouterEngineTest.java  |  10 +-
 .../support/AbstractClusterInvokerTest.java        |   6 +-
 .../support/wrapper/MockClusterInvokerTest.java    |  11 +-
 .../java/org/apache/dubbo/common/Constants.java    |  12 +-
 .../src/main/java/org/apache/dubbo/common/URL.java |   5 +
 .../common/config/CompositeConfiguration.java      |   6 +-
 .../dubbo/common/config/ConfigurationUtils.java    |   1 +
 .../apache/dubbo/common/config/Environment.java    |  42 ++-
 .../org/apache/dubbo/common/utils/UrlUtils.java    |   6 +
 .../org/apache/dubbo/config/AbstractConfig.java    |  25 +-
 .../dubbo/config/AbstractInterfaceConfig.java      | 142 ++++---
 .../apache/dubbo/config/AbstractServiceConfig.java |  10 +
 .../org/apache/dubbo/config/ApplicationConfig.java |  10 +
 .../apache/dubbo/config/ConfigCenterConfig.java    |  31 +-
 .../org/apache/dubbo/config/ReferenceConfig.java   |   4 +-
 .../org/apache/dubbo/config/ServiceConfig.java     |  75 +++-
 .../apache/dubbo/config/AbstractConfigTest.java    |   8 +-
 .../dubbo/config/spring/ConfigCenterBean.java      |  22 +-
 .../apache/dubbo/config/spring/ReferenceBean.java  |  30 +-
 .../apache/dubbo/config/spring/ServiceBean.java    |  56 ++-
 .../annotation/DubboConfigConfiguration.java       |   4 +-
 .../spring/schema/DubboBeanDefinitionParser.java   |  38 +-
 .../spring/schema/DubboNamespaceHandler.java       |   2 +-
 .../src/main/resources/META-INF/compat/dubbo.xsd   |   4 +-
 .../src/main/resources/META-INF/dubbo.xsd          |   4 +-
 .../configcenter/AbstractDynamicConfiguration.java |  40 +-
 .../dubbo/configcenter/ConfigChangeEvent.java      |  13 +-
 .../dubbo/configcenter/DynamicConfiguration.java   |  47 ++-
 .../support/nop/NopDynamicConfiguration.java       |  12 +-
 .../mock/MockDynamicConfiguration.java             |  12 +-
 .../support/apollo/ApolloDynamicConfiguration.java |  43 ++-
 .../support/zookeeper/CacheListener.java           |  11 +-
 .../zookeeper/ZookeeperDynamicConfiguration.java   |  31 +-
 .../ZookeeperDynamicConfigurationTest.java         |   2 +-
 .../integration/AbstractConfiguratorListener.java  |  79 ++++
 .../registry/integration/RegistryDirectory.java    | 411 ++++++++++++---------
 .../registry/integration/RegistryProtocol.java     | 226 +++++------
 .../registry/support/ProviderConsumerRegTable.java |  11 +-
 .../java/org/apache/dubbo/registry/ZKTools.java    |  44 ++-
 .../registry/dubbo/RegistryDirectoryTest.java      |   5 +-
 .../java/org/apache/dubbo/rpc/AsyncContext.java    |   1 +
 .../main/java/org/apache/dubbo/rpc/RpcContext.java |   3 +
 .../apache/dubbo/rpc/model/ApplicationModel.java   |  10 +
 73 files changed, 1620 insertions(+), 1578 deletions(-)
 copy dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/{router/condition/ConditionRouterFactory.java => AbstractAppRouterFactory.java} (68%)
 copy dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/{router/condition/ConditionRouterFactory.java => AbstractRouterFactory.java} (58%)
 delete mode 100644 dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/InvokerTreeCache.java
 delete mode 100644 dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/TreeNode.java
 create mode 100644 dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AbstractConfigConditionRouter.java
 copy dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/{ConfigConditionRouterFactory.java => AppConfigConditionRouter.java} (60%)
 copy dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/{ConfigConditionRouterFactory.java => AppConfigConditionRouterFactory.java} (76%)
 delete mode 100644 dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouter.java
 copy dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/{ConfigConditionRouterFactory.java => ServiceConfigConditionRouter.java} (61%)
 rename dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/{ConfigConditionRouterFactory.java => ServiceConfigConditionRouterFactory.java} (74%)
 copy dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/{ConditionRouterRule.java => BlackWhiteListRule.java} (91%)
 create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java


[incubator-dubbo] 01/07: fix problem when creating router chain for StaticDirectory (consume multi groups)

Posted by li...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

liujun pushed a commit to branch dev-metadata
in repository https://gitbox.apache.org/repos/asf/incubator-dubbo.git

commit b01e251a541fb73c41fcc3e458efbf65c36fdde7
Author: ken.lj <ke...@gmail.com>
AuthorDate: Tue Dec 4 13:45:10 2018 +0800

    fix problem when creating router chain for StaticDirectory (consume multi groups)
---
 .../src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java    | 1 +
 .../java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java   | 2 +-
 .../rpc/cluster/router/condition/config/ConfigConditionRouter.java | 7 +++++--
 .../java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java    | 4 +++-
 .../org/apache/dubbo/registry/integration/RegistryDirectory.java   | 2 +-
 5 files changed, 11 insertions(+), 5 deletions(-)

diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java
index 2848904..3dfa325 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java
@@ -140,6 +140,7 @@ public class RouterChain<T> {
             parentNode.addChild(node);
             // Only when we have more routers and the sub-lis is not empty.
             if (i < routers.size() && CollectionUtils.isNotEmpty(list)) {
+                node.setInvokers(null); // only store invoker list in leaf nodes.
                 Router nextRouter = routers.get(i);
                 doRoute(nextRouter, i + 1, node, nextRouter.preRoute(list, url, invocation), url, invocation);
             }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java
index dc8b63b..56f24ca 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java
@@ -29,7 +29,7 @@ import java.util.List;
 import java.util.Map;
 
 /**
- * TODO Extract more code here if necessary
+ * TODO Extract more code to here if necessary
  */
 public abstract class AbstractRouter implements Router {
     protected int priority;
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouter.java
index cf1f336..91fe434 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouter.java
@@ -77,7 +77,7 @@ public class ConfigConditionRouter extends AbstractRouter implements Configurati
     @Override
     public synchronized void process(ConfigChangeEvent event) {
         if (logger.isInfoEnabled()) {
-            logger.info("Notification of tag rule, change type is: " + event.getChangeType() + ", raw rule is:\n " + event.getNewValue());
+            logger.info("Notification of condition rule, change type is: " + event.getChangeType() + ", raw rule is:\n " + event.getNewValue());
         }
 
         if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
@@ -102,7 +102,10 @@ public class ConfigConditionRouter extends AbstractRouter implements Configurati
                 logger.error("Failed to parse the raw condition rule and it will not take effect, please check if the condition rule matches with the template, the raw rule is:\n " + event.getNewValue(), e);
             }
         }
-        routerChain.notifyRuleChanged();
+
+        if (routerChain != null) {
+            routerChain.notifyRuleChanged();
+        }
     }
 
     @Override
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java
index a8477e0..1c86eb1 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java
@@ -110,7 +110,9 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
             } else {
                 this.tagRouterRule = TagRuleParser.parse(event.getNewValue());
             }
-            routerChain.notifyRuleChanged();
+            if (routerChain != null) {
+                routerChain.notifyRuleChanged();
+            }
         } catch (Exception e) {
             logger.error("Failed to parse the raw tag router rule and it will not take effect, please check if the rule matches with the template, the raw rule is:\n ", e);
         }
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java
index e352de5..fea5824 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java
@@ -381,7 +381,7 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
                 for (List<Invoker<T>> groupList : groupMap.values()) {
                     StaticDirectory<T> staticDirectory = new StaticDirectory<>(groupList);
                     Map<String, List<Invoker<T>>> methodGroupInvokers = new HashMap<>();
-                    methodGroupInvokers.put(method, groupInvokers);
+                    methodGroupInvokers.put(method, groupList);
                     staticDirectory.buildRouterChain(methodGroupInvokers, dynamicConfiguration);
                     groupInvokers.add(cluster.join(staticDirectory));
                 }


[incubator-dubbo] 04/07: support using multi registries/protocols in config center.

Posted by li...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

liujun pushed a commit to branch dev-metadata
in repository https://gitbox.apache.org/repos/asf/incubator-dubbo.git

commit 0a2aab8c59d43486bb497c09a1b44c986db4fe78
Author: ken.lj <ke...@gmail.com>
AuthorDate: Mon Dec 17 11:31:04 2018 +0800

    support using multi registries/protocols in config center.
---
 .../common/config/CompositeConfiguration.java      |   6 +-
 .../dubbo/common/config/ConfigurationUtils.java    |   1 +
 .../apache/dubbo/common/config/Environment.java    |  42 ++++--
 .../org/apache/dubbo/common/utils/UrlUtils.java    |   6 +
 .../org/apache/dubbo/config/AbstractConfig.java    |  25 ++--
 .../dubbo/config/AbstractInterfaceConfig.java      | 142 ++++++++++++++-------
 .../apache/dubbo/config/AbstractServiceConfig.java |  10 ++
 .../org/apache/dubbo/config/ApplicationConfig.java |  10 ++
 .../apache/dubbo/config/ConfigCenterConfig.java    |  31 ++++-
 .../org/apache/dubbo/config/ReferenceConfig.java   |   2 +-
 .../org/apache/dubbo/config/ServiceConfig.java     |  75 ++++++++---
 .../apache/dubbo/config/AbstractConfigTest.java    |   8 +-
 .../dubbo/config/spring/ConfigCenterBean.java      |  22 ++--
 .../apache/dubbo/config/spring/ReferenceBean.java  |  30 ++++-
 .../apache/dubbo/config/spring/ServiceBean.java    |  56 +++++++-
 .../annotation/DubboConfigConfiguration.java       |   4 +-
 .../spring/schema/DubboBeanDefinitionParser.java   |  38 +-----
 .../spring/schema/DubboNamespaceHandler.java       |   2 +-
 .../src/main/resources/META-INF/compat/dubbo.xsd   |   4 +-
 .../src/main/resources/META-INF/dubbo.xsd          |   4 +-
 20 files changed, 350 insertions(+), 168 deletions(-)

diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java
index 6d732da..a181aeb 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java
@@ -19,7 +19,6 @@ package org.apache.dubbo.common.config;
 import java.util.Arrays;
 import java.util.LinkedList;
 import java.util.List;
-import java.util.stream.Collectors;
 
 /**
  *
@@ -78,9 +77,6 @@ public class CompositeConfiguration extends AbstractConfiguration {
 
     @Override
     public boolean containsKey(String key) {
-        List<Configuration> subConfigList = configList.stream()
-                .filter(config -> config.containsKey(key))
-                .collect(Collectors.toList());
-        return subConfigList.size() > 0;
+        return configList.stream().anyMatch(c -> c.containsKey(key));
     }
 }
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java
index 28ef93b..a69a6cf 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java
@@ -55,4 +55,5 @@ public class ConfigurationUtils {
     public static String getProperty(String property, String defaultValue) {
         return Environment.getInstance().getConfiguration().getString(property, defaultValue);
     }
+
 }
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java
index 11aabd5..fe4c03d 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java
@@ -21,6 +21,7 @@ import org.apache.dubbo.common.utils.StringUtils;
 
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Optional;
 import java.util.concurrent.ConcurrentHashMap;
 
 /**
@@ -82,14 +83,22 @@ public class Environment {
         return appConfigs.get(toKey(prefix, id));
     }
 
-    public void setExternalConfig(Map<String, String> externalConfiguration) {
+    public void setExternalConfigMap(Map<String, String> externalConfiguration) {
         this.externalConfigurationMap = externalConfiguration;
     }
 
-    public void setAppExternalConfig(Map<String, String> appExternalConfiguration) {
+    public void setAppExternalConfigMap(Map<String, String> appExternalConfiguration) {
         this.appExternalConfigurationMap = appExternalConfiguration;
     }
 
+    public Map<String, String> getExternalConfigurationMap() {
+        return externalConfigurationMap;
+    }
+
+    public Map<String, String> getAppExternalConfigurationMap() {
+        return appExternalConfigurationMap;
+    }
+
     public void addAppConfig(String prefix, String id, Map<String, String> properties) {
         appConfigs.computeIfAbsent(toKey(prefix, id), k -> {
             InmemoryConfiguration configuration = new InmemoryConfiguration(prefix, id);
@@ -117,15 +126,24 @@ public class Environment {
      */
     public Configuration getConfiguration(String prefix, String id) {
         CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
-        compositeConfiguration.addConfiguration(this.getSystemConfig(prefix, id));
-        compositeConfiguration.addConfiguration(this.getAppExternalConfig(prefix, id));
-        compositeConfiguration.addConfiguration(this.getExternalConfig(prefix, id));
-        compositeConfiguration.addConfiguration(this.getPropertiesConfig(prefix, id));
-
         InmemoryConfiguration appConfig = this.getAppConfig(prefix, id);
-        if (appConfig != null) {
-            int index = configCenterFirst ? 3 : 1;
-            compositeConfiguration.addConfiguration(index, appConfig);
+        // Config center has the highest priority
+        if (!configCenterFirst) {
+            if (appConfig != null) {
+                compositeConfiguration.addConfiguration(appConfig);
+            }
+            compositeConfiguration.addConfiguration(this.getSystemConfig(prefix, id));
+            compositeConfiguration.addConfiguration(this.getAppExternalConfig(prefix, id));
+            compositeConfiguration.addConfiguration(this.getExternalConfig(prefix, id));
+            compositeConfiguration.addConfiguration(this.getPropertiesConfig(prefix, id));
+        } else {
+            compositeConfiguration.addConfiguration(this.getSystemConfig(prefix, id));
+            compositeConfiguration.addConfiguration(this.getAppExternalConfig(prefix, id));
+            compositeConfiguration.addConfiguration(this.getExternalConfig(prefix, id));
+            if (appConfig != null) {
+                compositeConfiguration.addConfiguration(appConfig);
+            }
+            compositeConfiguration.addConfiguration(this.getPropertiesConfig(prefix, id));
         }
         return compositeConfiguration;
     }
@@ -161,8 +179,8 @@ public class Environment {
         this.configCenterFirst = configCenterFirst;
     }
 
-    public Configuration getDynamicConfiguration() {
-        return dynamicConfiguration;
+    public Optional<Configuration> getDynamicConfiguration() {
+        return Optional.ofNullable(dynamicConfiguration);
     }
 
     public void setDynamicConfiguration(Configuration dynamicConfiguration) {
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java
index 65381ab..8cbb34d 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java
@@ -24,6 +24,8 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
 
 public class UrlUtils {
 
@@ -439,6 +441,10 @@ public class UrlUtils {
                 value.getParameter(Constants.VERSION_KEY));
     }
 
+    public static List<URL> classifyUrls(List<URL> urls, Predicate<URL> predicate) {
+        return urls.stream().filter(predicate).collect(Collectors.toList());
+    }
+
     /**
      * Check if the given value matches the given pattern. The pattern supports wildcard "*".
      *
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java
index 537893a..9ca9204 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java
@@ -35,8 +35,10 @@ import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Set;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+import java.util.stream.Collectors;
 
 /**
  * Utility methods and public methods for parsing configuration
@@ -80,8 +82,7 @@ public abstract class AbstractConfig implements Serializable {
     }
 
     protected String id;
-    private boolean init;
-    private volatile Map<String, String> metaData;
+    protected String prefix;
 
     private static String convertLegacyValue(String key, String value) {
         if (value != null && value.length() > 0) {
@@ -352,6 +353,13 @@ public abstract class AbstractConfig implements Serializable {
         }
     }
 
+    protected static Set<String> getSubProperties(Map<String, String> properties, String prefix) {
+        return properties.keySet().stream().filter(k -> k.contains(prefix)).map(k -> {
+            k = k.substring(prefix.length());
+            return k.substring(0, k.indexOf("."));
+        }).collect(Collectors.toSet());
+    }
+
     private static String extractPropertyName(Class<?> clazz, Method setter) throws Exception {
         String propertyName = setter.getName().substring("set".length());
         Method getter = null;
@@ -436,7 +444,7 @@ public abstract class AbstractConfig implements Serializable {
      * Notice! This method should include all properties in the returning map, treat @Parameter differently compared to appendParameters.
      */
     public Map<String, String> getMetaData() {
-        metaData = new HashMap<>();
+        Map<String, String> metaData = new HashMap<>();
         Method[] methods = this.getClass().getMethods();
         for (Method method : methods) {
             try {
@@ -510,7 +518,11 @@ public abstract class AbstractConfig implements Serializable {
 
     @Parameter(excluded = true)
     public String getPrefix() {
-        return Constants.DUBBO + "." + getTagName(this.getClass());
+        return StringUtils.isNotEmpty(prefix) ? prefix : (Constants.DUBBO + "." + getTagName(this.getClass()));
+    }
+
+    public void setPrefix(String prefix) {
+        this.prefix = prefix;
     }
 
     /**
@@ -518,11 +530,6 @@ public abstract class AbstractConfig implements Serializable {
      * overriding of customized parameters stored in 'parameters'.
      */
     public void refresh() {
-        if (init) {
-            return;
-        }
-        init = true;
-
         try {
             Environment env = Environment.getInstance();
             env.addAppConfig(getPrefix(), getId(), getMetaData());
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java
index 61c29ac..8bef3bf 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java
@@ -34,13 +34,16 @@ import org.apache.dubbo.rpc.Filter;
 import org.apache.dubbo.rpc.InvokerListener;
 import org.apache.dubbo.rpc.ProxyFactory;
 import org.apache.dubbo.rpc.cluster.Cluster;
+import org.apache.dubbo.rpc.model.ApplicationModel;
 import org.apache.dubbo.rpc.support.MockInvoker;
 
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 import static org.apache.dubbo.common.Constants.APPLICATION_KEY;
 import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
@@ -94,6 +97,8 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig {
     // registry centers
     protected List<RegistryConfig> registries;
 
+    protected String registryLiteral;
+
     // connection events
     protected String onconnect;
 
@@ -107,67 +112,27 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig {
     private String scope;
 
     protected void checkRegistry() {
-        // for backward compatibility
-        // -Ddubbo.registry.address is now deprecated.
-        if (registries == null || registries.isEmpty()) {
-            String address = ConfigUtils.getProperty("dubbo.registry.address");
-            if (address != null && address.length() > 0) {
-                registries = new ArrayList<RegistryConfig>();
-                String[] as = address.split("\\s*[|]+\\s*");
-                for (String a : as) {
-                    RegistryConfig registryConfig = new RegistryConfig();
-                    registryConfig.setAddress(a);
-                    registries.add(registryConfig);
-                }
-            }
-        }
+        loadRegistriesFromBackwardConfig();
 
-        if (registries == null || registries.isEmpty()) {
-            registries = new ArrayList<>();
-            String registryIds = Environment.getInstance().getConfiguration(null, null).getString("dubbo.registries");
-            if (StringUtils.isNotEmpty(registryIds)) {
-                Arrays.stream(Constants.COMMA_SPLIT_PATTERN.split(registryIds))
-                        .map(regId -> {
-                            RegistryConfig registryConfig = new RegistryConfig();
-                            registryConfig.setId(regId);
-                            return registryConfig;
-                        })
-                        .forEach(registries::add);
-            } else {
-                registries.add(new RegistryConfig());
-            }
-        }
+        convertRegistryLiteralToRegistries();
 
         for (RegistryConfig registryConfig : registries) {
             registryConfig.refresh();
+            if (StringUtils.isNotEmpty(registryConfig.getId())) {
+                registryConfig.setPrefix(Constants.REGISTRIES_SUFFIX);
+                registryConfig.refresh();
+            }
         }
 
         for (RegistryConfig registryConfig : registries) {
             if (!registryConfig.isValid()) {
-                throw new IllegalStateException("No registry config found or it's not a valid config!");
+                throw new IllegalStateException("No registry config found or it's not a valid config! The registry config is: " + registryConfig);
             }
         }
 
         useRegistryForConfigIfNecessary();
     }
 
-    /**
-     * For compatibility purpose, use registry as the default config center if the registry protocol is zookeeper and
-     * there's no config center specified explicitly.
-     */
-    private void useRegistryForConfigIfNecessary() {
-        RegistryConfig registry = registries.get(0);
-        if (registry.isZookeeperProtocol()) {
-            // we use the loading status of DynamicConfiguration to decide whether ConfigCenter has been initiated.
-            if (Environment.getInstance().getDynamicConfiguration() == null) {
-                ConfigCenterConfig configCenterConfig = new ConfigCenterConfig();
-                configCenterConfig.setProtocol(registry.getProtocol());
-                configCenterConfig.setAddress(registry.getAddress());
-                configCenterConfig.init();
-            }
-        }
-    }
-
     @SuppressWarnings("deprecation")
     protected void checkApplication() {
         // for backward compatibility
@@ -182,6 +147,9 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig {
                     "No application config found or it's not a valid config! Please add <dubbo:application name=\"...\" /> to your spring config.");
         }
 
+        ApplicationModel.setApplication(application.getName());
+
+        // backward compatibility
         String wait = ConfigUtils.getProperty(Constants.SHUTDOWN_WAIT_KEY);
         if (wait != null && wait.trim().length() > 0) {
             System.setProperty(Constants.SHUTDOWN_WAIT_KEY, wait.trim());
@@ -418,6 +386,77 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig {
         }
     }
 
+    private void convertRegistryLiteralToRegistries() {
+        if (StringUtils.isEmpty(registryLiteral) && (registries == null || registries.isEmpty())) {
+            Set<String> configedRegistries = new HashSet<>();
+            configedRegistries.addAll(getSubProperties(Environment.getInstance()
+                    .getExternalConfigurationMap(), Constants.REGISTRIES_SUFFIX));
+            configedRegistries.addAll(getSubProperties(Environment.getInstance()
+                    .getAppExternalConfigurationMap(), Constants.REGISTRIES_SUFFIX));
+
+            registryLiteral = String.join(",", configedRegistries);
+        }
+
+        if (StringUtils.isEmpty(registryLiteral)) {
+            if (registries == null || registries.isEmpty()) {
+                registries = new ArrayList<>();
+                registries.add(new RegistryConfig());
+            }
+        } else {
+            String[] arr = Constants.COMMA_SPLIT_PATTERN.split(registryLiteral);
+            if (registries == null || registries.isEmpty()) {
+                registries = new ArrayList<>();
+            }
+            Arrays.stream(arr).forEach(id -> {
+                if (registries.stream().noneMatch(reg -> reg.getId().equals(id))) {
+                    RegistryConfig registryConfig = new RegistryConfig();
+                    registryConfig.setId(id);
+                    registries.add(registryConfig);
+                }
+            });
+            if (registries.size() > arr.length) {
+                throw new IllegalStateException("Too much registries found, the registries assigned to this service are :" + registryLiteral + ", but got " + registries
+                        .size() + " registries!");
+            }
+        }
+
+    }
+
+    private void loadRegistriesFromBackwardConfig() {
+        // for backward compatibility
+        // -Ddubbo.registry.address is now deprecated.
+        if (registries == null || registries.isEmpty()) {
+            String address = ConfigUtils.getProperty("dubbo.registry.address");
+            if (address != null && address.length() > 0) {
+                registries = new ArrayList<RegistryConfig>();
+                String[] as = address.split("\\s*[|]+\\s*");
+                for (String a : as) {
+                    RegistryConfig registryConfig = new RegistryConfig();
+                    registryConfig.setAddress(a);
+                    registries.add(registryConfig);
+                }
+            }
+        }
+    }
+
+    /**
+     * For compatibility purpose, use registry as the default config center if the registry protocol is zookeeper and
+     * there's no config center specified explicitly.
+     */
+    private void useRegistryForConfigIfNecessary() {
+        registries.stream().filter(RegistryConfig::isZookeeperProtocol).findFirst().ifPresent(rc -> {
+            // we use the loading status of DynamicConfiguration to decide whether ConfigCenter has been initiated.
+            Environment.getInstance().getDynamicConfiguration().orElseGet(() -> {
+                ConfigCenterConfig configCenterConfig = new ConfigCenterConfig();
+                configCenterConfig.setProtocol(rc.getProtocol());
+                configCenterConfig.setAddress(rc.getAddress());
+                configCenterConfig.setEnable(false);
+                configCenterConfig.init();
+                return null;
+            });
+        });
+    }
+
     /**
      * @return local
      * @deprecated Replace to <code>getStub()</code>
@@ -557,6 +596,15 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig {
         this.registries = (List<RegistryConfig>) registries;
     }
 
+    @Parameter(excluded = true)
+    public String getRegistryLiteral() {
+        return registryLiteral;
+    }
+
+    public void setRegistry(String registryLiteral) {
+        this.registryLiteral = registryLiteral;
+    }
+
     public MonitorConfig getMonitor() {
         return monitor;
     }
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java
index 6109294..2b3ae11 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java
@@ -62,6 +62,7 @@ public abstract class AbstractServiceConfig extends AbstractInterfaceConfig {
     // access log
     protected String accesslog;
     protected List<ProtocolConfig> protocols;
+    protected String protocolLiteral;
     // provider tag
     protected String tag;
     // max allowed execute times
@@ -174,6 +175,15 @@ public abstract class AbstractServiceConfig extends AbstractInterfaceConfig {
         this.protocols = Arrays.asList(protocol);
     }
 
+    @Parameter(excluded = true)
+    public String getProtocolLiteral() {
+        return protocolLiteral;
+    }
+
+    public void setProtocol(String protocolLiteral) {
+        this.protocolLiteral = protocolLiteral;
+    }
+
     public String getAccesslog() {
         return accesslog;
     }
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java
index 9710515..37ae811 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java
@@ -62,6 +62,7 @@ public class ApplicationConfig extends AbstractConfig {
 
     // registry centers
     private List<RegistryConfig> registries;
+    private String registryLiteral;
 
     // monitor center
     private MonitorConfig monitor;
@@ -177,6 +178,15 @@ public class ApplicationConfig extends AbstractConfig {
         this.registries = (List<RegistryConfig>) registries;
     }
 
+    @Parameter(excluded = true)
+    public String getRegistryLiteral() {
+        return registryLiteral;
+    }
+
+    public void setRegistry(String registryLiteral) {
+        this.registryLiteral = registryLiteral;
+    }
+
     public MonitorConfig getMonitor() {
         return monitor;
     }
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java
index dbe3821..7aee0ba 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java
@@ -31,11 +31,14 @@ import java.io.StringReader;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Properties;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
  *
  */
 public class ConfigCenterConfig extends AbstractConfig {
+    private AtomicBoolean inited = new AtomicBoolean(false);
+
     private String protocol;
     private String address;
     private String env;
@@ -45,7 +48,7 @@ public class ConfigCenterConfig extends AbstractConfig {
     private String username;
     private String password;
     private Long timeout = 3000L;
-    private Boolean priority = true;
+    private Boolean enable = true;
     private Boolean check = true;
 
     private String appname;
@@ -62,6 +65,10 @@ public class ConfigCenterConfig extends AbstractConfig {
     }
 
     public void init() {
+        if (!inited.compareAndSet(false, true)) {
+            return;
+        }
+
         // give jvm properties the chance to override local configs, e.g., -Ddubbo.configcenter.config.priority
         refresh();
         // try to use registryConfig as the default configcenter, only applies to zookeeper.
@@ -85,7 +92,7 @@ public class ConfigCenterConfig extends AbstractConfig {
                         );
             }
             try {
-                Environment.getInstance().setConfigCenterFirst(priority);
+                Environment.getInstance().setConfigCenterFirst(enable);
                 Environment.getInstance().updateExternalConfigurationMap(parseProperties(configContent));
                 Environment.getInstance().updateAppExternalConfigurationMap(parseProperties(appConfigContent));
             } catch (IOException e) {
@@ -139,6 +146,16 @@ public class ConfigCenterConfig extends AbstractConfig {
         return map;
     }
 
+    public void setExternalConfig(Map<String, String> externalConfiguration) {
+        Environment.getInstance().setExternalConfigMap(externalConfiguration);
+        inited.set(true);
+    }
+
+    public void setAppExternalConfig(Map<String, String> appExternalConfiguration) {
+        Environment.getInstance().setAppExternalConfigMap(appExternalConfiguration);
+        inited.set(true);
+    }
+
     public String getProtocol() {
         return protocol;
     }
@@ -201,13 +218,13 @@ public class ConfigCenterConfig extends AbstractConfig {
         this.check = check;
     }
 
-    @Parameter(key = Constants.CONFIG_PRIORITY_KEY)
-    public Boolean isPriority() {
-        return priority;
+    @Parameter(key = Constants.CONFIG_ENABLE_KEY)
+    public Boolean getEnable() {
+        return enable;
     }
 
-    public void setPriority(Boolean priority) {
-        this.priority = priority;
+    public void setEnable(Boolean enable) {
+        this.enable = enable;
     }
 
     public String getUsername() {
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
index 9b3380d..c304fc8 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
@@ -555,7 +555,7 @@ public class ReferenceConfig<T> extends AbstractReferenceConfig {
     @Override
     @Parameter(excluded = true)
     public String getPrefix() {
-        return Constants.DUBBO + ".reference";
+        return Constants.DUBBO + ".reference." + interfaceName;
     }
 
 }
diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
index dd86532..fc5d251 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
@@ -91,6 +91,7 @@ public class ServiceConfig<T> extends AbstractServiceConfig {
     // method configuration
     private List<MethodConfig> methods;
     private ProviderConfig provider;
+    private String providerLiteral;
     private transient volatile boolean exported;
 
     private transient volatile boolean unexported;
@@ -726,31 +727,56 @@ public class ServiceConfig<T> extends AbstractServiceConfig {
     }
 
     private void checkProtocol() {
-        if ((protocols == null || protocols.isEmpty())
-                && provider != null) {
+        if ((protocols == null || protocols.isEmpty()) && provider != null) {
             setProtocols(provider.getProtocols());
         }
-        // backward compatibility
-        if (protocols == null || protocols.isEmpty()) {
-            //check 'dubbo.protocols=dubboProtocolId,hessianProtocolId' and decide if we need multiple protocols
-            String protocolIds = Environment.getInstance().getConfiguration(null, null).getString("dubbo.protocols");
-            if (StringUtils.isNotEmpty(protocolIds)) {
-                Arrays.stream(Constants.COMMA_SPLIT_PATTERN.split(protocolIds))
-                        .map(pId -> {
-                            ProtocolConfig protocolConfig = new ProtocolConfig();
-                            protocolConfig.setId(pId);
-                            return protocolConfig;
-                        })
-                        .forEach(protocols::add);
-            } else {
-                setProtocol(new ProtocolConfig());
-            }
-        }
+
+        convertProtocolLiteralToProtocols();
+
         for (ProtocolConfig protocolConfig : protocols) {
             if (StringUtils.isEmpty(protocolConfig.getName())) {
                 protocolConfig.setName(Constants.DUBBO_VERSION_KEY);
             }
             protocolConfig.refresh();
+            if (StringUtils.isNotEmpty(protocolConfig.getId())) {
+                protocolConfig.setPrefix("dubbo.protocols.");
+                protocolConfig.refresh();
+            }
+        }
+    }
+
+    private void convertProtocolLiteralToProtocols() {
+        if (StringUtils.isEmpty(protocolLiteral) && (protocols == null || protocols.isEmpty())) {
+            List<String> configedProtocols = new ArrayList<>();
+            configedProtocols.addAll(getSubProperties(Environment.getInstance()
+                    .getExternalConfigurationMap(), Constants.PROTOCOLS_SUFFIX));
+            configedProtocols.addAll(getSubProperties(Environment.getInstance()
+                    .getAppExternalConfigurationMap(), Constants.PROTOCOLS_SUFFIX));
+
+            protocolLiteral = String.join(",", configedProtocols);
+        }
+
+        if (StringUtils.isEmpty(protocolLiteral)) {
+            if (protocols == null || protocols.isEmpty()) {
+                protocols = new ArrayList<>();
+                protocols.add(new ProtocolConfig());
+            }
+        } else {
+            String[] arr = Constants.COMMA_SPLIT_PATTERN.split(protocolLiteral);
+            if (protocols == null || protocols.isEmpty()) {
+                protocols = new ArrayList<>();
+            }
+            Arrays.stream(arr).forEach(id -> {
+                if (protocols.stream().noneMatch(prot -> prot.getId().equals(id))) {
+                    ProtocolConfig protocolConfig = new ProtocolConfig();
+                    protocolConfig.setId(id);
+                    protocols.add(protocolConfig);
+                }
+            });
+            if (protocols.size() > arr.length) {
+                throw new IllegalStateException("Too much protocols found, the protocols comply to this service are :" + protocolLiteral + " but got " + protocols
+                        .size() + " registries!");
+            }
         }
     }
 
@@ -837,6 +863,15 @@ public class ServiceConfig<T> extends AbstractServiceConfig {
         this.provider = provider;
     }
 
+    @Parameter(excluded = true)
+    public String getProviderLiteral() {
+        return providerLiteral;
+    }
+
+    public void setProvider(String providerLiteral) {
+        this.providerLiteral = providerLiteral;
+    }
+
     public String getGeneric() {
         return generic;
     }
@@ -888,7 +923,7 @@ public class ServiceConfig<T> extends AbstractServiceConfig {
         if (group != null && group.length() > 0) {
             buf.append(group).append("/");
         }
-        buf.append(interfaceName);
+        buf.append(StringUtils.isNotEmpty(path) ? path : interfaceName);
         if (version != null && version.length() > 0) {
             buf.append(":").append(version);
         }
@@ -898,6 +933,6 @@ public class ServiceConfig<T> extends AbstractServiceConfig {
     @Override
     @Parameter(excluded = true)
     public String getPrefix() {
-        return Constants.DUBBO + ".service";
+        return Constants.DUBBO + ".service." + interfaceName;
     }
 }
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java
index b50433a..85a9301 100644
--- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java
+++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java
@@ -293,7 +293,7 @@ public class AbstractConfigTest {
             external.put("dubbo.override.key", "external");
             // @Parameter(key="key2", useKeyAsProperty=true)
             external.put("dubbo.override.key2", "external");
-            Environment.getInstance().setExternalConfig(external);
+            Environment.getInstance().setExternalConfigMap(external);
 
             System.setProperty("dubbo.override.address", "system://127.0.0.1:2181");
             System.setProperty("dubbo.override.protocol", "system");
@@ -348,7 +348,7 @@ public class AbstractConfigTest {
     @Test
     public void testRefreshProperties() {
         try {
-            Environment.getInstance().setExternalConfig(new HashMap<>());
+            Environment.getInstance().setExternalConfigMap(new HashMap<>());
             OverrideConfig overrideConfig = new OverrideConfig();
             overrideConfig.setAddress("override-config://127.0.0.1:2181");
             overrideConfig.setProtocol("override-config");
@@ -384,7 +384,7 @@ public class AbstractConfigTest {
             external.put("dubbo.override.key", "external");
             // @Parameter(key="key2", useKeyAsProperty=true)
             external.put("dubbo.override.key2", "external");
-            Environment.getInstance().setExternalConfig(external);
+            Environment.getInstance().setExternalConfigMap(external);
 
             overrideConfig.refresh();
 
@@ -418,7 +418,7 @@ public class AbstractConfigTest {
             external.put("dubbo.override.key", "external");
             // @Parameter(key="key2", useKeyAsProperty=true)
             external.put("dubbo.override.key2", "external");
-            Environment.getInstance().setExternalConfig(external);
+            Environment.getInstance().setExternalConfigMap(external);
 
             ConfigCenterConfig configCenter = new ConfigCenterConfig();
             configCenter.init();
diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java
index 6b5782e..a0ddd87 100644
--- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java
+++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java
@@ -16,11 +16,13 @@
  */
 package org.apache.dubbo.config.spring;
 
+import org.apache.dubbo.common.utils.StringUtils;
 import org.apache.dubbo.config.ApplicationConfig;
 import org.apache.dubbo.config.ConfigCenterConfig;
 import org.apache.dubbo.config.RegistryConfig;
 import org.apache.dubbo.config.spring.extension.SpringExtensionFactory;
 import org.apache.dubbo.config.support.Parameter;
+
 import org.springframework.beans.factory.BeanFactoryUtils;
 import org.springframework.beans.factory.DisposableBean;
 import org.springframework.beans.factory.InitializingBean;
@@ -46,7 +48,7 @@ public class ConfigCenterBean extends ConfigCenterConfig implements Initializing
 
     private transient ApplicationContext applicationContext;
 
-    private Boolean auto = false;
+    private Boolean fromSpring = false;
 
     @Override
     public void setApplicationContext(ApplicationContext applicationContext) {
@@ -92,7 +94,7 @@ public class ConfigCenterBean extends ConfigCenterConfig implements Initializing
             }
         }
 
-        if (!auto) {
+        if (!fromSpring) {
             this.init();
         }
     }
@@ -104,11 +106,11 @@ public class ConfigCenterBean extends ConfigCenterConfig implements Initializing
 
     @Override
     public void setEnvironment(Environment environment) {
-        if (auto) {
+        if (fromSpring) {
             Map<String, String> externalProperties = getConfigurations(getConfigfile(), environment);
-            Map<String, String> appExternalProperties = getConfigurations("application." + getConfigfile(), environment);
-            org.apache.dubbo.common.config.Environment.getInstance().setExternalConfig(externalProperties);
-            org.apache.dubbo.common.config.Environment.getInstance().setAppExternalConfig(appExternalProperties);
+            Map<String, String> appExternalProperties = getConfigurations(StringUtils.isNotEmpty(getLocalconfigfile()) ? getLocalconfigfile() : ("application." + getConfigfile()), environment);
+            org.apache.dubbo.common.config.Environment.getInstance().setExternalConfigMap(externalProperties);
+            org.apache.dubbo.common.config.Environment.getInstance().setAppExternalConfigMap(appExternalProperties);
             this.init();
         }
     }
@@ -142,11 +144,11 @@ public class ConfigCenterBean extends ConfigCenterConfig implements Initializing
     }
 
     @Parameter(excluded = true)
-    public boolean isAuto() {
-        return auto;
+    public Boolean getFromSpring() {
+        return fromSpring;
     }
 
-    public void setAuto(boolean auto) {
-        this.auto = auto;
+    public void setFromSpring(Boolean fromSpring) {
+        this.fromSpring = fromSpring;
     }
 }
diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java
index b6ac23b..b1b360e 100644
--- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java
+++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java
@@ -16,6 +16,8 @@
  */
 package org.apache.dubbo.config.spring;
 
+import org.apache.dubbo.common.Constants;
+import org.apache.dubbo.common.utils.StringUtils;
 import org.apache.dubbo.config.ApplicationConfig;
 import org.apache.dubbo.config.ConsumerConfig;
 import org.apache.dubbo.config.MetadataReportConfig;
@@ -36,6 +38,7 @@ import org.springframework.context.ApplicationContext;
 import org.springframework.context.ApplicationContextAware;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 
@@ -138,15 +141,35 @@ public class ReferenceBean<T> extends ReferenceConfig<T> implements FactoryBean,
                 }
             }
         }
+
+        if (StringUtils.isEmpty(getRegistryLiteral())) {
+            if (getApplication() != null && StringUtils.isNotEmpty(getApplication().getRegistryLiteral())) {
+                setRegistry(getApplication().getRegistryLiteral());
+            }
+            if (getConsumer() != null && StringUtils.isNotEmpty(getConsumer().getRegistryLiteral())) {
+                setRegistry(getConsumer().getRegistryLiteral());
+            }
+        }
+
         if ((getRegistries() == null || getRegistries().isEmpty())
                 && (getConsumer() == null || getConsumer().getRegistries() == null || getConsumer().getRegistries().isEmpty())
                 && (getApplication() == null || getApplication().getRegistries() == null || getApplication().getRegistries().isEmpty())) {
             Map<String, RegistryConfig> registryConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, RegistryConfig.class, false, false);
             if (registryConfigMap != null && registryConfigMap.size() > 0) {
                 List<RegistryConfig> registryConfigs = new ArrayList<>();
-                for (RegistryConfig config : registryConfigMap.values()) {
-                    if (config.isDefault() == null || config.isDefault()) {
-                        registryConfigs.add(config);
+                if (StringUtils.isNotEmpty(registryLiteral)) {
+                    Arrays.stream(Constants.COMMA_SPLIT_PATTERN.split(registryLiteral)).forEach(registryLiteral -> {
+                        if (registryConfigMap.containsKey(registryLiteral)) {
+                            registryConfigs.add(registryConfigMap.get(registryLiteral));
+                        }
+                    });
+                }
+
+                if (registryConfigs.isEmpty()) {
+                    for (RegistryConfig config : registryConfigMap.values()) {
+                        if (StringUtils.isEmpty(registryLiteral)) {
+                            registryConfigs.add(config);
+                        }
                     }
                 }
                 if (!registryConfigs.isEmpty()) {
@@ -154,6 +177,7 @@ public class ReferenceBean<T> extends ReferenceConfig<T> implements FactoryBean,
                 }
             }
         }
+
         if (getMetadataReportConfig() == null) {
             Map<String, MetadataReportConfig> metadataReportConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, MetadataReportConfig.class, false, false);
             if (metadataReportConfigMap != null && metadataReportConfigMap.size() == 1) {
diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java
index 74d06df..6d83374 100644
--- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java
+++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java
@@ -16,6 +16,8 @@
  */
 package org.apache.dubbo.config.spring;
 
+import org.apache.dubbo.common.Constants;
+import org.apache.dubbo.common.utils.StringUtils;
 import org.apache.dubbo.config.ApplicationConfig;
 import org.apache.dubbo.config.MetadataReportConfig;
 import org.apache.dubbo.config.ModuleConfig;
@@ -39,6 +41,7 @@ import org.springframework.context.ApplicationListener;
 import org.springframework.context.event.ContextRefreshedEvent;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 
@@ -172,15 +175,35 @@ public class ServiceBean<T> extends ServiceConfig<T> implements InitializingBean
                 }
             }
         }
+
+        if (StringUtils.isEmpty(getRegistryLiteral())) {
+            if (getApplication() != null && StringUtils.isNotEmpty(getApplication().getRegistryLiteral())) {
+                setRegistry(getApplication().getRegistryLiteral());
+            }
+            if (getProvider() != null && StringUtils.isNotEmpty(getProvider().getRegistryLiteral())) {
+                setRegistry(getProvider().getRegistryLiteral());
+            }
+        }
+
         if ((getRegistries() == null || getRegistries().isEmpty())
                 && (getProvider() == null || getProvider().getRegistries() == null || getProvider().getRegistries().isEmpty())
                 && (getApplication() == null || getApplication().getRegistries() == null || getApplication().getRegistries().isEmpty())) {
             Map<String, RegistryConfig> registryConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, RegistryConfig.class, false, false);
             if (registryConfigMap != null && registryConfigMap.size() > 0) {
-                List<RegistryConfig> registryConfigs = new ArrayList<RegistryConfig>();
-                for (RegistryConfig config : registryConfigMap.values()) {
-                    if (config.isDefault() == null || config.isDefault()) {
-                        registryConfigs.add(config);
+                List<RegistryConfig> registryConfigs = new ArrayList<>();
+                if (StringUtils.isNotEmpty(registryLiteral)) {
+                    Arrays.stream(Constants.COMMA_SPLIT_PATTERN.split(registryLiteral)).forEach(registryLiteral -> {
+                        if (registryConfigMap.containsKey(registryLiteral)) {
+                            registryConfigs.add(registryConfigMap.get(registryLiteral));
+                        }
+                    });
+                }
+
+                if (registryConfigs.isEmpty()) {
+                    for (RegistryConfig config : registryConfigMap.values()) {
+                        if (StringUtils.isEmpty(registryLiteral)) {
+                            registryConfigs.add(config);
+                        }
                     }
                 }
                 if (!registryConfigs.isEmpty()) {
@@ -225,16 +248,35 @@ public class ServiceBean<T> extends ServiceConfig<T> implements InitializingBean
                 }
             }
         }
+
+        if (StringUtils.isEmpty(getProtocolLiteral())) {
+            if (getProvider() != null && StringUtils.isNotEmpty(getProvider().getProtocolLiteral())) {
+                setProtocol(getProvider().getProtocolLiteral());
+            }
+        }
+
         if ((getProtocols() == null || getProtocols().isEmpty())
                 && (getProvider() == null || getProvider().getProtocols() == null || getProvider().getProtocols().isEmpty())) {
             Map<String, ProtocolConfig> protocolConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false);
             if (protocolConfigMap != null && protocolConfigMap.size() > 0) {
                 List<ProtocolConfig> protocolConfigs = new ArrayList<ProtocolConfig>();
-                for (ProtocolConfig config : protocolConfigMap.values()) {
-                    if (config.isDefault() == null || config.isDefault()) {
-                        protocolConfigs.add(config);
+                if (StringUtils.isNotEmpty(getProtocolLiteral())) {
+                    Arrays.stream(Constants.COMMA_SPLIT_PATTERN.split(getProtocolLiteral()))
+                            .forEach(protocolLiteral -> {
+                                if (protocolConfigMap.containsKey(protocolLiteral)) {
+                                    protocolConfigs.add(protocolConfigMap.get(protocolLiteral));
+                                }
+                            });
+                }
+
+                if (protocolConfigs.isEmpty()) {
+                    for (ProtocolConfig config : protocolConfigMap.values()) {
+                        if (StringUtils.isEmpty(protocolLiteral)) {
+                            protocolConfigs.add(config);
+                        }
                     }
                 }
+
                 if (!protocolConfigs.isEmpty()) {
                     super.setProtocols(protocolConfigs);
                 }
diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java
index e154baf..cd5ddce 100644
--- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java
+++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java
@@ -27,6 +27,7 @@ import org.apache.dubbo.config.ProviderConfig;
 import org.apache.dubbo.config.RegistryConfig;
 import org.apache.dubbo.config.RegistryDataConfig;
 import org.apache.dubbo.config.spring.ConfigCenterBean;
+
 import org.springframework.context.annotation.Configuration;
 
 /**
@@ -57,8 +58,7 @@ public class DubboConfigConfiguration {
             @EnableDubboConfigBinding(prefix = "dubbo.protocol", type = ProtocolConfig.class),
             @EnableDubboConfigBinding(prefix = "dubbo.monitor", type = MonitorConfig.class),
             @EnableDubboConfigBinding(prefix = "dubbo.provider", type = ProviderConfig.class),
-            @EnableDubboConfigBinding(prefix = "dubbo.consumer", type = ConsumerConfig.class),
-            @EnableDubboConfigBinding(prefix = "dubbo.configcenter", type = ConfigCenterBean.class),
+            @EnableDubboConfigBinding(prefix = "dubbo.consumer", type = ConsumerConfig.class), @EnableDubboConfigBinding(prefix = "dubbo.config-center", type = ConfigCenterBean.class),
             @EnableDubboConfigBinding(prefix = "dubbo.registrydata", type = RegistryDataConfig.class),
             @EnableDubboConfigBinding(prefix = "dubbo.metadatareport", type = MetadataReportConfig.class)
     })
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 e38d1af..58e92b0 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
@@ -17,7 +17,6 @@
 package org.apache.dubbo.config.spring.schema;
 
 import org.apache.dubbo.common.Constants;
-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.ReflectUtils;
@@ -30,7 +29,6 @@ import org.apache.dubbo.config.ProviderConfig;
 import org.apache.dubbo.config.RegistryConfig;
 import org.apache.dubbo.config.spring.ReferenceBean;
 import org.apache.dubbo.config.spring.ServiceBean;
-import org.apache.dubbo.rpc.Protocol;
 
 import org.springframework.beans.PropertyValue;
 import org.springframework.beans.factory.config.BeanDefinition;
@@ -166,12 +164,8 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser {
                                 RegistryConfig registryConfig = new RegistryConfig();
                                 registryConfig.setAddress(RegistryConfig.NO_AVAILABLE);
                                 beanDefinition.getPropertyValues().addPropertyValue(property, registryConfig);
-                            } else if ("registry".equals(property) && value.indexOf(',') != -1) {
-                                parseMultiRef("registries", value, beanDefinition, parserContext);
-                            } else if ("provider".equals(property) && value.indexOf(',') != -1) {
-                                parseMultiRef("providers", value, beanDefinition, parserContext);
-                            } else if ("protocol".equals(property) && value.indexOf(',') != -1) {
-                                parseMultiRef("protocols", value, beanDefinition, parserContext);
+                            } else if ("provider".equals(property) || "protocol".equals(property) || "registry".equals(property)) {
+                                beanDefinition.getPropertyValues().addPropertyValue(property, value);
                             } else {
                                 Object reference;
                                 if (isPrimitive(type)) {
@@ -185,17 +179,6 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser {
                                         value = null;
                                     }
                                     reference = value;
-                                } else if ("protocol".equals(property)
-                                        && ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(value)
-                                        && (!parserContext.getRegistry().containsBeanDefinition(value)
-                                        || !ProtocolConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) {
-                                    if ("dubbo:provider".equals(element.getTagName())) {
-                                        logger.warn("Recommended replace <dubbo:provider protocol=\"" + value + "\" ... /> to <dubbo:protocol name=\"" + value + "\" ... />");
-                                    }
-                                    // backward compatibility
-                                    ProtocolConfig protocol = new ProtocolConfig();
-                                    protocol.setName(value);
-                                    reference = protocol;
                                 } else if ("onreturn".equals(property)) {
                                     int index = value.lastIndexOf(".");
                                     String returnRef = value.substring(0, index);
@@ -256,23 +239,6 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser {
                 || cls == String.class || cls == Date.class || cls == Class.class;
     }
 
-    @SuppressWarnings("unchecked")
-    private static void parseMultiRef(String property, String value, RootBeanDefinition beanDefinition,
-                                      ParserContext parserContext) {
-        String[] values = value.split("\\s*[,]+\\s*");
-        ManagedList list = null;
-        for (int i = 0; i < values.length; i++) {
-            String v = values[i];
-            if (v != null && v.length() > 0) {
-                if (list == null) {
-                    list = new ManagedList();
-                }
-                list.add(new RuntimeBeanReference(v));
-            }
-        }
-        beanDefinition.getPropertyValues().addPropertyValue(property, list);
-    }
-
     private static void parseNested(Element element, ParserContext parserContext, Class<?> beanClass, boolean required, String tag, String property, String ref, BeanDefinition beanDefinition) {
         NodeList nodeList = element.getChildNodes();
         if (nodeList != null && nodeList.getLength() > 0) {
diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandler.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandler.java
index afbc26b..d4ea6ed 100644
--- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandler.java
+++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandler.java
@@ -46,7 +46,7 @@ public class DubboNamespaceHandler extends NamespaceHandlerSupport {
         registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true));
         registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true));
         registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true));
-        registerBeanDefinitionParser("configcenter", new DubboBeanDefinitionParser(ConfigCenterBean.class, true));
+        registerBeanDefinitionParser("config-center", new DubboBeanDefinitionParser(ConfigCenterBean.class, true));
         registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true));
         registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true));
         registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true));
diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd
index f68a47d..87f2f11 100644
--- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd
+++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd
@@ -659,7 +659,7 @@
                 <xsd:documentation><![CDATA[ The request timeout. ]]></xsd:documentation>
             </xsd:annotation>
         </xsd:attribute>
-        <xsd:attribute name="priority" type="xsd:boolean" use="optional">
+        <xsd:attribute name="enable" type="xsd:boolean" use="optional">
             <xsd:annotation>
                 <xsd:documentation>
                     <![CDATA[ Whether the configs from config center has the highest priority. ]]></xsd:documentation>
@@ -1343,7 +1343,7 @@
         </xsd:annotation>
     </xsd:element>
 
-    <xsd:element name="configcenter" type="configCenterType">
+    <xsd:element name="config-center" type="configCenterType">
         <xsd:annotation>
             <xsd:documentation><![CDATA[ The config center config ]]></xsd:documentation>
         </xsd:annotation>
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 294c1b5..c36e59c 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
@@ -653,7 +653,7 @@
                 <xsd:documentation><![CDATA[ The request timeout. ]]></xsd:documentation>
             </xsd:annotation>
         </xsd:attribute>
-        <xsd:attribute name="priority" type="xsd:boolean" use="optional">
+        <xsd:attribute name="enable" type="xsd:boolean" use="optional">
             <xsd:annotation>
                 <xsd:documentation>
                     <![CDATA[ Whether the configs from config center has the highest priority. ]]></xsd:documentation>
@@ -1332,7 +1332,7 @@
         </xsd:annotation>
     </xsd:element>
 
-    <xsd:element name="configcenter" type="configCenterType">
+    <xsd:element name="config-center" type="configCenterType">
         <xsd:annotation>
             <xsd:documentation><![CDATA[ The config center config ]]></xsd:documentation>
         </xsd:annotation>


[incubator-dubbo] 06/07: resolve conflicts

Posted by li...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

liujun pushed a commit to branch dev-metadata
in repository https://gitbox.apache.org/repos/asf/incubator-dubbo.git

commit e86b89c49dabc23ab3d84c6317309ded3342aef8
Merge: e425767 368a59e
Author: ken.lj <ke...@gmail.com>
AuthorDate: Mon Dec 17 14:55:43 2018 +0800

    resolve conflicts

 .../java/org/apache/dubbo/common/Constants.java    |  2 +
 .../apache/dubbo/config/MetadataReportConfig.java  | 13 ++++
 .../configcenter/AbstractDynamicConfiguration.java |  3 +-
 .../definition/builder/CollectionTypeBuilder.java  |  1 -
 .../definition/builder/MapTypeBuilder.java         |  1 -
 .../dubbo/metadata/definition/MetadataTest.java    | 11 ----
 .../definition/ServiceDefinitionBuildderTest.java  | 16 +++++
 .../metadata/definition/common/TestService.java    |  5 --
 .../metadata/definition/service/ComplexObject.java | 16 +++++
 .../identifier/ConsumerMetadataIdentifier.java     | 31 ---------
 .../metadata/identifier/MetadataIdentifier.java    | 46 ++++++++++---
 .../identifier/ProviderMetadataIdentifier.java     | 17 -----
 .../integration/MetadataReportService.java         | 12 ++--
 .../dubbo/metadata/store/MetadataReport.java       |  7 +-
 .../metadata/support/AbstractMetadataReport.java   | 67 +++++++++++++------
 .../integration/InterfaceNameTestService.java      | 16 +++++
 .../integration/InterfaceNameTestService2.java     | 16 +++++
 .../integration/MetadataReportServiceTest.java     | 77 +++++++++++-----------
 .../metadata/integration/RetryTestService.java     | 16 +++++
 .../store/test/JTestMetadataReport4Test.java       | 14 ++--
 .../support/AbstractMetadataReportFactoryTest.java | 23 +++++--
 .../support/AbstractMetadataReportTest.java        | 56 ++++++++++------
 .../metadata/store/redis/RedisMetadataReport.java  |  7 +-
 .../store/redis/RedisMetadataReportTest.java       | 27 +++++---
 .../store/zookeeper/ZookeeperMetadataReport.java   |  6 +-
 .../zookeeper/ZookeeperMetadataReportTest.java     | 27 ++++----
 26 files changed, 328 insertions(+), 205 deletions(-)

diff --cc dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java
index 98413c5,cc1461a..8ec7566
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java
@@@ -730,11 -730,11 +730,13 @@@ public class Constants 
  
      public static final String RETRY_PERIOD_KEY = "retry-period";
  
+     public static final String SYNC_REPORT_KEY = "sync-report";
+ 
      public static final String CYCLE_REPORT_KEY = "cycle-report";
  
 -    public static final String API_VERSION_KEY = "apiVersion";
 +    public static final String CONFIG_VERSION_KEY = "configVersion";
 +
 +    public static final String COMPATIBLE_CONFIG_KEY = "compatible_config";
      // package version in the manifest
      public static final String SPECIFICATION_VERSION_KEY = "specVersion";
  


[incubator-dubbo] 07/07: use asyncInterfaceClass

Posted by li...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

liujun pushed a commit to branch dev-metadata
in repository https://gitbox.apache.org/repos/asf/incubator-dubbo.git

commit f92f00f8d9e2f0e49100f15beb7e2e4a589a840e
Author: ken.lj <ke...@gmail.com>
AuthorDate: Mon Dec 17 14:56:47 2018 +0800

    use asyncInterfaceClass
---
 .../src/main/java/org/apache/dubbo/config/ReferenceConfig.java          | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
index c304fc8..2389b33 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
@@ -439,7 +439,7 @@ public class ReferenceConfig<T> extends AbstractReferenceConfig {
         this.asyncInterfaceClass = interfaceClass;
         this.interfaceClass = target;
         setInterface(this.interfaceClass.getName());
-        map.put(Constants.INTERFACES, interfaceClass.getName());
+        map.put(Constants.INTERFACES, asyncInterfaceClass.getName());
     }
 
 


[incubator-dubbo] 05/07: fix problem of governance: configurator & router

Posted by li...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

liujun pushed a commit to branch dev-metadata
in repository https://gitbox.apache.org/repos/asf/incubator-dubbo.git

commit e4257677e9b276c8e73c01b246f6617cc92af1d7
Author: ken.lj <ke...@gmail.com>
AuthorDate: Mon Dec 17 14:50:47 2018 +0800

    fix problem of governance: configurator & router
---
 .../config/AbstractConfigConditionRouter.java         | 12 ++++++------
 .../condition/config/model/ConditionRouterRule.java   | 10 +++++-----
 .../condition/config/model/ConditionRuleParser.java   |  2 +-
 .../integration/AbstractConfiguratorListener.java     | 19 +++++++++++++++++--
 .../dubbo/registry/integration/RegistryDirectory.java |  4 ----
 .../dubbo/registry/integration/RegistryProtocol.java  |  2 --
 6 files changed, 29 insertions(+), 20 deletions(-)

diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AbstractConfigConditionRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AbstractConfigConditionRouter.java
index 26fad9a..5f27a29 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AbstractConfigConditionRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AbstractConfigConditionRouter.java
@@ -79,15 +79,15 @@ public abstract class AbstractConfigConditionRouter extends AbstractRouter imple
 
     @Override
     public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
-        if (CollectionUtils.isEmpty(invokers) || conditionRouters.size() == 0 || !isEnabled()) {
+        if (CollectionUtils.isEmpty(invokers) || conditionRouters.size() == 0) {
             return invokers;
         }
 
-        if (isRuleEnabled()) {
-            for (Router router : conditionRouters) {
-                invokers = router.route(invokers, url, invocation);
-            }
+        // We will check enabled status inside each router.
+        for (Router router : conditionRouters) {
+            invokers = router.route(invokers, url, invocation);
         }
+
         return invokers;
     }
 
@@ -129,7 +129,7 @@ public abstract class AbstractConfigConditionRouter extends AbstractRouter imple
                 routers.add(subRouter);
             });
 
-            BlackWhiteListRule blackWhiteList = rule.getBlackWhiteListRule();
+            BlackWhiteListRule blackWhiteList = rule.getBlackWhiteList();
             if (blackWhiteList != null && blackWhiteList.isValid()) {
                 blackWhiteList.getConditions().forEach(condition -> {
                     // All sub rules have the same force, runtime value.
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java
index 97518b7..ede6913 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java
@@ -27,7 +27,7 @@ public class ConditionRouterRule extends AbstractRouterRule {
     public ConditionRouterRule() {
     }
 
-    private BlackWhiteListRule blackWhiteListRule;
+    private BlackWhiteListRule blackWhiteList;
     private List<String> conditions;
 
     public List<String> getConditions() {
@@ -38,11 +38,11 @@ public class ConditionRouterRule extends AbstractRouterRule {
         this.conditions = conditions;
     }
 
-    public BlackWhiteListRule getBlackWhiteListRule() {
-        return blackWhiteListRule;
+    public BlackWhiteListRule getBlackWhiteList() {
+        return blackWhiteList;
     }
 
-    public void setBlackWhiteListRule(BlackWhiteListRule blackWhiteListRule) {
-        this.blackWhiteListRule = blackWhiteListRule;
+    public void setBlackWhiteList(BlackWhiteListRule blackWhiteList) {
+        this.blackWhiteList = blackWhiteList;
     }
 }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java
index 074c1fc..4c6a04b 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java
@@ -47,7 +47,7 @@ public class ConditionRuleParser {
             rule.setValid(false);
         }
 
-        BlackWhiteListRule blackWhiteList = rule.getBlackWhiteListRule();
+        BlackWhiteListRule blackWhiteList = rule.getBlackWhiteList();
         if (blackWhiteList != null && CollectionUtils.isEmpty(blackWhiteList.getConditions())) {
             blackWhiteList.setValid(false);
         }
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java
index f569eb5..3d0268d 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java
@@ -16,7 +16,6 @@
  */
 package org.apache.dubbo.registry.integration;
 
-import org.apache.dubbo.common.Constants;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.logger.Logger;
 import org.apache.dubbo.common.logger.LoggerFactory;
@@ -24,9 +23,19 @@ import org.apache.dubbo.configcenter.ConfigChangeEvent;
 import org.apache.dubbo.configcenter.ConfigChangeType;
 import org.apache.dubbo.configcenter.ConfigurationListener;
 import org.apache.dubbo.rpc.cluster.configurator.parser.ConfigParser;
+import org.apache.dubbo.rpc.model.ApplicationModel;
 
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
+
+import static org.apache.dubbo.common.Constants.ANYHOST_VALUE;
+import static org.apache.dubbo.common.Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY;
+import static org.apache.dubbo.common.Constants.CATEGORY_KEY;
+import static org.apache.dubbo.common.Constants.CONFIGURATORS_SUFFIX;
+import static org.apache.dubbo.common.Constants.DYNAMIC_CONFIGURATORS_CATEGORY;
+import static org.apache.dubbo.common.Constants.EMPTY_PROTOCOL;
 
 /**
  *
@@ -44,7 +53,13 @@ public abstract class AbstractConfiguratorListener implements ConfigurationListe
         List<URL> urls;
         if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
             urls = new ArrayList<>();
-            urls.add(new URL(Constants.EMPTY_PROTOCOL, Constants.ANYHOST_VALUE, 0));
+            Map<String, String> map = new HashMap<>(1);
+            if (event.getKey().endsWith(ApplicationModel.getApplication() + CONFIGURATORS_SUFFIX)) {
+                map.put(CATEGORY_KEY, APP_DYNAMIC_CONFIGURATORS_CATEGORY);
+            } else {
+                map.put(CATEGORY_KEY, DYNAMIC_CONFIGURATORS_CATEGORY);
+            }
+            urls.add(new URL(EMPTY_PROTOCOL, ANYHOST_VALUE, 0, map));
         } else {
             try {
                 // parseConfigurators will recognize app/service config automatically.
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java
index c564a47..527f6b6 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java
@@ -135,8 +135,6 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
         this.multiGroup = group != null && ("*".equals(group) || group.contains(","));
         String methods = queryMap.get(Constants.METHODS_KEY);
         this.serviceMethods = methods == null ? null : Constants.COMMA_SPLIT_PATTERN.split(methods);
-
-        consumerConfigurationListener.addNotifyListener(this);
     }
 
     /**
@@ -828,7 +826,6 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
 
         @Override
         protected void notifyOverrides(List<URL> urls) {
-            urls.forEach(u -> u.addParameter(CATEGORY_KEY, DYNAMIC_CONFIGURATORS_CATEGORY));
             RegistryDirectory.this.notify(urls);
         }
     }
@@ -863,7 +860,6 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
 
         @Override
         protected void notifyOverrides(List<URL> urls) {
-            urls.forEach(u -> u.addParameter(CATEGORY_KEY, APP_DYNAMIC_CONFIGURATORS_CATEGORY));
             listeners.forEach(listener -> listener.notify(urls));
         }
     }
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java
index f401eb9..cfb7d28 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java
@@ -562,7 +562,6 @@ public class RegistryProtocol implements Protocol {
 
         @Override
         protected void notifyOverrides(List<URL> urls) {
-            urls.forEach(u -> u.addParameter(CATEGORY_KEY, DYNAMIC_CONFIGURATORS_CATEGORY));
             notifyListener.notify(urls);
         }
     }
@@ -598,7 +597,6 @@ public class RegistryProtocol implements Protocol {
 
         @Override
         protected void notifyOverrides(List<URL> urls) {
-            urls.forEach(u -> u.addParameter(CATEGORY_KEY, APP_DYNAMIC_CONFIGURATORS_CATEGORY));
             overrideListeners.values().forEach(listener -> listener.notify(urls));
         }
     }


[incubator-dubbo] 03/07: Optimize service governance: 1. avoid duplicate notification of application level override rule 2. remove route cache 3. support sub menu in ops for router and configurator

Posted by li...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

liujun pushed a commit to branch dev-metadata
in repository https://gitbox.apache.org/repos/asf/incubator-dubbo.git

commit 6007fd30a80b2fa0a68c1dc0a263f125ed0dfb95
Author: ken.lj <ke...@gmail.com>
AuthorDate: Mon Dec 17 11:29:15 2018 +0800

    Optimize service governance:
    1. avoid duplicate notification of application level override rule
    2. remove route cache
    3. support sub menu in ops for router and configurator
---
 ...rFactory.java => AbstractAppRouterFactory.java} |  27 +-
 ...uterFactory.java => AbstractRouterFactory.java} |  25 +-
 .../java/org/apache/dubbo/rpc/cluster/Router.java  |  44 ++-
 .../org/apache/dubbo/rpc/cluster/RouterChain.java  | 113 ++----
 .../apache/dubbo/rpc/cluster/RouterFactory.java    |  14 +-
 .../cluster/configurator/AbstractConfigurator.java |   4 +-
 .../cluster/configurator/parser/ConfigParser.java  |  77 ++--
 .../configurator/parser/model/ConfigItem.java      |  23 ++
 .../parser/model/ConfiguratorConfig.java           |  16 +-
 .../rpc/cluster/directory/StaticDirectory.java     |  11 +-
 .../dubbo/rpc/cluster/router/AbstractRouter.java   |  50 ++-
 .../dubbo/rpc/cluster/router/InvokerTreeCache.java | 127 -------
 .../apache/dubbo/rpc/cluster/router/TreeNode.java  | 113 ------
 .../cluster/router/condition/ConditionRouter.java  |  11 +-
 .../config/AbstractConfigConditionRouter.java      | 145 ++++++++
 ...rFactory.java => AppConfigConditionRouter.java} |  26 +-
 ...y.java => AppConfigConditionRouterFactory.java} |  13 +-
 .../condition/config/ConfigConditionRouter.java    | 230 ------------
 ...tory.java => ServiceConfigConditionRouter.java} |  26 +-
 ...va => ServiceConfigConditionRouterFactory.java} |  17 +-
 ...tionRouterRule.java => BlackWhiteListRule.java} |   5 +-
 .../config/model/ConditionRouterRule.java          |   9 +
 .../config/model/ConditionRuleParser.java          |   6 +
 .../cluster/router/mock/MockInvokersSelector.java  |   5 -
 .../rpc/cluster/router/mock/MockRouterFactory.java |   5 -
 .../rpc/cluster/router/script/ScriptRouter.java    |   5 -
 .../dubbo/rpc/cluster/router/tag/TagRouter.java    | 189 +++-------
 .../rpc/cluster/router/tag/TagRouterFactory.java   |  17 +-
 .../org.apache.dubbo.rpc.cluster.RouterFactory     |   3 +-
 .../configurator/parser/ConfigParserTest.java      |  18 +-
 .../cluster/router/file/FileRouterEngineTest.java  |  10 +-
 .../support/AbstractClusterInvokerTest.java        |   6 +-
 .../support/wrapper/MockClusterInvokerTest.java    |  11 +-
 .../java/org/apache/dubbo/common/Constants.java    |  12 +-
 .../src/main/java/org/apache/dubbo/common/URL.java |   5 +
 .../integration/AbstractConfiguratorListener.java  |  64 ++++
 .../registry/integration/RegistryDirectory.java    | 413 ++++++++++++---------
 .../registry/integration/RegistryProtocol.java     | 228 ++++++------
 .../registry/support/ProviderConsumerRegTable.java |  11 +-
 .../java/org/apache/dubbo/registry/ZKTools.java    |  44 ++-
 .../registry/dubbo/RegistryDirectoryTest.java      |   5 +-
 .../java/org/apache/dubbo/rpc/AsyncContext.java    |   1 +
 .../main/java/org/apache/dubbo/rpc/RpcContext.java |   3 +
 .../apache/dubbo/rpc/model/ApplicationModel.java   |  10 +
 44 files changed, 973 insertions(+), 1224 deletions(-)

diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/AbstractAppRouterFactory.java
similarity index 64%
copy from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockRouterFactory.java
copy to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/AbstractAppRouterFactory.java
index 967bc2f..96d339a 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/AbstractAppRouterFactory.java
@@ -14,27 +14,28 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.apache.dubbo.rpc.cluster.router.mock;
+package org.apache.dubbo.rpc.cluster;
 
 import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.extension.Activate;
-import org.apache.dubbo.configcenter.DynamicConfiguration;
-import org.apache.dubbo.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
 
 /**
  *
  */
-@Activate
-public class MockRouterFactory implements RouterFactory {
+public abstract class AbstractAppRouterFactory implements RouterFactory {
+    private Router router;
 
     @Override
     public Router getRouter(URL url) {
-        return new MockInvokersSelector();
+        if (router != null) {
+            return router;
+        }
+        synchronized (this) {
+            if (router == null) {
+                router = createRouter(url);
+            }
+        }
+        return router;
     }
 
-    @Override
-    public Router getRouter(DynamicConfiguration dynamicConfiguration, URL url) {
-        return getRouter(url);
-    }
-}
\ No newline at end of file
+    protected abstract Router createRouter(URL url);
+}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/AbstractRouterFactory.java
similarity index 57%
copy from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java
copy to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/AbstractRouterFactory.java
index 7861227..18c7ecc 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/AbstractRouterFactory.java
@@ -14,26 +14,25 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.apache.dubbo.rpc.cluster.router.condition.config;
+package org.apache.dubbo.rpc.cluster;
 
 import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.extension.Activate;
-import org.apache.dubbo.configcenter.DynamicConfiguration;
-import org.apache.dubbo.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
 
 /**
- *
+ * If you want to provide a Router implementation based on design of v2.7.0, please extend from this abstract class.
+ * For 2.6.x style Router, please implement and use RouterFactory directly.
  */
-@Activate(order = 200)
-public class ConfigConditionRouterFactory implements RouterFactory {
+public abstract class AbstractRouterFactory implements RouterFactory {
+    private ConcurrentMap<String, Router> routerMap = new ConcurrentHashMap<>();
+
     @Override
     public Router getRouter(URL url) {
-        return null;
+        routerMap.computeIfAbsent(url.getServiceKey(), k -> createRouter(url));
+        return routerMap.get(url.getServiceKey());
     }
 
-    @Override
-    public Router getRouter(DynamicConfiguration dynamicConfiguration, URL url) {
-        return new ConfigConditionRouter(dynamicConfiguration, url);
-    }
+    protected abstract Router createRouter(URL url);
 }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Router.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Router.java
index 3aaf298..e775714 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Router.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Router.java
@@ -20,7 +20,6 @@ import org.apache.dubbo.common.URL;
 import org.apache.dubbo.rpc.Invocation;
 import org.apache.dubbo.rpc.Invoker;
 import org.apache.dubbo.rpc.RpcException;
-import org.apache.dubbo.rpc.cluster.router.TreeNode;
 
 import java.util.List;
 import java.util.Map;
@@ -42,7 +41,7 @@ public interface Router extends Comparable<Router> {
     URL getUrl();
 
     /**
-     * route.
+     * Filter invokers with current routing rule and only return the invokers that comply with the rule.
      *
      * @param invokers
      * @param url        refer url
@@ -56,25 +55,32 @@ public interface Router extends Comparable<Router> {
         return null;
     }
 
-    default void setRouterChain(RouterChain routerChain) {
-    }
-
-    default String getName() {
-        return "";
-    }
+    /**
+     * Each router has a reference of the router chain.
+     *
+     * @param routerChain
+     */
+    void addRouterChain(RouterChain routerChain);
 
+    /**
+     * To decide whether this router need to execute every time an RPC comes or should only execute when addresses or rule change.
+     *
+     * @return
+     */
     boolean isRuntime();
 
-    default String getKey() {
-        return TreeNode.FAILOVER_KEY;
-    }
-
-    default boolean isForce() {
-        return false;
-    }
-
-    default int getPriority() {
-        return 0;
-    }
+    /**
+     * To decide whether this router should take effect when none of the invoker can match the router rule, which means the {@link #route(List, URL, Invocation)} would be empty.
+     * Most of time, most router implementation would default this value to false.
+     *
+     * @return
+     */
+    boolean isForce();
 
+    /**
+     * used to sort routers.
+     *
+     * @return
+     */
+    int getPriority();
 }
\ No newline at end of file
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java
index 3dfa325..f19472d 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java
@@ -19,16 +19,11 @@ package org.apache.dubbo.rpc.cluster;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.extension.ExtensionLoader;
 import org.apache.dubbo.common.utils.CollectionUtils;
-import org.apache.dubbo.configcenter.DynamicConfiguration;
 import org.apache.dubbo.rpc.Invocation;
 import org.apache.dubbo.rpc.Invoker;
-import org.apache.dubbo.rpc.RpcInvocation;
-import org.apache.dubbo.rpc.cluster.router.InvokerTreeCache;
-import org.apache.dubbo.rpc.cluster.router.TreeNode;
 
 import java.util.Collections;
 import java.util.List;
-import java.util.Map;
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.stream.Collectors;
 
@@ -38,24 +33,21 @@ import java.util.stream.Collectors;
 public class RouterChain<T> {
 
     // full list of addresses from registry, classified by method name.
-    private Map<String, List<Invoker<T>>> fullMethodInvokers;
+    private List<Invoker<T>> fullInvokers;
     private URL url;
 
-    // a tree-structured cache generated from the full address list after being filtered by all routers.
-    // it's aimed to improve performance, only routers explicitly specifies 'runtime=true' will be executed when an RPC comes.
-    private InvokerTreeCache<T> treeCache;
     // containing all routers, reconstruct every time 'route://' urls change.
     private List<Router> routers = new CopyOnWriteArrayList<>();
     // Fixed router instances: ConfigConditionRouter, TagRouter, e.g., the rule for each instance may change but the instance will never delete or recreate.
     private List<Router> residentRouters;
 
-    public static <T> RouterChain<T> buildChain(DynamicConfiguration dynamicConfiguration, URL url) {
+    public static <T> RouterChain<T> buildChain(URL url) {
         RouterChain<T> routerChain = new RouterChain<>(url);
         List<RouterFactory> extensionFactories = ExtensionLoader.getExtensionLoader(RouterFactory.class).getActivateExtension(url, (String[]) null);
         List<Router> routers = extensionFactories.stream()
                 .map(factory -> {
-                    Router router = factory.getRouter(dynamicConfiguration, url);
-                    router.setRouterChain(routerChain);
+                    Router router = factory.getRouter(url);
+                    router.addRouterChain(routerChain);
                     return router;
                 }).collect(Collectors.toList());
         routerChain.setResidentRouters(routers);
@@ -64,16 +56,14 @@ public class RouterChain<T> {
 
     protected RouterChain(List<Router> routers) {
         this.routers.addAll(routers);
-        treeCache = new InvokerTreeCache<>();
     }
 
     protected RouterChain(URL url) {
-        treeCache = new InvokerTreeCache<>();
         this.url = url;
     }
 
     /**
-     * the resident routers must have already been generated before notification of provider addresses.
+     * the resident routers must being initialized before address notification.
      *
      * @param residentRouters
      */
@@ -88,7 +78,7 @@ public class RouterChain<T> {
      * so we should keep the routers up to date, that is, each time router URLs changes, we should update the routers list,
      * only keep the residentRouters which are available all the time and the latest notified routers which are generated from URLs.
      *
-     * @param generatedRouters
+     * @param generatedRouters routers from 'router://' rules in 2.6.x or before.
      */
     public void setGeneratedRouters(List<Router> generatedRouters) {
         List<Router> newRouters = new CopyOnWriteArrayList<>();
@@ -97,14 +87,9 @@ public class RouterChain<T> {
         this.routers = newRouters;
         // FIXME will sort cause concurrent problem? since it's kind of a write operation.
         this.sort();
-        if (fullMethodInvokers != null) {
-            this.preRoute(fullMethodInvokers, url, null);
-        }
-    }
-
-    public void addRouter(Router router) {
-        this.routers.add(router);
-        this.sort();
+       /* if (fullInvokers != null) {
+            this.preRoute(fullInvokers, url, null);
+        }*/
     }
 
     public void sort() {
@@ -112,39 +97,18 @@ public class RouterChain<T> {
     }
 
     /**
-     * Route cache building can be triggered in different threads, for example, registry notification and governance notification.
+     * TODO
+     *
+     * Building of router cache can be triggered from within different threads, for example, registry notification and governance notification.
      * So this operation should be synchronized.
-     * @param methodInvokers
+     * @param invokers
      * @param url
-     * @param invocation     TODO has not been used yet
+     * @param invocation
      */
-    public void preRoute(Map<String, List<Invoker<T>>> methodInvokers, URL url, Invocation invocation) {
-        if (CollectionUtils.isEmpty(routers) || methodInvokers == null) {
-            treeCache.refreshTree(null);
-            return;
+    public void preRoute(List<Invoker<T>> invokers, URL url, Invocation invocation) {
+        for (Router router : routers) {
+            router.preRoute(invokers, url, invocation);
         }
-        TreeNode<T> root = treeCache.buildRootNode();
-        Router router = routers.get(0);
-        methodInvokers.forEach((method, invokers) -> {
-            TreeNode<T> node = new TreeNode<>("METHOD_ROUTER", "method", method, invokers, true);
-            root.addChild(node);
-            Invocation invocation1 = new RpcInvocation(method, new Class<?>[0], new Object[0]);
-            doRoute(router, 1, node, router.preRoute(invokers, url, invocation1), url, invocation1);
-        });
-        treeCache.refreshTree(root);
-    }
-
-    private void doRoute(Router router, int i, TreeNode parentNode, Map<String, List<Invoker<T>>> invokers, URL url, Invocation invocation) {
-        invokers.forEach((routerValue, list) -> {
-            TreeNode<T> node = new TreeNode<>(router.getName(), router.getKey(), routerValue, list, router.isForce());
-            parentNode.addChild(node);
-            // Only when we have more routers and the sub-lis is not empty.
-            if (i < routers.size() && CollectionUtils.isNotEmpty(list)) {
-                node.setInvokers(null); // only store invoker list in leaf nodes.
-                Router nextRouter = routers.get(i);
-                doRoute(nextRouter, i + 1, node, nextRouter.preRoute(list, url, invocation), url, invocation);
-            }
-        });
     }
 
     /**
@@ -154,38 +118,39 @@ public class RouterChain<T> {
      * @return
      */
     public List<Invoker<T>> route(URL url, Invocation invocation) {
-        List<Invoker<T>> finalInvokers = treeCache.getInvokers(treeCache.getTree(), url, invocation);
-        for (Router router : routers) {
-            if (router.isRuntime()) {
-                finalInvokers = router.route(finalInvokers, url, invocation);
-            }
-        }
-        return finalInvokers;
-    }
-
-    public List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) {
-        List<Invoker<T>> finalInvokers = invokers;
-        if (treeCache.getTree() != null) {
-            finalInvokers = treeCache.getInvokers(treeCache.getTree(), url, invocation);
-        }
+        List<Invoker<T>> finalInvokers = fullInvokers;
         for (Router router : routers) {
-            if (router.isRuntime()) {
-                finalInvokers = router.route(invokers, url, invocation);
-            }
+//            if (router.isRuntime()) {
+//                finalInvokers = router.route(finalInvokers, url, invocation);
+//            }
+            finalInvokers = router.route(finalInvokers, url, invocation);
         }
         return finalInvokers;
     }
 
+    /**
+     * When any of the router's rule changed, notify the router chain to rebuild cache from scratch.
+     */
     public void notifyRuleChanged() {
-        preRoute(this.fullMethodInvokers, url, null);
+        if (CollectionUtils.isEmpty(this.fullInvokers)) {
+            return;
+        }
+        preRoute(this.fullInvokers, url, null);
     }
 
-    public void notifyFullInvokers(Map<String, List<Invoker<T>>> invokers, URL url) {
+    /**
+     * Notify router chain of the initial addresses from registry at the first time.
+     * Notify whenever addresses in registry change.
+     *
+     * @param invokers
+     * @param url
+     */
+    public void notifyFullInvokers(List<Invoker<T>> invokers, URL url) {
         setFullMethodInvokers(invokers);
         preRoute(invokers, url, null);
     }
 
-    public void setFullMethodInvokers(Map<String, List<Invoker<T>>> fullMethodInvokers) {
-        this.fullMethodInvokers = fullMethodInvokers;
+    public void setFullMethodInvokers(List<Invoker<T>> fullInvokers) {
+        this.fullInvokers = fullInvokers;
     }
 }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterFactory.java
index 16467b0..13dbbd7 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterFactory.java
@@ -19,7 +19,6 @@ package org.apache.dubbo.rpc.cluster;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.extension.Adaptive;
 import org.apache.dubbo.common.extension.SPI;
-import org.apache.dubbo.configcenter.DynamicConfiguration;
 
 /**
  * RouterFactory. (SPI, Singleton, ThreadSafe)
@@ -28,25 +27,20 @@ import org.apache.dubbo.configcenter.DynamicConfiguration;
  *
  * @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory)
  * @see org.apache.dubbo.rpc.cluster.Directory#list(org.apache.dubbo.rpc.Invocation)
+ *
+ * Note Router has a different behaviour since 2.7.0, for each type of Router, there will only has one Router instance for each service.
+ * See {@link AbstractRouterFactory} and {@link RouterChain} for how to extend a new Router or how the Router instances are loaded.
  */
 @SPI
 public interface RouterFactory {
 
     /**
      * Create router.
+     * Since 2.7.0, most of the time, we will not use @Adaptive feature, so it's keeped only for compatibility.
      *
      * @param url
      * @return router
      */
     @Adaptive("protocol")
     Router getRouter(URL url);
-
-    /**
-     * @param dynamicConfiguration
-     * @param url                  reserved for future usage.
-     * @return
-     */
-    default Router getRouter(DynamicConfiguration dynamicConfiguration, URL url) {
-        return null;
-    }
 }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java
index 3b682ee..ac40435 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java
@@ -55,7 +55,7 @@ public abstract class AbstractConfigurator implements Configurator {
         /**
          * This if branch is created since 2.7.0.
          */
-        String apiVersion = configuratorUrl.getParameter(Constants.API_VERSION_KEY);
+        String apiVersion = configuratorUrl.getParameter(Constants.CONFIG_VERSION_KEY);
         if (StringUtils.isNotEmpty(apiVersion)) {
             String currentSide = url.getParameter(Constants.SIDE_KEY);
             String configuratorSide = configuratorUrl.getParameter(Constants.SIDE_KEY);
@@ -112,7 +112,7 @@ public abstract class AbstractConfigurator implements Configurator {
                     conditionKeys.add(Constants.VERSION_KEY);
                     conditionKeys.add(Constants.APPLICATION_KEY);
                     conditionKeys.add(Constants.SIDE_KEY);
-                    conditionKeys.add(Constants.API_VERSION_KEY);
+                    conditionKeys.add(Constants.CONFIG_VERSION_KEY);
                     for (Map.Entry<String, String> entry : configuratorUrl.getParameters().entrySet()) {
                         String key = entry.getKey();
                         String value = entry.getValue();
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java
index 52384f3..8347141 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java
@@ -30,14 +30,13 @@ import org.yaml.snakeyaml.constructor.Constructor;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
-import java.util.stream.Collectors;
 
 /**
  *
  */
 public class ConfigParser {
 
-    public static List<URL> parseConfigurators(String rawConfig, String serviceKey) {
+    public static List<URL> parseConfigurators(String rawConfig) {
         List<URL> urls = new ArrayList<>();
         ConfiguratorConfig configuratorConfig = parseObject(rawConfig, ConfiguratorConfig.class);
 
@@ -45,22 +44,9 @@ public class ConfigParser {
         List<ConfigItem> items = configuratorConfig.getConfigs();
 
         if (ConfiguratorConfig.SCOPE_APPLICATION.equals(scope)) {
-            items.forEach(item -> urls.addAll(
-                    appItemToUrls(item, configuratorConfig.getKey(), serviceKey)
-                            .stream()
-                            .map(u -> u.addParameter(Constants.CATEGORY_KEY, Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY))
-                            .map(u -> u.addParameter(Constants.ENABLED_KEY, configuratorConfig.isEnabled()))
-                            .map(u -> u.addParameter(Constants.API_VERSION_KEY, configuratorConfig.getApiVersion()))
-                            .collect(Collectors.toList())
-            ));
+            items.forEach(item -> urls.addAll(appItemToUrls(item, configuratorConfig)));
         } else { // servcie scope by default.
-            items.forEach(item -> urls.addAll(
-                    serviceItemToUrls(item, configuratorConfig.getKey())
-                            .stream()
-                            .map(u -> u.addParameter(Constants.ENABLED_KEY, configuratorConfig.isEnabled()))
-                            .map(u -> u.addParameter(Constants.API_VERSION_KEY, configuratorConfig.getApiVersion()))
-                            .collect(Collectors.toList()))
-            );
+            items.forEach(item -> urls.addAll(serviceItemToUrls(item, configuratorConfig)));
         }
         return urls;
     }
@@ -75,7 +61,7 @@ public class ConfigParser {
         return yaml.load(rawConfig);
     }
 
-    private static List<URL> serviceItemToUrls(ConfigItem item, String serviceKey) {
+    private static List<URL> serviceItemToUrls(ConfigItem item, ConfiguratorConfig config) {
         List<URL> urls = new ArrayList<>();
         List<String> addresses = item.getAddresses();
         if (addresses == null) {
@@ -86,21 +72,36 @@ public class ConfigParser {
         }
 
         addresses.forEach(addr -> {
-            String urlStr = "override://" + addr + "/";
+            StringBuilder urlBuilder = new StringBuilder();
+            urlBuilder.append("override://").append(addr).append("/");
+
+            urlBuilder.append(appendService(config.getKey()));
+            urlBuilder.append(toParameterString(item));
+
+            urlBuilder.append("&enabled=");
+            if (item.getType() == null || ConfigItem.GENERAL_TYPE.equals(item.getType())) {
+                urlBuilder.append(config.getEnabled());
+            } else {
+                urlBuilder.append(item.getEnabled());
+            }
+
+            urlBuilder.append("&category=").append(Constants.DYNAMIC_CONFIGURATORS_CATEGORY);
+            urlBuilder.append("&configVersion=").append(config.getConfigVersion());
+
             List<String> apps = item.getApplications();
             if (apps != null && apps.size() > 0) {
                 apps.forEach(app -> {
-                    urls.add(URL.valueOf(urlStr + appendService(serviceKey) + toParameterString(item) + "&application=" + app));
+                    urls.add(URL.valueOf(urlBuilder.append("&application=" + app).toString()));
                 });
             } else {
-                urls.add(URL.valueOf(urlStr + appendService(serviceKey) + toParameterString(item)));
+                urls.add(URL.valueOf(urlBuilder.toString()));
             }
         });
 
         return urls;
     }
 
-    private static List<URL> appItemToUrls(ConfigItem item, String appKey, String serviceKey) {
+    private static List<URL> appItemToUrls(ConfigItem item, ConfiguratorConfig config) {
         List<URL> urls = new ArrayList<>();
         List<String> addresses = item.getAddresses();
         if (addresses == null) {
@@ -110,15 +111,33 @@ public class ConfigParser {
             addresses.add(Constants.ANYHOST_VALUE);
         }
         for (String addr : addresses) {
-            String urlStr = "override://" + addr + "/";
+            StringBuilder urlBuilder = new StringBuilder();
+            urlBuilder.append("override://").append(addr).append("/");
             List<String> services = item.getServices();
-            String targetService = serviceKey;
-            if (CollectionUtils.isEmpty(services) || services.contains("*")) {
-                targetService = "*";
-            } else if (!services.contains(serviceKey)) {
-                return urls;
+            if (services == null) {
+                services = new ArrayList<>();
+            }
+            if (services.size() == 0) {
+                services.add("*");
+            }
+            for (String s : services) {
+                urlBuilder.append(appendService(s));
+                urlBuilder.append(toParameterString(item));
+
+                urlBuilder.append("&application=").append(config.getKey());
+
+                urlBuilder.append("&enabled=");
+                if (item.getType() == null || ConfigItem.GENERAL_TYPE.equals(item.getType())) {
+                    urlBuilder.append(config.getEnabled());
+                } else {
+                    urlBuilder.append(item.getEnabled());
+                }
+
+                urlBuilder.append("&category=").append(Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY);
+                urlBuilder.append("&configVersion=").append(config.getConfigVersion());
+
+                urls.add(URL.valueOf(urlBuilder.toString()));
             }
-            urls.add(URL.valueOf(urlStr + appendService(targetService) + toParameterString(item) + "&application=" + appKey));
         }
         return urls;
     }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfigItem.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfigItem.java
index a814ff3..2a6a56a 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfigItem.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfigItem.java
@@ -23,6 +23,13 @@ import java.util.Map;
  *
  */
 public class ConfigItem {
+    public static final String GENERAL_TYPE = "general";
+    public static final String WEIGHT_TYPE = "weight";
+    public static final String BALANCING_TYPE = "balancing";
+    public static final String DISABLED_TYPE = "disabled";
+
+    private String type;
+    private Boolean enabled;
     private List<String> addresses;
     private List<String> providerAddresses;
     private List<String> services;
@@ -30,6 +37,22 @@ public class ConfigItem {
     private Map<String, String> parameters;
     private String side;
 
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+
+    public Boolean getEnabled() {
+        return enabled;
+    }
+
+    public void setEnabled(Boolean enabled) {
+        this.enabled = enabled;
+    }
+
     public List<String> getAddresses() {
         return addresses;
     }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfiguratorConfig.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfiguratorConfig.java
index dd0d3b0..aadc999 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfiguratorConfig.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfiguratorConfig.java
@@ -25,19 +25,19 @@ public class ConfiguratorConfig {
     public static final String SCOPE_SERVICE = "service";
     public static final String SCOPE_APPLICATION = "application";
 
-    private String apiVersion;
+    private String configVersion;
     private String scope;
     private String key;
-    private boolean enabled = true;
+    private Boolean enabled = true;
     private List<ConfigItem> configs;
 
 
-    public String getApiVersion() {
-        return apiVersion;
+    public String getConfigVersion() {
+        return configVersion;
     }
 
-    public void setApiVersion(String apiVersion) {
-        this.apiVersion = apiVersion;
+    public void setConfigVersion(String configVersion) {
+        this.configVersion = configVersion;
     }
 
     public String getScope() {
@@ -56,11 +56,11 @@ public class ConfiguratorConfig {
         this.key = key;
     }
 
-    public boolean isEnabled() {
+    public Boolean getEnabled() {
         return enabled;
     }
 
-    public void setEnabled(boolean enabled) {
+    public void setEnabled(Boolean enabled) {
         this.enabled = enabled;
     }
 
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java
index 07b6419..02041ba 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java
@@ -19,20 +19,16 @@ package org.apache.dubbo.rpc.cluster.directory;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.logger.Logger;
 import org.apache.dubbo.common.logger.LoggerFactory;
-import org.apache.dubbo.configcenter.DynamicConfiguration;
 import org.apache.dubbo.rpc.Invocation;
 import org.apache.dubbo.rpc.Invoker;
 import org.apache.dubbo.rpc.RpcException;
 import org.apache.dubbo.rpc.cluster.RouterChain;
 
 import java.util.List;
-import java.util.Map;
 
 /**
  * StaticDirectory
  *
- * FIXME We should add separate router rules for StaticDirectory, not use RouterChain in AbstractDirectory. For example, machineRoom rule only. Ask LVS team for help.
- *
  */
 public class StaticDirectory<T> extends AbstractDirectory<T> {
     private static final Logger logger = LoggerFactory.getLogger(StaticDirectory.class);
@@ -88,10 +84,9 @@ public class StaticDirectory<T> extends AbstractDirectory<T> {
         invokers.clear();
     }
 
-    public void buildRouterChain(Map<String, List<Invoker<T>>> methodGroupInvokers, DynamicConfiguration dynamicConfiguration) {
-        ;
-        RouterChain<T> routerChain = RouterChain.buildChain(dynamicConfiguration, getUrl());
-        routerChain.notifyFullInvokers(methodGroupInvokers, getUrl());
+    public void buildRouterChain(List<Invoker<T>> groupInvokers) {
+        RouterChain<T> routerChain = RouterChain.buildChain(getUrl());
+        routerChain.notifyFullInvokers(groupInvokers, getUrl());
         this.setRouterChain(routerChain);
     }
 
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java
index 56f24ca..301ca01 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java
@@ -17,16 +17,12 @@
 package org.apache.dubbo.rpc.cluster.router;
 
 import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.utils.CollectionUtils;
-import org.apache.dubbo.rpc.Invocation;
-import org.apache.dubbo.rpc.Invoker;
-import org.apache.dubbo.rpc.RpcException;
+import org.apache.dubbo.configcenter.DynamicConfiguration;
 import org.apache.dubbo.rpc.cluster.Router;
 import org.apache.dubbo.rpc.cluster.RouterChain;
 
-import java.util.HashMap;
 import java.util.List;
-import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
 
 /**
  * TODO Extract more code to here if necessary
@@ -35,9 +31,19 @@ public abstract class AbstractRouter implements Router {
     protected int priority;
     protected boolean force;
     protected boolean enabled;
-    protected RouterChain routerChain;
+    protected List<RouterChain> routerChains = new CopyOnWriteArrayList<>();
     protected URL url;
 
+    protected DynamicConfiguration configuration;
+
+    public AbstractRouter(DynamicConfiguration configuration, URL url) {
+        this.configuration = configuration;
+        this.url = url;
+    }
+
+    public AbstractRouter() {
+    }
+
     @Override
     public URL getUrl() {
         return url;
@@ -48,24 +54,13 @@ public abstract class AbstractRouter implements Router {
     }
 
     @Override
-    public <T> Map<String, List<Invoker<T>>> preRoute(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
-        Map<String, List<Invoker<T>>> map = new HashMap<>();
-
-        if (CollectionUtils.isEmpty(invokers)) {
-            return map;
-        }
-
-        if (isRuntime() || !isEnabled()) {
-            map.put(TreeNode.FAILOVER_KEY, invokers);
-        } else {
-            map.put(TreeNode.FAILOVER_KEY, route(invokers, url, invocation));
-        }
-        return map;
+    public void addRouterChain(RouterChain routerChain) {
+        this.routerChains.add(routerChain);
     }
 
-    @Override
-    public void setRouterChain(RouterChain routerChain) {
-        this.routerChain = routerChain;
+
+    public void setConfiguration(DynamicConfiguration configuration) {
+        this.configuration = configuration;
     }
 
     @Override
@@ -82,6 +77,11 @@ public abstract class AbstractRouter implements Router {
         this.force = force;
     }
 
+    @Override
+    public int compareTo(Router o) {
+        return (this.getPriority() >= o.getPriority()) ? 1 : -1;
+    }
+
     public boolean isEnabled() {
         return enabled;
     }
@@ -98,8 +98,4 @@ public abstract class AbstractRouter implements Router {
         this.priority = priority;
     }
 
-    @Override
-    public int compareTo(Router o) {
-        return (this.getPriority() >= o.getPriority()) ? 1 : -1;
-    }
 }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/InvokerTreeCache.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/InvokerTreeCache.java
deleted file mode 100644
index 812632a..0000000
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/InvokerTreeCache.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.dubbo.rpc.cluster.router;
-
-import org.apache.dubbo.common.Constants;
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.utils.CollectionUtils;
-import org.apache.dubbo.common.utils.StringUtils;
-import org.apache.dubbo.rpc.Invocation;
-import org.apache.dubbo.rpc.Invoker;
-
-import java.util.Collections;
-import java.util.List;
-
-/**
- *
- */
-public class InvokerTreeCache<T> {
-
-    private TreeNode<T> tree;
-
-    public TreeNode<T> buildRootNode() {
-        TreeNode<T> rootNode = new TreeNode<>();
-        rootNode.setRouterName("ROOT_ROUTER");
-        rootNode.setConditionValue("root");
-        rootNode.setConditionKey("root");
-        return rootNode;
-    }
-
-    public List<Invoker<T>> getInvokers(TreeNode<T> node, URL url, Invocation invocation) {
-        // We have reached the leaf node.
-        if (node == null) {
-            return Collections.emptyList();
-        }
-        if (node.isLeaf()) {
-            return node.getInvokers();
-        }
-
-        //
-       /* if (node.getChildren().size() == 1) {
-            return getInvokers(node.getChildren().get(0), url, invocation);
-        }*/
-
-        TreeNode<T> failoverNode = null;
-        for (TreeNode<T> n : node.getChildren()) {
-            String key = n.getConditionKey();
-            // if the key is FAILOVER, it indicates we have only one child in this level, just proceed on.
-            if (TreeNode.FAILOVER_KEY.equals(key)) {
-                return getInvokers(n, url, invocation);
-            }
-            if (TreeNode.FAILOVER_KEY.equals(n.getConditionValue())) {
-                failoverNode = n;
-                continue;
-            }
-
-            //TODO key=method, but it will appear neither in url nor in attachments.
-            String value = invocation.getAttachment(key, url.getParameter(key));
-            if (Constants.METHOD_KEY.equals(key)) {
-                value = invocation.getMethodName();
-            }
-
-            // If we don't have a match condition in the request, then our goal would be find the failoverNode in this loop and continue match with failoverNode's children.
-            if (StringUtils.isEmpty(value)) {
-                if (failoverNode == null) {
-                    for (TreeNode<T> innerLoopNode : node.getChildren()) {
-                        if (innerLoopNode.getConditionValue().equals(TreeNode.FAILOVER_KEY)) {
-                            failoverNode = innerLoopNode;
-                        }
-                    }
-                }
-                // Router will guarantee that there's always a FAILOVER node.
-                // To make it more robust, we may need to add null check for failoverNode here.
-                return getInvokers(failoverNode, url, invocation);
-            }
-
-            // If the request condition matches with the node branch, go ahead.
-            if (n.getConditionValue().equals(value)) {
-                // If the invoker list in this node is empty, we need to check force to decide to return empty list or to seek for FAILOVER.
-                if (CollectionUtils.isNotEmpty(n.getInvokers()) || (CollectionUtils.isEmpty(n.getInvokers()) && n.isForce()))
-                    return getInvokers(n, url, invocation);
-            }
-        }
-
-        // If we get here,
-        // 1. we must have several brothers in current node level.
-        // 2. there is a router match condition in the request.
-        // 3. the request value failed to match any of the values specified by the router rule.
-        if (failoverNode != null) {
-            // What if force parameter comes from runtime? Use a convention format of 'force.xxx', for example, for TagRouter it would be 'force.tag'.
-            // FIXME check force logic here
-            String forceKey = "force." + failoverNode.getConditionKey();
-            if (Boolean.valueOf(invocation.getAttachment(forceKey, url.getParameter(forceKey, "false")))) {
-                /**
-                 * This may mistakenly return empty list for runtime routers
-                 * see {@link org.apache.dubbo.rpc.cluster.router.tag.TagRouter.getKey()} for the workaround.
-                 */
-                return Collections.emptyList();
-            }
-            return getInvokers(failoverNode, url, invocation);
-        }
-        return Collections.emptyList();
-    }
-
-
-    public void refreshTree(TreeNode<T> node) {
-        this.tree = node;
-    }
-
-    public TreeNode<T> getTree() {
-        return tree;
-    }
-
-}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/TreeNode.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/TreeNode.java
deleted file mode 100644
index 106e244..0000000
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/TreeNode.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.dubbo.rpc.cluster.router;
-
-import org.apache.dubbo.common.utils.CollectionUtils;
-import org.apache.dubbo.rpc.Invoker;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- *
- */
-public class TreeNode<T> {
-    public static final String FAILOVER_KEY = "failover";
-
-    private String routerName;
-    private String conditionKey;
-    private String conditionValue;
-    private boolean force;
-    private List<Invoker<T>> invokers;
-    private List<TreeNode<T>> children;
-
-    public TreeNode() {
-        this.children = new ArrayList<>();
-    }
-
-    public TreeNode(String routerName, String conditionKey, String conditionValue, List<Invoker<T>> invokers, boolean force) {
-        this.routerName = routerName;
-        this.conditionKey = conditionKey;
-        this.conditionValue = conditionValue;
-        this.invokers = invokers;
-        this.force = force;
-        this.children = new ArrayList<>();
-    }
-
-    public void traverse() {
-
-    }
-
-    public void addChild(TreeNode child) {
-        children.add(child);
-    }
-
-    public boolean isLeaf() {
-        if (CollectionUtils.isEmpty(children)) {
-            return true;
-        }
-        return false;
-    }
-
-    public String getRouterName() {
-        return routerName;
-    }
-
-    public void setRouterName(String routerName) {
-        this.routerName = routerName;
-    }
-
-    public String getConditionKey() {
-        return conditionKey;
-    }
-
-    public void setConditionKey(String conditionKey) {
-        this.conditionKey = conditionKey;
-    }
-
-    public String getConditionValue() {
-        return conditionValue;
-    }
-
-    public void setConditionValue(String conditionValue) {
-        this.conditionValue = conditionValue;
-    }
-
-    public List<Invoker<T>> getInvokers() {
-        return invokers;
-    }
-
-    public void setInvokers(List<Invoker<T>> invokers) {
-        this.invokers = invokers;
-    }
-
-    public List<TreeNode<T>> getChildren() {
-        return children;
-    }
-
-    public void setChildren(List<TreeNode<T>> children) {
-        this.children = children;
-    }
-
-    public boolean isForce() {
-        return force;
-    }
-
-    public void setForce(boolean force) {
-        this.force = force;
-    }
-}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java
index 95dae26..ba63ba6 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java
@@ -154,6 +154,10 @@ public class ConditionRouter extends AbstractRouter implements Comparable<Router
     @Override
     public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation)
             throws RpcException {
+        if (!isEnabled()) {
+            return invokers;
+        }
+
         if (invokers == null || invokers.isEmpty()) {
             return invokers;
         }
@@ -184,11 +188,6 @@ public class ConditionRouter extends AbstractRouter implements Comparable<Router
     }
 
     @Override
-    public String getName() {
-        return NAME;
-    }
-
-    @Override
     public boolean isRuntime() {
         // We always return true for previously defined Router, that is, old Router doesn't support cache anymore.
 //        return true;
@@ -197,7 +196,7 @@ public class ConditionRouter extends AbstractRouter implements Comparable<Router
 
     @Override
     public boolean isEnabled() {
-        return url.getParameter(Constants.ENABLED_KEY, false);
+        return url == null ? enabled : url.getParameter(Constants.ENABLED_KEY, false);
     }
 
     @Override
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AbstractConfigConditionRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AbstractConfigConditionRouter.java
new file mode 100644
index 0000000..26fad9a
--- /dev/null
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AbstractConfigConditionRouter.java
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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.router.condition.config;
+
+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.CollectionUtils;
+import org.apache.dubbo.configcenter.ConfigChangeEvent;
+import org.apache.dubbo.configcenter.ConfigChangeType;
+import org.apache.dubbo.configcenter.ConfigurationListener;
+import org.apache.dubbo.configcenter.DynamicConfiguration;
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.RpcException;
+import org.apache.dubbo.rpc.cluster.Router;
+import org.apache.dubbo.rpc.cluster.RouterChain;
+import org.apache.dubbo.rpc.cluster.router.AbstractRouter;
+import org.apache.dubbo.rpc.cluster.router.condition.ConditionRouter;
+import org.apache.dubbo.rpc.cluster.router.condition.config.model.BlackWhiteListRule;
+import org.apache.dubbo.rpc.cluster.router.condition.config.model.ConditionRouterRule;
+import org.apache.dubbo.rpc.cluster.router.condition.config.model.ConditionRuleParser;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ *
+ */
+public abstract class AbstractConfigConditionRouter extends AbstractRouter implements ConfigurationListener {
+    public static final String NAME = "CONFIG_CONDITION_OUTER";
+    public static final int DEFAULT_PRIORITY = 200;
+    private static final Logger logger = LoggerFactory.getLogger(AbstractConfigConditionRouter.class);
+    private ConditionRouterRule routerRule;
+    private List<ConditionRouter> conditionRouters = new ArrayList<>();
+
+    public AbstractConfigConditionRouter(DynamicConfiguration configuration, URL url) {
+        super(configuration, url);
+        this.force = false;
+        this.init();
+    }
+
+    @Override
+    public synchronized void process(ConfigChangeEvent event) {
+        if (logger.isInfoEnabled()) {
+            logger.info("Notification of condition rule, change type is: " + event.getChangeType() + ", raw rule is:\n " + event
+                    .getValue());
+        }
+
+        if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
+            routerRule = null;
+            conditionRouters.clear();
+        } else {
+            try {
+                routerRule = ConditionRuleParser.parse(event.getValue());
+                generateConditions(routerRule, conditionRouters);
+            } catch (Exception e) {
+                logger.error("Failed to parse the raw condition rule and it will not take effect, please check if the condition rule matches with the template, the raw rule is:\n " + event
+                        .getValue(), e);
+            }
+        }
+
+        routerChains.forEach(RouterChain::notifyRuleChanged);
+    }
+
+    @Override
+    public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
+        if (CollectionUtils.isEmpty(invokers) || conditionRouters.size() == 0 || !isEnabled()) {
+            return invokers;
+        }
+
+        if (isRuleEnabled()) {
+            for (Router router : conditionRouters) {
+                invokers = router.route(invokers, url, invocation);
+            }
+        }
+        return invokers;
+    }
+
+    @Override
+    public int getPriority() {
+        return DEFAULT_PRIORITY;
+    }
+
+    /*@Override
+    public boolean isRuntime() {
+        return isRuleRuntime();
+    }*/
+
+    @Override
+    public boolean isEnabled() {
+        return isRuleEnabled();
+    }
+
+    @Override
+    public boolean isForce() {
+        return (routerRule != null && routerRule.isForce());
+    }
+
+    private boolean isRuleEnabled() {
+        return routerRule != null && routerRule.isValid() && routerRule.isEnabled();
+    }
+
+    private boolean isRuleRuntime() {
+        return routerRule != null && routerRule.isValid() && routerRule.isRuntime();
+    }
+
+    private void generateConditions(ConditionRouterRule rule, List<ConditionRouter> routers) {
+        if (rule != null && rule.isValid()) {
+            routers.clear();
+            rule.getConditions().forEach(condition -> {
+                // All sub rules have the same force, runtime value.
+                ConditionRouter subRouter = new ConditionRouter(condition, rule.isForce());
+                subRouter.setEnabled(rule.isEnabled());
+                routers.add(subRouter);
+            });
+
+            BlackWhiteListRule blackWhiteList = rule.getBlackWhiteListRule();
+            if (blackWhiteList != null && blackWhiteList.isValid()) {
+                blackWhiteList.getConditions().forEach(condition -> {
+                    // All sub rules have the same force, runtime value.
+                    ConditionRouter subRouter = new ConditionRouter(condition, true);
+                    subRouter.setEnabled(blackWhiteList.isEnabled());
+                    routers.add(subRouter);
+                });
+            }
+        }
+    }
+
+    protected abstract void init();
+}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppConfigConditionRouter.java
similarity index 60%
copy from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java
copy to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppConfigConditionRouter.java
index 7861227..b580d36 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppConfigConditionRouter.java
@@ -16,24 +16,28 @@
  */
 package org.apache.dubbo.rpc.cluster.router.condition.config;
 
+import org.apache.dubbo.common.Constants;
 import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.extension.Activate;
+import org.apache.dubbo.configcenter.ConfigChangeEvent;
 import org.apache.dubbo.configcenter.DynamicConfiguration;
-import org.apache.dubbo.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
 
 /**
  *
  */
-@Activate(order = 200)
-public class ConfigConditionRouterFactory implements RouterFactory {
-    @Override
-    public Router getRouter(URL url) {
-        return null;
+public class AppConfigConditionRouter extends AbstractConfigConditionRouter {
+
+    public AppConfigConditionRouter(DynamicConfiguration configuration, URL url) {
+        super(configuration, url);
     }
 
-    @Override
-    public Router getRouter(DynamicConfiguration dynamicConfiguration, URL url) {
-        return new ConfigConditionRouter(dynamicConfiguration, url);
+    protected synchronized void init() {
+        String appKey = url.getParameter(Constants.APPLICATION_KEY) + Constants.ROUTERS_SUFFIX;
+        String appRawRule = configuration.getConfig(appKey);
+        if (appRawRule != null) {
+            this.process(new ConfigChangeEvent(appKey, appRawRule));
+        }
+
+        configuration.addListener(appKey, this);
     }
+
 }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppConfigConditionRouterFactory.java
similarity index 76%
copy from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java
copy to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppConfigConditionRouterFactory.java
index 7861227..bc62bcb 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppConfigConditionRouterFactory.java
@@ -19,21 +19,18 @@ package org.apache.dubbo.rpc.cluster.router.condition.config;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.extension.Activate;
 import org.apache.dubbo.configcenter.DynamicConfiguration;
+import org.apache.dubbo.rpc.cluster.AbstractAppRouterFactory;
 import org.apache.dubbo.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
 
 /**
  *
  */
 @Activate(order = 200)
-public class ConfigConditionRouterFactory implements RouterFactory {
-    @Override
-    public Router getRouter(URL url) {
-        return null;
-    }
+public class AppConfigConditionRouterFactory extends AbstractAppRouterFactory {
+    public static final String NAME = "app-config-condition";
 
     @Override
-    public Router getRouter(DynamicConfiguration dynamicConfiguration, URL url) {
-        return new ConfigConditionRouter(dynamicConfiguration, url);
+    protected Router createRouter(URL url) {
+        return new AppConfigConditionRouter(DynamicConfiguration.getDynamicConfiguration(), url);
     }
 }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouter.java
deleted file mode 100644
index 91fe434..0000000
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouter.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.dubbo.rpc.cluster.router.condition.config;
-
-import org.apache.dubbo.common.Constants;
-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.CollectionUtils;
-import org.apache.dubbo.configcenter.ConfigChangeEvent;
-import org.apache.dubbo.configcenter.ConfigChangeType;
-import org.apache.dubbo.configcenter.ConfigurationListener;
-import org.apache.dubbo.configcenter.DynamicConfiguration;
-import org.apache.dubbo.rpc.Invocation;
-import org.apache.dubbo.rpc.Invoker;
-import org.apache.dubbo.rpc.RpcException;
-import org.apache.dubbo.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.router.AbstractRouter;
-import org.apache.dubbo.rpc.cluster.router.TreeNode;
-import org.apache.dubbo.rpc.cluster.router.condition.ConditionRouter;
-import org.apache.dubbo.rpc.cluster.router.condition.config.model.ConditionRouterRule;
-import org.apache.dubbo.rpc.cluster.router.condition.config.model.ConditionRuleParser;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- *
- */
-public class ConfigConditionRouter extends AbstractRouter implements ConfigurationListener {
-    public static final String NAME = "CONFIG_CONDITION_OUTER";
-    public static final int DEFAULT_PRIORITY = 200;
-    private static final Logger logger = LoggerFactory.getLogger(ConfigConditionRouter.class);
-    private DynamicConfiguration configuration;
-    private ConditionRouterRule routerRule;
-    private ConditionRouterRule appRouterRule;
-    private List<ConditionRouter> conditionRouters = new ArrayList<>();
-    private List<ConditionRouter> appConditionRouters = new ArrayList<>();
-
-    public ConfigConditionRouter(DynamicConfiguration configuration, URL url) {
-        this.configuration = configuration;
-        this.force = false;
-        this.url = url;
-
-        synchronized (this) {
-            String appKey = url.getParameter(Constants.APPLICATION_KEY) + Constants.ROUTERS_SUFFIX;
-            configuration.addListener(appKey, this);
-            String appRawRule = configuration.getConfig(appKey);
-            if (appRawRule != null) {
-                this.process(new ConfigChangeEvent(appKey, appRawRule));
-            }
-            String key = url.getEncodedServiceKey() + Constants.ROUTERS_SUFFIX;
-            configuration.addListener(key, this);
-            String rawRule = configuration.getConfig(key);
-            if (rawRule != null) {
-                this.process(new ConfigChangeEvent(key, rawRule));
-            }
-        }
-    }
-
-    @Override
-    public synchronized void process(ConfigChangeEvent event) {
-        if (logger.isInfoEnabled()) {
-            logger.info("Notification of condition rule, change type is: " + event.getChangeType() + ", raw rule is:\n " + event.getNewValue());
-        }
-
-        if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
-            // Now, we can only recognize if it's a app level or service level change by try to match event key.
-            if (event.getKey().endsWith(this.url.getParameter(Constants.APPLICATION_KEY) + Constants.ROUTERS_SUFFIX)) {
-                appRouterRule = null;
-                conditionRouters.clear();
-            } else {
-                routerRule = null;
-                appConditionRouters.clear();
-            }
-        } else {
-            try {
-                if (event.getKey().endsWith(this.url.getParameter(Constants.APPLICATION_KEY) + Constants.ROUTERS_SUFFIX)) {
-                    appRouterRule = ConditionRuleParser.parse(event.getNewValue());
-                    generateAppConditions();
-                } else {
-                    routerRule = ConditionRuleParser.parse(event.getNewValue());
-                    generateConditions();
-                }
-            } catch (Exception e) {
-                logger.error("Failed to parse the raw condition rule and it will not take effect, please check if the condition rule matches with the template, the raw rule is:\n " + event.getNewValue(), e);
-            }
-        }
-
-        if (routerChain != null) {
-            routerChain.notifyRuleChanged();
-        }
-    }
-
-    @Override
-    public <T> Map<String, List<Invoker<T>>> preRoute(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
-        Map<String, List<Invoker<T>>> map = new HashMap<>();
-
-        if (CollectionUtils.isEmpty(invokers)
-                || (conditionRouters.size() == 0 && appConditionRouters.size() == 0)
-                || isRuntime()) {
-            map.put(TreeNode.FAILOVER_KEY, invokers);
-            return map;
-        }
-
-        // only one branch, always use the failover key
-        if (isAppRuleEnabled()) {
-            for (Router router : appConditionRouters) {
-                invokers = router.route(invokers, url, invocation);
-            }
-        }
-        if (isRuleEnabled()) {
-            for (Router router : conditionRouters) {
-                invokers = router.route(invokers, url, invocation);
-            }
-        }
-        map.put(TreeNode.FAILOVER_KEY, invokers);
-
-        return map;
-    }
-
-    @Override
-    public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
-        if (CollectionUtils.isEmpty(invokers)
-                || (conditionRouters.size() == 0 && appConditionRouters.size() == 0)
-                || !isEnabled()) {
-            return invokers;
-        }
-
-        if (isAppRuleEnabled()) {
-            for (Router router : appConditionRouters) {
-                invokers = router.route(invokers, url, invocation);
-            }
-        }
-        if (isRuleEnabled()) {
-            for (Router router : conditionRouters) {
-                invokers = router.route(invokers, url, invocation);
-            }
-        }
-        return invokers;
-    }
-
-    @Override
-    public String getName() {
-        return NAME;
-    }
-
-    @Override
-    public int getPriority() {
-        return DEFAULT_PRIORITY;
-    }
-
-    @Override
-    public boolean isRuntime() {
-        return isRuleRuntime() || isAppRuleRuntime();
-    }
-
-    @Override
-    public boolean isEnabled() {
-        return isAppRuleEnabled() || isRuleEnabled();
-    }
-
-    @Override
-    public String getKey() {
-        if (isRuntime()) {
-            return super.getKey();
-        }
-        return TreeNode.FAILOVER_KEY;
-    }
-
-    @Override
-    public boolean isForce() {
-        return (routerRule != null && routerRule.isForce())
-                || (appRouterRule != null && appRouterRule.isForce());
-    }
-
-    private boolean isAppRuleEnabled() {
-        return appRouterRule != null && appRouterRule.isValid() && appRouterRule.isEnabled();
-    }
-
-    private boolean isRuleEnabled() {
-        return routerRule != null && routerRule.isValid() && routerRule.isEnabled();
-    }
-
-    private boolean isAppRuleRuntime() {
-        return appRouterRule != null && appRouterRule.isValid() && appRouterRule.isRuntime();
-    }
-
-    private boolean isRuleRuntime() {
-        return routerRule != null && routerRule.isValid() && routerRule.isRuntime();
-    }
-
-    private void generateConditions() {
-        if (routerRule != null && routerRule.isValid()) {
-            conditionRouters.clear();
-            routerRule.getConditions().forEach(condition -> {
-                // All sub rules have the same force, runtime value.
-                ConditionRouter subRouter = new ConditionRouter(condition, routerRule.isForce());
-                conditionRouters.add(subRouter);
-            });
-        }
-    }
-
-    private void generateAppConditions() {
-        if (appRouterRule != null && appRouterRule.isValid()) {
-            appConditionRouters.clear();
-            appRouterRule.getConditions().forEach(condition -> {
-                // All sub rules have the same force, runtime value.
-                ConditionRouter subRouter = new ConditionRouter(condition, appRouterRule.isForce());
-                appConditionRouters.add(subRouter);
-            });
-        }
-    }
-}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceConfigConditionRouter.java
similarity index 61%
copy from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java
copy to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceConfigConditionRouter.java
index 7861227..447973d 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceConfigConditionRouter.java
@@ -16,24 +16,28 @@
  */
 package org.apache.dubbo.rpc.cluster.router.condition.config;
 
+import org.apache.dubbo.common.Constants;
 import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.extension.Activate;
+import org.apache.dubbo.configcenter.ConfigChangeEvent;
 import org.apache.dubbo.configcenter.DynamicConfiguration;
-import org.apache.dubbo.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
 
 /**
  *
  */
-@Activate(order = 200)
-public class ConfigConditionRouterFactory implements RouterFactory {
-    @Override
-    public Router getRouter(URL url) {
-        return null;
+public class ServiceConfigConditionRouter extends AbstractConfigConditionRouter {
+
+    public ServiceConfigConditionRouter(DynamicConfiguration configuration, URL url) {
+        super(configuration, url);
     }
 
-    @Override
-    public Router getRouter(DynamicConfiguration dynamicConfiguration, URL url) {
-        return new ConfigConditionRouter(dynamicConfiguration, url);
+    protected synchronized void init() {
+        String key = url.getEncodedServiceKey() + Constants.ROUTERS_SUFFIX;
+        String rawRule = configuration.getConfig(key);
+        if (rawRule != null) {
+            this.process(new ConfigChangeEvent(key, rawRule));
+        }
+
+        configuration.addListener(key, this);
     }
+
 }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceConfigConditionRouterFactory.java
similarity index 74%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceConfigConditionRouterFactory.java
index 7861227..d16e5a2 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConfigConditionRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceConfigConditionRouterFactory.java
@@ -19,21 +19,20 @@ package org.apache.dubbo.rpc.cluster.router.condition.config;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.extension.Activate;
 import org.apache.dubbo.configcenter.DynamicConfiguration;
+import org.apache.dubbo.rpc.cluster.AbstractRouterFactory;
 import org.apache.dubbo.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
 
 /**
  *
  */
-@Activate(order = 200)
-public class ConfigConditionRouterFactory implements RouterFactory {
-    @Override
-    public Router getRouter(URL url) {
-        return null;
-    }
+@Activate(order = 300)
+public class ServiceConfigConditionRouterFactory extends AbstractRouterFactory {
+
+    public static final String NAME = "config-condition";
 
     @Override
-    public Router getRouter(DynamicConfiguration dynamicConfiguration, URL url) {
-        return new ConfigConditionRouter(dynamicConfiguration, url);
+    protected Router createRouter(URL url) {
+        return new ServiceConfigConditionRouter(DynamicConfiguration.getDynamicConfiguration(), url);
     }
+
 }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/BlackWhiteListRule.java
similarity index 91%
copy from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java
copy to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/BlackWhiteListRule.java
index 7455585..d656aa7 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/BlackWhiteListRule.java
@@ -23,10 +23,7 @@ import java.util.List;
 /**
  *
  */
-public class ConditionRouterRule extends AbstractRouterRule {
-    public ConditionRouterRule() {
-    }
-
+public class BlackWhiteListRule extends AbstractRouterRule {
     private List<String> conditions;
 
     public List<String> getConditions() {
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java
index 7455585..97518b7 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java
@@ -27,6 +27,7 @@ public class ConditionRouterRule extends AbstractRouterRule {
     public ConditionRouterRule() {
     }
 
+    private BlackWhiteListRule blackWhiteListRule;
     private List<String> conditions;
 
     public List<String> getConditions() {
@@ -36,4 +37,12 @@ public class ConditionRouterRule extends AbstractRouterRule {
     public void setConditions(List<String> conditions) {
         this.conditions = conditions;
     }
+
+    public BlackWhiteListRule getBlackWhiteListRule() {
+        return blackWhiteListRule;
+    }
+
+    public void setBlackWhiteListRule(BlackWhiteListRule blackWhiteListRule) {
+        this.blackWhiteListRule = blackWhiteListRule;
+    }
 }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java
index 859b7f3..074c1fc 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java
@@ -17,6 +17,7 @@
 package org.apache.dubbo.rpc.cluster.router.condition.config.model;
 
 import org.apache.dubbo.common.utils.CollectionUtils;
+
 import org.yaml.snakeyaml.Yaml;
 import org.yaml.snakeyaml.constructor.Constructor;
 
@@ -45,6 +46,11 @@ public class ConditionRuleParser {
         if (CollectionUtils.isEmpty(rule.getConditions())) {
             rule.setValid(false);
         }
+
+        BlackWhiteListRule blackWhiteList = rule.getBlackWhiteListRule();
+        if (blackWhiteList != null && CollectionUtils.isEmpty(blackWhiteList.getConditions())) {
+            blackWhiteList.setValid(false);
+        }
         return rule;
     }
 
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java
index a479136..a1b1be2 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java
@@ -90,11 +90,6 @@ public class MockInvokersSelector extends AbstractRouter {
         return hasMockProvider;
     }
 
-    @Override
-    public String getName() {
-        return NAME;
-    }
-
     /**
      * Always stay on the top of the list
      *
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockRouterFactory.java
index 967bc2f..238634a 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockRouterFactory.java
@@ -18,7 +18,6 @@ package org.apache.dubbo.rpc.cluster.router.mock;
 
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.extension.Activate;
-import org.apache.dubbo.configcenter.DynamicConfiguration;
 import org.apache.dubbo.rpc.cluster.Router;
 import org.apache.dubbo.rpc.cluster.RouterFactory;
 
@@ -33,8 +32,4 @@ public class MockRouterFactory implements RouterFactory {
         return new MockInvokersSelector();
     }
 
-    @Override
-    public Router getRouter(DynamicConfiguration dynamicConfiguration, URL url) {
-        return getRouter(url);
-    }
 }
\ No newline at end of file
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java
index 7f1ceca..05815df 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java
@@ -113,11 +113,6 @@ public class ScriptRouter extends AbstractRouter {
     }
 
     @Override
-    public String getName() {
-        return NAME;
-    }
-
-    @Override
     public boolean isRuntime() {
         return this.url.getParameter(Constants.RUNTIME_KEY, false);
     }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java
index 1c86eb1..681200c 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java
@@ -18,7 +18,6 @@ package org.apache.dubbo.rpc.cluster.router.tag;
 
 import org.apache.dubbo.common.Constants;
 import org.apache.dubbo.common.URL;
-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;
@@ -27,21 +26,17 @@ import org.apache.dubbo.configcenter.ConfigChangeEvent;
 import org.apache.dubbo.configcenter.ConfigChangeType;
 import org.apache.dubbo.configcenter.ConfigurationListener;
 import org.apache.dubbo.configcenter.DynamicConfiguration;
-import org.apache.dubbo.configcenter.DynamicConfigurationFactory;
 import org.apache.dubbo.rpc.Invocation;
 import org.apache.dubbo.rpc.Invoker;
 import org.apache.dubbo.rpc.RpcException;
 import org.apache.dubbo.rpc.cluster.Router;
+import org.apache.dubbo.rpc.cluster.RouterChain;
 import org.apache.dubbo.rpc.cluster.router.AbstractRouter;
-import org.apache.dubbo.rpc.cluster.router.TreeNode;
 import org.apache.dubbo.rpc.cluster.router.tag.model.TagRouterRule;
 import org.apache.dubbo.rpc.cluster.router.tag.model.TagRuleParser;
 
-import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.function.Predicate;
 import java.util.stream.Collectors;
 
@@ -53,66 +48,34 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
     private static final int DEFAULT_PRIORITY = 100;
     private static final Logger logger = LoggerFactory.getLogger(TagRouter.class);
     private static final String TAGROUTERRULES_DATAID = ".tagrouters"; // acts
-    private DynamicConfiguration configuration;
     private TagRouterRule tagRouterRule;
     private String application;
 
-    private AtomicBoolean inited = new AtomicBoolean(false);
-
-    /**
-     * compatible constructor, it should never be called to create TagRouter.
-     *
-     * @param url
-     */
-    public TagRouter(URL url) {
-        this(ExtensionLoader.getExtensionLoader(DynamicConfigurationFactory.class).getDefaultExtension().getDynamicConfiguration(url), url);
-    }
+    private boolean inited = false;
 
     public TagRouter(DynamicConfiguration configuration, URL url) {
-        setConfiguration(configuration);
-        this.url = url;
+        super(configuration, url);
     }
 
     protected TagRouter() {
     }
 
-    public void setConfiguration(DynamicConfiguration configuration) {
-        this.configuration = configuration;
-    }
-
-    private void init() {
-        if (!inited.compareAndSet(false, true)) {
-            return;
-        }
-        if (StringUtils.isEmpty(application)) {
-            logger.error("TagRouter must getConfig from or subscribe to a specific application, but the application in this TagRouter is not specified.");
-        }
-
-        synchronized (this) {
-            String key = application + TAGROUTERRULES_DATAID;
-            configuration.addListener(key, this);
-            String rawRule = configuration.getConfig(key);
-            if (rawRule != null) {
-                this.process(new ConfigChangeEvent(key, rawRule));
-            }
-        }
-    }
-
     @Override
     public synchronized void process(ConfigChangeEvent event) {
-        if (logger.isInfoEnabled()) {
-            logger.info("Notification of tag rule, change type is: " + event.getChangeType() + ", raw rule is:\n " + event.getNewValue());
+        if (logger.isDebugEnabled()) {
+            logger.debug("Notification of tag rule, change type is: " + event.getChangeType() + ", raw rule is:\n " + event
+                    .getValue());
         }
 
         try {
             if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
                 this.tagRouterRule = null;
             } else {
-                this.tagRouterRule = TagRuleParser.parse(event.getNewValue());
-            }
-            if (routerChain != null) {
-                routerChain.notifyRuleChanged();
+                this.tagRouterRule = TagRuleParser.parse(event.getValue());
             }
+
+            routerChains.forEach(RouterChain::notifyRuleChanged);
+
         } catch (Exception e) {
             logger.error("Failed to parse the raw tag router rule and it will not take effect, please check if the rule matches with the template, the raw rule is:\n ", e);
         }
@@ -124,8 +87,6 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
     }
 
     /**
-     * TODO It seems that this router does not need to run at runtime at all, because preRoute already classified each invoker into the right tag.
-     * preRoute will always be executed ignoring the runtime status in rule.
      *
      * @param invokers
      * @param url
@@ -140,8 +101,6 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
             return invokers;
         }
 
-        checkAndInit(invokers.get(0).getUrl());
-
         if (tagRouterRule == null || !tagRouterRule.isValid() || !tagRouterRule.isEnabled()) {
             // the invokers must have been preRouted by static tag configuration, so this invoker list is just what we want.
             return invokers;
@@ -159,17 +118,22 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
                 if (CollectionUtils.isNotEmpty(result) || tagRouterRule.isForce()) {
                     return result;
                 }
+            } else {
+                // dynamic tag group doesn't have any item about the requested app OR it's null after filtered by dynamic tag group but force=false.
+                // check static tag
+                result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl()
+                        .getParameter(Constants.TAG_KEY)));
             }
-            // dynamic tag group doesn't have any item about the requested app OR it's null after filtered by dynamic tag group but force=false.
-            // check static tag
-            result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(Constants.TAG_KEY)));
-            // If there's no tagged providers that can match the value in this tag. force.tag is set by default to true, which means it will not invoker any providers without a tag unless it's explicitly allowed.
+            // If there's no tagged providers that can match the current tagged request. force.tag is set by default to false, which means it will invoke any providers without a tag unless it's explicitly disallowed.
             if (CollectionUtils.isNotEmpty(result) || Boolean.valueOf(invocation.getAttachment(Constants.FORCE_USE_TAG, url.getParameter(Constants.FORCE_USE_TAG, "false")))) {
                 return result;
             }
             // FAILOVER: return all Providers without any tags.
             else {
-                return filterInvoker(invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(Constants.TAG_KEY)));
+                List<Invoker<T>> tmp = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(), tagRouterRule
+                        .getAddresses()));
+                return filterInvoker(tmp, invoker -> StringUtils.isEmpty(invoker.getUrl()
+                        .getParameter(Constants.TAG_KEY)));
             }
         } else {
             // List<String> addresses = tagRouterRule.filter(providerApp);
@@ -193,72 +157,23 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
         }
     }
 
+    /**
+     * This method is reserved for building router cache.
+     * Currently, we rely on this method to do the init task since it will get triggered before route() really happens.
+     *
+     * @param invokers
+     * @param url
+     * @param invocation
+     * @param <T>
+     * @return
+     * @throws RpcException
+     */
     @Override
     public <T> Map<String, List<Invoker<T>>> preRoute(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
-        Map<String, List<Invoker<T>>> map = new HashMap<>();
-
-        if (CollectionUtils.isEmpty(invokers)) {
-            return map;
+        if (CollectionUtils.isNotEmpty(invokers)) {
+            checkAndInit(invokers.get(0).getUrl());
         }
-
-        checkAndInit(invokers.get(0).getUrl());
-
-        // Notice! we don't check runtime status here, because we will always need preRoute to run for the dynamic tag configuration.
-        // So, only default to the static tag configuration when the dynamic configuration is empty.
-        if (tagRouterRule == null || !tagRouterRule.isValid() || !tagRouterRule.isEnabled()) {
-            // We still need to group invokers by static tag configuration
-            invokers.forEach(invoker -> {
-                String tag = invoker.getUrl().getParameter(Constants.TAG_KEY);
-                if (StringUtils.isEmpty(tag)) {
-                    tag = TreeNode.FAILOVER_KEY;
-                }
-                List<Invoker<T>> subInvokers = map.computeIfAbsent(tag, t -> new ArrayList<>());
-                subInvokers.add(invoker);
-            });
-            return map;
-        }
-
-        /**
-         * If tag rule can work, then group invokers by,
-         * 1. dynamic tag group
-         * 2. static tag group
-         */
-        invokers.forEach(invoker -> {
-            String address = invoker.getUrl().getAddress();
-            List<String> tags = tagRouterRule.getAddressToTagnames().get(address);
-            if (CollectionUtils.isEmpty(tags)) {
-                String tag = invoker.getUrl().getParameter(Constants.TAG_KEY);
-                // we have checked that this address is not included in any of the tag listed in dynamic tag group.
-                // so if found this address were grouped into one tag in dynamic tag group, we think it's invalid, which means, dynamic tag group will override static tag group (the dynamic config may have explicitly removed this address from one or another group).
-                if (tagRouterRule.getTagNames().contains(tag) || StringUtils.isEmpty(tag)) {
-                    tag = TreeNode.FAILOVER_KEY;
-                }
-                tags = new ArrayList<>();
-                tags.add(tag);
-            }
-
-            tags.forEach(tag -> {
-                List<Invoker<T>> subInvokers = map.computeIfAbsent(tag, k -> new ArrayList<>());
-                subInvokers.add(invoker);
-            });
-        });
-
-        // Now, FAILOVER key is required here.
-//        map.putIfAbsent(TreeNode.FAILOVER_KEY, Collections.emptyList());
-
-        return map;
-    }
-
-    public void checkAndInit(URL providerUrl) {
-        if (StringUtils.isEmpty(application)) {
-            setApplication(providerUrl.getParameter(Constants.REMOTE_APPLICATION_KEY));
-        }
-        this.init();
-    }
-
-    @Override
-    public String getName() {
-        return NAME;
+        return super.preRoute(invokers, url, invocation);
     }
 
     @Override
@@ -273,14 +188,6 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
     }
 
     @Override
-    public String getKey() {
-        /*if (isRuntime()) {
-            return super.getKey();
-        }*/
-        return Constants.TAG_KEY;
-    }
-
-    @Override
     public boolean isForce() {
         // FIXME
         return tagRouterRule != null && tagRouterRule.isForce();
@@ -293,14 +200,38 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
     }
 
     private boolean addressMatches(URL url, List<String> addresses) {
-        return addresses.contains(url.getAddress());
+        return addresses != null && addresses.contains(url.getAddress());
     }
 
     private boolean addressNotMatches(URL url, List<String> addresses) {
-        return !addresses.contains(url.getAddress());
+        return addresses == null || !addresses.contains(url.getAddress());
     }
 
     public void setApplication(String app) {
         this.application = app;
     }
+
+    private synchronized void checkAndInit(URL url) {
+        String providerApplication = url.getParameter(Constants.REMOTE_APPLICATION_KEY);
+        if (StringUtils.isEmpty(application) || !providerApplication.equals(application)) {
+            setApplication(providerApplication);
+            inited = false;
+        }
+
+        if (StringUtils.isEmpty(application)) {
+            logger.error("TagRouter must getConfig from or subscribe to a specific application, but the application in this TagRouter is not specified.");
+            return;
+        }
+
+        if (!inited) {
+            inited = true;
+            String key = application + TAGROUTERRULES_DATAID;
+            configuration.addListener(key, this);
+            String rawRule = configuration.getConfig(key);
+            if (rawRule != null) {
+                this.process(new ConfigChangeEvent(key, rawRule));
+            }
+        }
+    }
+
 }
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java
index 208829a..a052758 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java
@@ -19,28 +19,19 @@ package org.apache.dubbo.rpc.cluster.router.tag;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.extension.Activate;
 import org.apache.dubbo.configcenter.DynamicConfiguration;
+import org.apache.dubbo.rpc.cluster.AbstractRouterFactory;
 import org.apache.dubbo.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
 
 /**
  *
  */
 @Activate(order = 100)
-public class TagRouterFactory implements RouterFactory {
+public class TagRouterFactory extends AbstractRouterFactory {
 
     public static final String NAME = "tag";
 
     @Override
-    public Router getRouter(URL url) {
-        return new TagRouter(url);
-    }
-
-    @Override
-    public Router getRouter(DynamicConfiguration dynamicConfiguration, URL url) {
-        TagRouter router = new TagRouter(dynamicConfiguration, url);
-/*        TagRouter router = (TagRouter) ExtensionLoader.getExtensionLoader(Router.class).getExtension(NAME);
-        router.setConfiguration(dynamicConfiguration);
-        router.setUrl(url);*/
-        return router;
+    protected Router createRouter(URL url) {
+        return new TagRouter(DynamicConfiguration.getDynamicConfiguration(), url);
     }
 }
diff --git a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RouterFactory b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RouterFactory
index 4a27434..90dd59f 100644
--- a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RouterFactory
+++ b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RouterFactory
@@ -1,6 +1,7 @@
 file=org.apache.dubbo.rpc.cluster.router.file.FileRouterFactory
 script=org.apache.dubbo.rpc.cluster.router.script.ScriptRouterFactory
 condition=org.apache.dubbo.rpc.cluster.router.condition.ConditionRouterFactory
-configcondition=org.apache.dubbo.rpc.cluster.router.condition.config.ConfigConditionRouterFactory
+configcondition=org.apache.dubbo.rpc.cluster.router.condition.config.ServiceConfigConditionRouterFactory
+appconfigcondition=org.apache.dubbo.rpc.cluster.router.condition.config.AppConfigConditionRouterFactory
 tag=org.apache.dubbo.rpc.cluster.router.tag.TagRouterFactory
 mock=org.apache.dubbo.rpc.cluster.router.mock.MockRouterFactory
\ No newline at end of file
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java
index 2c56ba0..809437f 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java
@@ -63,7 +63,7 @@ public class ConfigParserTest {
     @Test
     public void parseConfiguratorsServiceNoAppTest() throws Exception {
         InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoApp.yml");
-        List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream), "serviceKey");
+        List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
         Assert.assertNotNull(urls);
         Assert.assertEquals(2, urls.size());
         URL url = urls.get(0);
@@ -74,7 +74,7 @@ public class ConfigParserTest {
     @Test
     public void parseConfiguratorsServiceGroupVersionTest() throws Exception {
         InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceGroupVersion.yml");
-        List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream), "testgroup/servicekey:1.0.0");
+        List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
         Assert.assertNotNull(urls);
         Assert.assertEquals(1, urls.size());
         URL url = urls.get(0);
@@ -85,7 +85,7 @@ public class ConfigParserTest {
     @Test
     public void parseConfiguratorsServiceMultiAppsTest() {
         InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceMultiApps.yml");
-        List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream), "serviceKey");
+        List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
         Assert.assertNotNull(urls);
         Assert.assertEquals(4, urls.size());
         URL url = urls.get(0);
@@ -97,7 +97,7 @@ public class ConfigParserTest {
     @Test(expected = IllegalStateException.class)
     public void parseConfiguratorsServiceNoRuleTest() {
         InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoRule.yml");
-        ConfigParser.parseConfigurators(streamToString(yamlStream), "serviceKey");
+        ConfigParser.parseConfigurators(streamToString(yamlStream));
         Assert.fail();
     }
 
@@ -105,7 +105,7 @@ public class ConfigParserTest {
     public void parseConfiguratorsAppMultiServicesTest() {
         InputStream yamlStream = this.getClass().getResourceAsStream("/AppMultiServices.yml");
         String yamlFile = streamToString(yamlStream);
-        List<URL> urls = ConfigParser.parseConfigurators(yamlFile, "service1");
+        List<URL> urls = ConfigParser.parseConfigurators(yamlFile);
         Assert.assertNotNull(urls);
         Assert.assertEquals(2, urls.size());
         URL url = urls.get(0);
@@ -115,7 +115,7 @@ public class ConfigParserTest {
         Assert.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY));
         Assert.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer");
 
-        List<URL> urls2 = ConfigParser.parseConfigurators(yamlFile, "service-not-exist");
+        List<URL> urls2 = ConfigParser.parseConfigurators(yamlFile);
         Assert.assertNotNull(urls2);
         Assert.assertEquals(0, urls2.size());
     }
@@ -124,7 +124,7 @@ public class ConfigParserTest {
     @Test
     public void parseConfiguratorsAppAnyServicesTest() {
         InputStream yamlStream = this.getClass().getResourceAsStream("/AppAnyServices.yml");
-        List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream), "service1");
+        List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
         Assert.assertNotNull(urls);
         Assert.assertEquals(2, urls.size());
         URL url = urls.get(0);
@@ -138,7 +138,7 @@ public class ConfigParserTest {
     @Test
     public void parseConfiguratorsAppNoServiceTest() {
         InputStream yamlStream = this.getClass().getResourceAsStream("/AppNoService.yml");
-        List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream), "service1");
+        List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
         Assert.assertNotNull(urls);
         Assert.assertEquals(1, urls.size());
         URL url = urls.get(0);
@@ -152,7 +152,7 @@ public class ConfigParserTest {
     @Test
     public void parseConsumerSpecificProvidersTest() {
         InputStream yamlStream = this.getClass().getResourceAsStream("/ConsumerSpecificProviders.yml");
-        List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream), "service1");
+        List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
         Assert.assertNotNull(urls);
         Assert.assertEquals(1, urls.size());
         URL url = urls.get(0);
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java
index 5d8db16..83a1424 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java
@@ -19,7 +19,6 @@ package org.apache.dubbo.rpc.cluster.router.file;
 import org.apache.dubbo.common.Constants;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.extension.ExtensionLoader;
-import org.apache.dubbo.configcenter.DynamicConfigurationFactory;
 import org.apache.dubbo.rpc.Invocation;
 import org.apache.dubbo.rpc.Invoker;
 import org.apache.dubbo.rpc.Result;
@@ -40,9 +39,7 @@ import org.junit.Test;
 import javax.script.ScriptEngineManager;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.HashMap;
 import java.util.List;
-import java.util.Map;
 
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
@@ -162,11 +159,8 @@ public class FileRouterEngineTest {
     }
 
     private void initDic(URL url) {
-        dic = new StaticDirectory<FileRouterEngineTest>(url, invokers);
-        Map<String, List<Invoker<FileRouterEngineTest>>> methodInvokers = new HashMap<>();
-        methodInvokers.put("method1", invokers);
-        methodInvokers.put("method2", invokers);
-        dic.buildRouterChain(methodInvokers, ExtensionLoader.getExtensionLoader(DynamicConfigurationFactory.class).getDefaultExtension().getDynamicConfiguration(null));
+        dic = new StaticDirectory<>(url, invokers);
+        dic.buildRouterChain(invokers);
         dic.getRouterChain().setResidentRouters(Arrays.asList(routerFactory.getRouter(url)));
     }
 
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java
index af81795..655e649 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java
@@ -20,7 +20,6 @@ import org.apache.dubbo.common.Constants;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.extension.ExtensionLoader;
 import org.apache.dubbo.common.utils.NetUtils;
-import org.apache.dubbo.configcenter.DynamicConfigurationFactory;
 import org.apache.dubbo.rpc.Invocation;
 import org.apache.dubbo.rpc.Invoker;
 import org.apache.dubbo.rpc.Result;
@@ -43,7 +42,6 @@ import org.junit.Test;
 import org.mockito.Mockito;
 
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
@@ -457,9 +455,7 @@ public class AbstractClusterInvokerTest {
     }
 
     private void initDic() {
-        Map<String, List<Invoker<IHelloService>>> map = new HashMap<>();
-        map.put("sayHello", invokers);
-        dic.buildRouterChain(map, ExtensionLoader.getExtensionLoader(DynamicConfigurationFactory.class).getDefaultExtension().getDynamicConfiguration(null));
+        dic.buildRouterChain(invokers);
     }
 
     @Test()
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java
index 1546f7a..cf5c8a0 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java
@@ -19,7 +19,6 @@ package org.apache.dubbo.rpc.cluster.support.wrapper;
 import org.apache.dubbo.common.Constants;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.extension.ExtensionLoader;
-import org.apache.dubbo.configcenter.DynamicConfigurationFactory;
 import org.apache.dubbo.rpc.Invocation;
 import org.apache.dubbo.rpc.Invoker;
 import org.apache.dubbo.rpc.Protocol;
@@ -36,12 +35,9 @@ import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.HashMap;
 import java.util.List;
-import java.util.Map;
 
 public class MockClusterInvokerTest {
 
@@ -656,12 +652,7 @@ public class MockClusterInvokerTest {
         }
 
         StaticDirectory<IHelloService> dic = new StaticDirectory<IHelloService>(durl, invokers, null);
-        Map<String, List<Invoker<IHelloService>>> methodInvokers = new HashMap<>();
-        Method[] methods = IHelloService.class.getMethods();
-        Arrays.stream(methods).forEach(m -> {
-            methodInvokers.put(m.getName(), invokers);
-        });
-        dic.buildRouterChain(methodInvokers, ExtensionLoader.getExtensionLoader(DynamicConfigurationFactory.class).getDefaultExtension().getDynamicConfiguration(null));
+        dic.buildRouterChain(invokers);
         AbstractClusterInvoker<IHelloService> cluster = new AbstractClusterInvoker(dic) {
             @Override
             protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance)
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java
index 6b5f8f6..98413c5 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java
@@ -66,7 +66,7 @@ public class Constants {
     public static final String CONFIG_GROUP_KEY = "config.group";
     public static final String CONFIG_CHECK_KEY = "config.check";
     public static final String CONFIG_CONFIGFILE_KEY = "config.configfile";
-    public static final String CONFIG_PRIORITY_KEY = "config.priority";
+    public static final String CONFIG_ENABLE_KEY = "config.enable";
     public static final String CONFIG_TIMEOUT_KEY = "config.timeout";
     public static final String CONFIG_APPNAME_KEY = "config.appname";
 
@@ -732,12 +732,20 @@ public class Constants {
 
     public static final String CYCLE_REPORT_KEY = "cycle-report";
 
-    public static final String API_VERSION_KEY = "apiVersion";
+    public static final String CONFIG_VERSION_KEY = "configVersion";
+
+    public static final String COMPATIBLE_CONFIG_KEY = "compatible_config";
     // package version in the manifest
     public static final String SPECIFICATION_VERSION_KEY = "specVersion";
 
     public static final String OVERRIDE_PROVIDERS_KEY = "providerAddreses";
 
+    public static final String PROTOCOLS_SUFFIX = "dubbo.protocols.";
+
+    public static final String PROTOCOL_SUFFIX = "dubbo.protocol.";
+
+    public static final String REGISTRIES_SUFFIX = "dubbo.registries.";
+
     public static final String[] DEFAULT_REGISTER_PROVIDER_KEYS = {APPLICATION_KEY, CODEC_KEY, EXCHANGER_KEY, SERIALIZATION_KEY, CLUSTER_KEY, CONNECTIONS_KEY, DEPRECATED_KEY,
             GROUP_KEY, LOADBALANCE_KEY, MOCK_KEY, PATH_KEY, TIMEOUT_KEY, TOKEN_KEY, VERSION_KEY, WARMUP_KEY, WEIGHT_KEY, TIMESTAMP_KEY, DUBBO_VERSION_KEY, SPECIFICATION_VERSION_KEY};
 
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java
index c94cb58..0aaffc7 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java
@@ -1285,6 +1285,11 @@ public /**final**/ class URL implements Serializable {
         return new InetSocketAddress(host, port);
     }
 
+    /**
+     * The format is '{group}/{interfaceName/path}*{version}'
+     *
+     * @return
+     */
     public String getEncodedServiceKey() {
         String serviceKey = this.getServiceKey();
         serviceKey = serviceKey.replaceFirst("/", "*");
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java
new file mode 100644
index 0000000..f569eb5
--- /dev/null
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.dubbo.registry.integration;
+
+import org.apache.dubbo.common.Constants;
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.configcenter.ConfigChangeEvent;
+import org.apache.dubbo.configcenter.ConfigChangeType;
+import org.apache.dubbo.configcenter.ConfigurationListener;
+import org.apache.dubbo.rpc.cluster.configurator.parser.ConfigParser;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ *
+ */
+public abstract class AbstractConfiguratorListener implements ConfigurationListener {
+    private static final Logger logger = LoggerFactory.getLogger(AbstractConfiguratorListener.class);
+
+    @Override
+    public void process(ConfigChangeEvent event) {
+        if (logger.isInfoEnabled()) {
+            logger.info("Notification of overriding rule, change type is: " + event.getChangeType() + ", raw config content is:\n " + event
+                    .getValue());
+        }
+
+        List<URL> urls;
+        if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
+            urls = new ArrayList<>();
+            urls.add(new URL(Constants.EMPTY_PROTOCOL, Constants.ANYHOST_VALUE, 0));
+        } else {
+            try {
+                // parseConfigurators will recognize app/service config automatically.
+                urls = ConfigParser.parseConfigurators(event.getValue());
+            } catch (Exception e) {
+                logger.error("Failed to parse raw dynamic config and it will not take effect, the raw config is: " + event
+                        .getValue(), e);
+                return;
+            }
+        }
+
+        logger.debug("Successfully transformed override rule to urls, will do override now, the urls are: " + urls);
+        notifyOverrides(urls);
+    }
+
+    protected abstract void notifyOverrides(List<URL> urls);
+}
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java
index fea5824..c564a47 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java
@@ -26,8 +26,6 @@ import org.apache.dubbo.common.utils.CollectionUtils;
 import org.apache.dubbo.common.utils.NetUtils;
 import org.apache.dubbo.common.utils.StringUtils;
 import org.apache.dubbo.configcenter.ConfigChangeEvent;
-import org.apache.dubbo.configcenter.ConfigChangeType;
-import org.apache.dubbo.configcenter.ConfigurationListener;
 import org.apache.dubbo.configcenter.DynamicConfiguration;
 import org.apache.dubbo.registry.NotifyListener;
 import org.apache.dubbo.registry.Registry;
@@ -45,8 +43,8 @@ import org.apache.dubbo.rpc.cluster.configurator.parser.ConfigParser;
 import org.apache.dubbo.rpc.cluster.directory.AbstractDirectory;
 import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
 import org.apache.dubbo.rpc.cluster.support.ClusterUtils;
+import org.apache.dubbo.rpc.model.ApplicationModel;
 import org.apache.dubbo.rpc.protocol.InvokerWrapper;
-import org.apache.dubbo.rpc.support.RpcUtils;
 
 import java.util.ArrayList;
 import java.util.Collection;
@@ -57,24 +55,35 @@ import java.util.HashSet;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
+import java.util.Optional;
 import java.util.Set;
 import java.util.stream.Collectors;
 
-import static org.apache.dubbo.common.Constants.APPLICATION_KEY;
-import static org.apache.dubbo.common.Constants.CONFIGURATORS_SUFFIX;
+import static org.apache.dubbo.common.Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY;
+import static org.apache.dubbo.common.Constants.CATEGORY_KEY;
+import static org.apache.dubbo.common.Constants.CONFIGURATORS_CATEGORY;
+import static org.apache.dubbo.common.Constants.DEFAULT_CATEGORY;
+import static org.apache.dubbo.common.Constants.DYNAMIC_CONFIGURATORS_CATEGORY;
+import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY;
+import static org.apache.dubbo.common.Constants.ROUTERS_CATEGORY;
+import static org.apache.dubbo.common.Constants.ROUTE_PROTOCOL;
+import static org.apache.dubbo.common.utils.UrlUtils.classifyUrls;
+
 
 /**
  * RegistryDirectory
  */
-public class RegistryDirectory<T> extends AbstractDirectory<T> implements NotifyListener, ConfigurationListener {
+public class RegistryDirectory<T> extends AbstractDirectory<T> implements NotifyListener {
 
     private static final Logger logger = LoggerFactory.getLogger(RegistryDirectory.class);
 
     private static final Cluster cluster = ExtensionLoader.getExtensionLoader(Cluster.class).getAdaptiveExtension();
 
-    private static final RouterFactory routerFactory = ExtensionLoader.getExtensionLoader(RouterFactory.class).getAdaptiveExtension();
+    private static final RouterFactory routerFactory = ExtensionLoader.getExtensionLoader(RouterFactory.class)
+            .getAdaptiveExtension();
 
-    private static final ConfiguratorFactory configuratorFactory = ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class).getAdaptiveExtension();
+    private static final ConfiguratorFactory configuratorFactory = ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class)
+            .getAdaptiveExtension();
     private final String serviceKey; // Initialization at construction time, assertion not null
     private final Class<T> serviceType; // Initialization at construction time, assertion not null
     private final Map<String, String> queryMap; // Initialization at construction time, assertion not null
@@ -83,7 +92,6 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
     private final boolean multiGroup;
     private Protocol protocol; // Initialization at the time of injection, the assertion is not null
     private Registry registry; // Initialization at the time of injection, the assertion is not null
-    private DynamicConfiguration dynamicConfiguration;
     private volatile boolean forbidden = false;
 
     private volatile URL overrideDirectoryUrl; // Initialization at construction time, assertion not null, and always assign non null value
@@ -100,13 +108,17 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
 
     // Map<url, Invoker> cache service url to invoker mapping.
     private volatile Map<String, Invoker<T>> urlInvokerMap; // The initial value is null and the midway may be assigned to null, please use the local variable reference
+    private volatile List<Invoker<T>> invokers;
 
     // Map<methodName, Invoker> cache service method to invokers mapping.
-    private volatile Map<String, List<Invoker<T>>> methodInvokerMap; // The initial value is null and the midway may be assigned to null, please use the local variable reference
+//    private volatile Map<String, List<Invoker<T>>> methodInvokerMap; // The initial value is null and the midway may be assigned to null, please use the local variable reference
 
     // Set<invokerUrls> cache invokeUrls to invokers mapping.
     private volatile Set<URL> cachedInvokerUrls; // The initial value is null and the midway may be assigned to null, please use the local variable reference
 
+    private static final ConsumerConfigurationListener consumerConfigurationListener = new ConsumerConfigurationListener();
+
+
     public RegistryDirectory(Class<T> serviceType, URL url) {
         super(url);
         if (serviceType == null) {
@@ -123,6 +135,8 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
         this.multiGroup = group != null && ("*".equals(group) || group.contains(","));
         String methods = queryMap.get(Constants.METHODS_KEY);
         this.serviceMethods = methods == null ? null : Constants.COMMA_SPLIT_PATTERN.split(methods);
+
+        consumerConfigurationListener.addNotifyListener(this);
     }
 
     /**
@@ -136,9 +150,9 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
      *             </br>4.override://0.0.0.0/ without parameters means clearing the override
      * @return
      */
-    public static List<Configurator> toConfigurators(List<URL> urls) {
-        if (urls == null || urls.isEmpty()) {
-            return Collections.emptyList();
+    public static Optional<List<Configurator>> toConfigurators(List<URL> urls) {
+        if (CollectionUtils.isEmpty(urls)) {
+            return Optional.empty();
         }
 
         List<Configurator> configurators = new ArrayList<Configurator>(urls.size());
@@ -157,15 +171,15 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
             configurators.add(configuratorFactory.getConfigurator(url));
         }
         Collections.sort(configurators);
-        return configurators;
+        return Optional.of(configurators);
     }
 
-    public static List<Configurator> configToConfiguratiors(String rawConfig, String serviceKey) {
+    public static List<Configurator> configToConfiguratiors(String rawConfig) {
         if (StringUtils.isEmpty(rawConfig)) {
             return new LinkedList<>();
         }
         try {
-            List<URL> urls = ConfigParser.parseConfigurators(rawConfig, serviceKey);
+            List<URL> urls = ConfigParser.parseConfigurators(rawConfig);
             return urls.stream().map(configuratorFactory::getConfigurator).collect(Collectors.toList());
         } catch (Exception e) {
             logger.error("Failed to parse raw dynamic config and it will not take effect, the raw config is: " + rawConfig, e);
@@ -179,7 +193,10 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
         if (StringUtils.isNotEmpty(isDefault)) {
             queryMap.put(Constants.REGISTRY_KEY + "." + Constants.DEFAULT_KEY, isDefault);
         }
-        return url.setPath(url.getServiceInterface()).clearParameters().addParameters(queryMap).removeParameter(Constants.MONITOR_KEY);
+        return url.setPath(url.getServiceInterface())
+                .clearParameters()
+                .addParameters(queryMap)
+                .removeParameter(Constants.MONITOR_KEY);
     }
 
     public void setProtocol(Protocol protocol) {
@@ -194,23 +211,13 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
         setConsumerUrl(url);
         registry.subscribe(url, this);
 
-        synchronized (this) {
-            String key = url.getEncodedServiceKey() + Constants.CONFIGURATORS_SUFFIX;
-            dynamicConfiguration.addListener(key, this);
-            String rawConfig = dynamicConfiguration.getConfig(key);
-            if (rawConfig != null) {
-                this.process(new ConfigChangeEvent(key, rawConfig));
-            }
+        consumerConfigurationListener.overrideUrl();
 
-            String appKey = url.getParameter(Constants.APPLICATION_KEY) + Constants.CONFIGURATORS_SUFFIX;
-            dynamicConfiguration.addListener(appKey, this);
-            String appRawConfig = dynamicConfiguration.getConfig(appKey);
-            if (appRawConfig != null) {
-                this.process(new ConfigChangeEvent(appKey, appRawConfig));
-            }
-        }
+        ServiceConfigurationListener serviceConfigurationListener = new ServiceConfigurationListener(url);
+        serviceConfigurationListener.overrideUrl();
     }
 
+
     @Override
     public void destroy() {
         if (isDestroyed()) {
@@ -221,6 +228,8 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
             if (getConsumerUrl() != null && registry != null && registry.isAvailable()) {
                 registry.unsubscribe(getConsumerUrl(), this);
             }
+            DynamicConfiguration.getDynamicConfiguration()
+                    .removeListener(ApplicationModel.getApplication(), consumerConfigurationListener);
         } catch (Throwable t) {
             logger.warn("unexpected error when unsubscribe service " + serviceKey + "from registry" + registry.getUrl(), t);
         }
@@ -234,75 +243,31 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
 
     @Override
     public synchronized void notify(List<URL> urls) {
-        List<URL> invokerUrls = new ArrayList<>();
-        List<URL> routerUrls = new ArrayList<>();
-        List<URL> configuratorUrls = new ArrayList<>();
-        List<URL> dynamicConfiguratorUrls = new ArrayList<>();
-        List<URL> appDynamicConfiguratorUrls = new ArrayList<>();
-        for (URL url : urls) {
-            String protocol = url.getProtocol();
-            String category = url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY);
-            if (Constants.ROUTERS_CATEGORY.equals(category)
-                    || Constants.ROUTE_PROTOCOL.equals(protocol)) {
-                routerUrls.add(url);
-            } else if (Constants.DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)) {
-                dynamicConfiguratorUrls.add(url);
-            } else if (Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)) {
-                appDynamicConfiguratorUrls.add(url);
-            } else if (Constants.CONFIGURATORS_CATEGORY.equals(category)
-                    || Constants.OVERRIDE_PROTOCOL.equals(protocol)) {
-                configuratorUrls.add(url);
-            } else if (Constants.PROVIDERS_CATEGORY.equals(category)) {
-                invokerUrls.add(url);
-            } else {
-                logger.warn("Unsupported category " + category + " in notified url: " + url + " from registry " + getUrl().getAddress() + " to consumer " + NetUtils.getLocalHost());
-            }
-        }
-        // configurators
-        if (!configuratorUrls.isEmpty()) {
-            this.configurators = toConfigurators(configuratorUrls);
-        }
-        // dynamic configurators
-        if (!dynamicConfiguratorUrls.isEmpty()) {
-            this.dynamicConfigurators = toConfigurators(dynamicConfiguratorUrls);
-        }
-        // dynamic configurators, app scope
-        if (!appDynamicConfiguratorUrls.isEmpty()) {
-            this.appDynamicConfigurators = toConfigurators(appDynamicConfiguratorUrls);
-        }
-        // routers
-        if (!routerUrls.isEmpty()) {
-            List<Router> routers = toRouters(routerUrls);
-            addRouters(routers);
-        }
-
+        List<URL> categoryUrls = urls.stream()
+                .filter(this::isValidCategory)
+                .filter(this::isNotCompatibleFor26x)
+                .collect(Collectors.toList());
+
+        this.configurators = toConfigurators(classifyUrls(categoryUrls, url -> url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY)
+                .equals(CONFIGURATORS_CATEGORY))).orElse(configurators);
+        this.dynamicConfigurators = toConfigurators(classifyUrls(categoryUrls, url -> url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY)
+                .equals(DYNAMIC_CONFIGURATORS_CATEGORY))).orElse(dynamicConfigurators);
+        this.appDynamicConfigurators = toConfigurators(classifyUrls(categoryUrls, url -> url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY)
+                .equals(APP_DYNAMIC_CONFIGURATORS_CATEGORY))).orElse(appDynamicConfigurators);
+
+
+        toRouters(classifyUrls(categoryUrls, url -> {
+            return url.getProtocol()
+                    .equals(ROUTE_PROTOCOL) || url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY)
+                    .equals(ROUTERS_CATEGORY);
+        })).ifPresent(this::addRouters);
+
+        // mock zookeeper://xxx?mock=return null
         overrideDirectoryUrl();
 
         // providers
-        refreshInvoker(invokerUrls);
-    }
-
-    private void overrideDirectoryUrl() {
-        // merge override parameters
-        this.overrideDirectoryUrl = directoryUrl;
-        List<Configurator> localConfigurators = this.configurators; // local reference
-        if (localConfigurators != null && !localConfigurators.isEmpty()) {
-            for (Configurator configurator : localConfigurators) {
-                this.overrideDirectoryUrl = configurator.configure(overrideDirectoryUrl);
-            }
-        }
-        List<Configurator> localAppDynamicConfigurators = this.appDynamicConfigurators; // local reference
-        if (CollectionUtils.isNotEmpty(localAppDynamicConfigurators)) {
-            localAppDynamicConfigurators.forEach(configurator -> {
-                this.overrideDirectoryUrl = configurator.configure(overrideDirectoryUrl);
-            });
-        }
-        List<Configurator> localDynamicConfigurators = this.dynamicConfigurators; // local reference
-        if (CollectionUtils.isNotEmpty(localDynamicConfigurators)) {
-            localDynamicConfigurators.forEach(configurator -> {
-                this.overrideDirectoryUrl = configurator.configure(overrideDirectoryUrl);
-            });
-        }
+        refreshInvoker(classifyUrls(categoryUrls, url -> url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY)
+                .equals(PROVIDERS_CATEGORY)));
     }
 
 /*    private List<URL> compositeDynamicConfiguration(List<URL> urls) {
@@ -319,12 +284,13 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
      */
     // TODO: 2017/8/31 FIXME The thread pool should be used to refresh the address, otherwise the task may be accumulated.
     private void refreshInvoker(List<URL> invokerUrls) {
-        if (invokerUrls != null && invokerUrls.size() == 1 && invokerUrls.get(0) != null
-                && Constants.EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) {
+        if (invokerUrls != null && invokerUrls.size() == 1 && invokerUrls.get(0) != null && Constants.EMPTY_PROTOCOL.equals(invokerUrls
+                .get(0)
+                .getProtocol())) {
             this.forbidden = true; // Forbid to access
-            this.methodInvokerMap = null; // Set the method invoker map to null
+            this.invokers = null;
             destroyAllInvokers(); // Close all invokers
-            routerChain.notifyFullInvokers(this.methodInvokerMap, getConsumerUrl());
+            routerChain.notifyFullInvokers(this.invokers, getConsumerUrl());
         } else {
             this.forbidden = false; // Allow to access
             Map<String, Invoker<T>> oldUrlInvokerMap = this.urlInvokerMap; // local reference
@@ -338,17 +304,22 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
                 return;
             }
             Map<String, Invoker<T>> newUrlInvokerMap = toInvokers(invokerUrls);// Translate url list to Invoker map
-            Map<String, List<Invoker<T>>> newMethodInvokerMap = toMethodInvokers(newUrlInvokerMap); // Change method name to map Invoker Map
+//            Map<String, List<Invoker<T>>> newMethodInvokerMap = toMethodInvokers(newUrlInvokerMap); // Change method name to map Invoker Map
+
             // state change
             // If the calculation is wrong, it is not processed.
             if (newUrlInvokerMap == null || newUrlInvokerMap.size() == 0) {
-                logger.error(new IllegalStateException("urls to invokers error .invokerUrls.size :" + invokerUrls.size() + ", invoker.size :0. urls :" + invokerUrls.toString()));
+                logger.error(new IllegalStateException("urls to invokers error .invokerUrls.size :" + invokerUrls.size() + ", invoker.size :0. urls :" + invokerUrls
+                        .toString()));
                 return;
             }
+
+            List<Invoker<T>> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values()));
             // pre-route and build cache, notice that route cache should build on original Invoker list.
             // toMergeMethodInvokerMap() will wrap some invokers having different groups, those wrapped invokers not should be routed.
-            routerChain.notifyFullInvokers(newMethodInvokerMap, getConsumerUrl());
-            this.methodInvokerMap = multiGroup ? toMergeMethodInvokerMap(newMethodInvokerMap) : newMethodInvokerMap;
+            routerChain.notifyFullInvokers(newInvokers, getConsumerUrl());
+//            this.methodInvokerMap = multiGroup ? toMergeMethodInvokerMap(newMethodInvokerMap) : newMethodInvokerMap;
+            this.invokers = multiGroup ? toMergeInvokerList(newInvokers) : newInvokers;
             this.urlInvokerMap = newUrlInvokerMap;
 
             try {
@@ -359,7 +330,30 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
         }
     }
 
-    private Map<String, List<Invoker<T>>> toMergeMethodInvokerMap(Map<String, List<Invoker<T>>> methodMap) {
+    private List<Invoker<T>> toMergeInvokerList(List<Invoker<T>> invokers) {
+        List<Invoker<T>> mergedInvokers = new ArrayList<>();
+        Map<String, List<Invoker<T>>> groupMap = new HashMap<String, List<Invoker<T>>>();
+        for (Invoker<T> invoker : invokers) {
+            String group = invoker.getUrl().getParameter(Constants.GROUP_KEY, "");
+            groupMap.computeIfAbsent(group, k -> new ArrayList<>());
+            groupMap.get(group).add(invoker);
+        }
+
+        if (groupMap.size() == 1) {
+            mergedInvokers.addAll(groupMap.values().iterator().next());
+        } else if (groupMap.size() > 1) {
+            for (List<Invoker<T>> groupList : groupMap.values()) {
+                StaticDirectory<T> staticDirectory = new StaticDirectory<>(groupList);
+                staticDirectory.buildRouterChain(invokers);
+                mergedInvokers.add(cluster.join(staticDirectory));
+            }
+        } else {
+            mergedInvokers = invokers;
+        }
+        return mergedInvokers;
+    }
+
+    /*private Map<String, List<Invoker<T>>> toMergeMethodInvokerMap(Map<String, List<Invoker<T>>> methodMap) {
         Map<String, List<Invoker<T>>> result = new HashMap<String, List<Invoker<T>>>();
         for (Map.Entry<String, List<Invoker<T>>> entry : methodMap.entrySet()) {
             String method = entry.getKey();
@@ -392,38 +386,38 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
         }
         return result;
     }
+*/
 
     /**
      * @param urls
      * @return null : no routers ,do nothing
      * else :routers list
      */
-    private List<Router> toRouters(List<URL> urls) {
-        List<Router> routers = new ArrayList<Router>();
+    private Optional<List<Router>> toRouters(List<URL> urls) {
         if (urls == null || urls.isEmpty()) {
-            return routers;
+            return Optional.empty();
         }
-        if (urls != null && !urls.isEmpty()) {
-            for (URL url : urls) {
-                if (Constants.EMPTY_PROTOCOL.equals(url.getProtocol())) {
-                    continue;
-                }
-                String routerType = url.getParameter(Constants.ROUTER_KEY);
-                if (routerType != null && routerType.length() > 0) {
-                    url = url.setProtocol(routerType);
-                }
-                try {
-                    Router router = routerFactory.getRouter(url);
-                    router.setRouterChain(routerChain);
+
+        List<Router> routers = new ArrayList<Router>();
+        for (URL url : urls) {
+            if (Constants.EMPTY_PROTOCOL.equals(url.getProtocol())) {
+                continue;
+            }
+            String routerType = url.getParameter(Constants.ROUTER_KEY);
+            if (routerType != null && routerType.length() > 0) {
+                url = url.setProtocol(routerType);
+            }
+            try {
+                Router router = routerFactory.getRouter(url);
+                router.addRouterChain(routerChain);
 //                    routerChain.addRouter(router);
-                    if (!routers.contains(router))
-                        routers.add(router);
-                } catch (Throwable t) {
-                    logger.error("convert router url to router error, url: " + url, t);
-                }
+                if (!routers.contains(router)) routers.add(router);
+            } catch (Throwable t) {
+                logger.error("convert router url to router error, url: " + url, t);
             }
         }
-        return routers;
+
+        return Optional.of(routers);
     }
 
     /**
@@ -458,8 +452,10 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
                 continue;
             }
             if (!ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(providerUrl.getProtocol())) {
-                logger.error(new IllegalStateException("Unsupported protocol " + providerUrl.getProtocol() + " in notified url: " + providerUrl + " from registry " + getUrl().getAddress() + " to consumer " + NetUtils.getLocalHost()
-                        + ", supported protocol: " + ExtensionLoader.getExtensionLoader(Protocol.class).getSupportedExtensions()));
+                logger.error(new IllegalStateException("Unsupported protocol " + providerUrl.getProtocol() + " in notified url: " + providerUrl + " from registry " + getUrl()
+                        .getAddress() + " to consumer " + NetUtils.getLocalHost() + ", supported protocol: " + ExtensionLoader
+                        .getExtensionLoader(Protocol.class)
+                        .getSupportedExtensions()));
                 continue;
             }
             URL url = mergeUrl(providerUrl);
@@ -513,8 +509,8 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
         // The combination of directoryUrl and override is at the end of notify, which can't be handled here
         this.overrideDirectoryUrl = this.overrideDirectoryUrl.addParametersIfAbsent(providerUrl.getParameters()); // Merge the provider side parameters
 
-        if ((providerUrl.getPath() == null || providerUrl.getPath().length() == 0)
-                && "dubbo".equals(providerUrl.getProtocol())) { // Compatible version 1.0
+        if ((providerUrl.getPath() == null || providerUrl.getPath()
+                .length() == 0) && "dubbo".equals(providerUrl.getProtocol())) { // Compatible version 1.0
             //fix by tony.chenl DUBBO-44
             String path = directoryUrl.getParameter(Constants.INTERFACE_KEY);
             if (path != null) {
@@ -574,8 +570,7 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
                     String[] methods = Constants.COMMA_SPLIT_PATTERN.split(parameter);
                     if (methods != null && methods.length > 0) {
                         for (String method : methods) {
-                            if (method != null && method.length() > 0
-                                    && !Constants.ANY_VALUE.equals(method)) {
+                            if (method != null && method.length() > 0 && !Constants.ANY_VALUE.equals(method)) {
                                 List<Invoker<T>> methodInvokers = newMethodInvokerMap.get(method);
                                 if (methodInvokers == null) {
                                     methodInvokers = new ArrayList<Invoker<T>>();
@@ -614,7 +609,7 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
             }
             localUrlInvokerMap.clear();
         }
-        methodInvokerMap = null;
+        invokers = null;
     }
 
     /**
@@ -666,15 +661,12 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
     public List<Invoker<T>> doList(Invocation invocation) {
         if (forbidden) {
             // 1. No service provider 2. Service providers are disabled
-            throw new RpcException(RpcException.FORBIDDEN_EXCEPTION,
-                    "No provider available from registry " + getUrl().getAddress() + " for service " + getConsumerUrl().getServiceKey() + " on consumer " + NetUtils.getLocalHost()
-                            + " use dubbo version " + Version.getVersion() + ", please check status of providers(disabled, not registered or in blacklist).");
+            throw new RpcException(RpcException.FORBIDDEN_EXCEPTION, "No provider available from registry " + getUrl().getAddress() + " for service " + getConsumerUrl()
+                    .getServiceKey() + " on consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", please check status of providers(disabled, not registered or in blacklist).");
         }
 
         if (multiGroup) {
-            Map<String, List<Invoker<T>>> localMethodInvokerMap = this.methodInvokerMap; // local reference
-            String methodName = RpcUtils.getMethodName(invocation);
-            return localMethodInvokerMap.get(methodName);
+            return this.invokers;
         }
 
         List<Invoker<T>> invokers = null;
@@ -710,36 +702,6 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
     }
 
     @Override
-    public synchronized void process(ConfigChangeEvent event) {
-        if (logger.isInfoEnabled()) {
-            logger.info("Notification of overriding rule, change type is: " + event.getChangeType() + ", raw config content is:\n " + event.getNewValue());
-        }
-
-        List<URL> urls = new ArrayList<>();
-        if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
-            URL url = getConsumerUrl().clearParameters().setProtocol(Constants.EMPTY_PROTOCOL);
-            if (event.getKey().endsWith(this.queryMap.get(APPLICATION_KEY) + CONFIGURATORS_SUFFIX)) {
-                url = url.addParameter(Constants.CATEGORY_KEY, Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY);
-            } else {
-                url = url.addParameter(Constants.CATEGORY_KEY, Constants.DYNAMIC_CONFIGURATORS_CATEGORY);
-            }
-            urls.add(url);
-        } else {
-            try {
-                urls = ConfigParser.parseConfigurators(event.getNewValue(), overrideDirectoryUrl.getServiceKey());
-            } catch (Exception e) {
-                logger.error("Failed to parse raw dynamic config and it will not take effect, the raw config is: " + event.getNewValue(), e);
-            }
-        }
-
-        if (logger.isDebugEnabled()) {
-            logger.debug("Successfully transformed override rule to urls, will do override now, the urls are: " + urls);
-        }
-
-        notify(urls);
-    }
-
-    @Override
     public URL getUrl() {
         return this.overrideDirectoryUrl;
     }
@@ -760,12 +722,8 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
         return false;
     }
 
-    public void setDynamicConfiguration(DynamicConfiguration dynamicConfiguration) {
-        this.dynamicConfiguration = dynamicConfiguration;
-    }
-
-    public void buildRouterChain(DynamicConfiguration dynamicConfiguration) {
-        this.setRouterChain(RouterChain.buildChain(dynamicConfiguration, overrideDirectoryUrl));
+    public void buildRouterChain(URL url) {
+        this.setRouterChain(RouterChain.buildChain(url));
     }
 
     /**
@@ -775,11 +733,8 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
         return urlInvokerMap;
     }
 
-    /**
-     * Haomin: added for test purpose
-     */
-    public Map<String, List<Invoker<T>>> getMethodInvokerMap() {
-        return methodInvokerMap;
+    public List<Invoker<T>> getInvokers() {
+        return invokers;
     }
 
     private static class InvokerComparator implements Comparator<Invoker<?>> {
@@ -800,6 +755,41 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
 
     }
 
+    private boolean isValidCategory(URL url) {
+        String category = url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY);
+        if ((ROUTERS_CATEGORY.equals(category) || ROUTE_PROTOCOL.equals(url.getProtocol())) || PROVIDERS_CATEGORY.equals(category) || CONFIGURATORS_CATEGORY
+                .equals(category) || DYNAMIC_CONFIGURATORS_CATEGORY.equals(category) || APP_DYNAMIC_CONFIGURATORS_CATEGORY
+                .equals(category)) {
+            return true;
+        }
+        logger.warn("Unsupported category " + category + " in notified url: " + url + " from registry " + getUrl().getAddress() + " to consumer " + NetUtils
+                .getLocalHost());
+        return false;
+    }
+
+    private boolean isNotCompatibleFor26x(URL url) {
+        return StringUtils.isEmpty(url.getParameter(Constants.COMPATIBLE_CONFIG_KEY));
+    }
+
+    private void overrideDirectoryUrl() {
+        // merge override parameters
+        this.overrideDirectoryUrl = directoryUrl;
+        List<Configurator> localConfigurators = this.configurators; // local reference
+        doOverrideUrl(localConfigurators);
+        List<Configurator> localAppDynamicConfigurators = this.appDynamicConfigurators; // local reference
+        doOverrideUrl(localAppDynamicConfigurators);
+        List<Configurator> localDynamicConfigurators = this.dynamicConfigurators; // local reference
+        doOverrideUrl(localDynamicConfigurators);
+    }
+
+    private void doOverrideUrl(List<Configurator> configurators) {
+        if (configurators != null && !configurators.isEmpty()) {
+            for (Configurator configurator : configurators) {
+                this.overrideDirectoryUrl = configurator.configure(overrideDirectoryUrl);
+            }
+        }
+    }
+
     /**
      * The delegate class, which is mainly used to store the URL address sent by the registry,and can be reassembled on the basis of providerURL queryMap overrideMap for re-refer.
      *
@@ -817,4 +807,65 @@ public class RegistryDirectory<T> extends AbstractDirectory<T> implements Notify
             return providerUrl;
         }
     }
+
+    private class ServiceConfigurationListener extends AbstractConfiguratorListener {
+        private URL url;
+
+        ServiceConfigurationListener(URL url) {
+            this.url = url;
+        }
+
+        synchronized void overrideUrl() {
+            DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration();
+            String key = url.getEncodedServiceKey() + Constants.CONFIGURATORS_SUFFIX;
+            String rawConfig = dynamicConfiguration.getConfig(key);
+            if (rawConfig != null) {
+                this.process(new ConfigChangeEvent(key, rawConfig));
+            }
+
+            dynamicConfiguration.addListener(key, this);
+        }
+
+        @Override
+        protected void notifyOverrides(List<URL> urls) {
+            urls.forEach(u -> u.addParameter(CATEGORY_KEY, DYNAMIC_CONFIGURATORS_CATEGORY));
+            RegistryDirectory.this.notify(urls);
+        }
+    }
+
+    private static class ConsumerConfigurationListener extends AbstractConfiguratorListener {
+        List<NotifyListener> listeners = new ArrayList<>();
+        ConfigChangeEvent initRule;
+
+        void addNotifyListener(NotifyListener listener) {
+            this.listeners.add(listener);
+        }
+
+        ConsumerConfigurationListener() {
+            this.init();
+        }
+
+        private synchronized void init() {
+            String appKey = ApplicationModel.getApplication() + Constants.CONFIGURATORS_SUFFIX;
+            String appRawConfig = DynamicConfiguration.getDynamicConfiguration().getConfig(appKey);
+            if (appRawConfig != null) {
+                initRule = new ConfigChangeEvent(appKey, appRawConfig);
+            }
+
+            DynamicConfiguration.getDynamicConfiguration().addListener(appKey, this);
+        }
+
+        synchronized void overrideUrl() {
+            if (initRule != null) {
+                process(initRule);
+            }
+        }
+
+        @Override
+        protected void notifyOverrides(List<URL> urls) {
+            urls.forEach(u -> u.addParameter(CATEGORY_KEY, APP_DYNAMIC_CONFIGURATORS_CATEGORY));
+            listeners.forEach(listener -> listener.notify(urls));
+        }
+    }
+
 }
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java
index 5fe151e..f401eb9 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java
@@ -19,16 +19,12 @@ package org.apache.dubbo.registry.integration;
 import org.apache.dubbo.common.Constants;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.config.ConfigurationUtils;
-import org.apache.dubbo.common.config.Environment;
 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.common.utils.NamedThreadFactory;
 import org.apache.dubbo.common.utils.StringUtils;
 import org.apache.dubbo.common.utils.UrlUtils;
-import org.apache.dubbo.configcenter.ConfigChangeEvent;
-import org.apache.dubbo.configcenter.ConfigChangeType;
 import org.apache.dubbo.configcenter.ConfigurationListener;
 import org.apache.dubbo.configcenter.DynamicConfiguration;
 import org.apache.dubbo.registry.NotifyListener;
@@ -44,7 +40,7 @@ import org.apache.dubbo.rpc.ProxyFactory;
 import org.apache.dubbo.rpc.RpcException;
 import org.apache.dubbo.rpc.cluster.Cluster;
 import org.apache.dubbo.rpc.cluster.Configurator;
-import org.apache.dubbo.rpc.cluster.configurator.parser.ConfigParser;
+import org.apache.dubbo.rpc.model.ApplicationModel;
 import org.apache.dubbo.rpc.protocol.InvokerWrapper;
 
 import java.util.ArrayList;
@@ -55,11 +51,13 @@ import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
-import java.util.stream.Collectors;
 
 import static org.apache.dubbo.common.Constants.ACCEPT_FOREIGN_IP;
-import static org.apache.dubbo.common.Constants.APPLICATION_KEY;
+import static org.apache.dubbo.common.Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY;
+import static org.apache.dubbo.common.Constants.CATEGORY_KEY;
+import static org.apache.dubbo.common.Constants.CONFIGURATORS_CATEGORY;
 import static org.apache.dubbo.common.Constants.CONFIGURATORS_SUFFIX;
+import static org.apache.dubbo.common.Constants.DYNAMIC_CONFIGURATORS_CATEGORY;
 import static org.apache.dubbo.common.Constants.EXPORT_KEY;
 import static org.apache.dubbo.common.Constants.INTERFACES;
 import static org.apache.dubbo.common.Constants.METHODS_KEY;
@@ -67,6 +65,7 @@ import static org.apache.dubbo.common.Constants.QOS_ENABLE;
 import static org.apache.dubbo.common.Constants.QOS_PORT;
 import static org.apache.dubbo.common.Constants.REFER_KEY;
 import static org.apache.dubbo.common.Constants.VALIDATION_KEY;
+import static org.apache.dubbo.common.utils.UrlUtils.classifyUrls;
 
 /**
  * RegistryProtocol
@@ -75,7 +74,9 @@ public class RegistryProtocol implements Protocol {
 
     private final static Logger logger = LoggerFactory.getLogger(RegistryProtocol.class);
     private static RegistryProtocol INSTANCE;
-    private final Map<URL, NotifyListener> overrideListeners = new ConcurrentHashMap<URL, NotifyListener>();
+    private final Map<URL, NotifyListener> overrideListeners = new ConcurrentHashMap<>();
+    private final Map<String, ConfigurationListener> serviceConfigurationListeners = new ConcurrentHashMap<>();
+    private final ProviderConfigurationListener providerConfigurationListener = new ProviderConfigurationListener();
     //To solve the problem of RMI repeated exposure port conflicts, the services that have been exposed are no longer exposed.
     //providerurl <--> exporter
     private final Map<String, ExporterChangeableWrapper<?>> bounds = new ConcurrentHashMap<String, ExporterChangeableWrapper<?>>();
@@ -83,11 +84,9 @@ public class RegistryProtocol implements Protocol {
     private Protocol protocol;
     private RegistryFactory registryFactory;
     private ProxyFactory proxyFactory;
-    private DynamicConfiguration dynamicConfiguration;
 
     public RegistryProtocol() {
         INSTANCE = this;
-        dynamicConfiguration = (DynamicConfiguration) Environment.getInstance().getDynamicConfiguration();
     }
 
     public static RegistryProtocol getRegistryProtocol() {
@@ -160,62 +159,35 @@ public class RegistryProtocol implements Protocol {
         final OverrideListener overrideSubscribeListener = new OverrideListener(overrideSubscribeUrl, originInvoker);
         overrideListeners.put(overrideSubscribeUrl, overrideSubscribeListener);
 
-        /**
-         * synchronized is used to make sure override notifications come after export and register finished.
-         * we will eagerly call dynamicConfiguration.getConfig() to let existing overrides take effect before export or register.
-         */
-        synchronized (overrideSubscribeListener) {
-            providerUrl = overrideUrlWithConfig(providerUrl, overrideSubscribeListener);
-            //export invoker
-            final ExporterChangeableWrapper<T> exporter = doLocalExport(originInvoker, providerUrl);
-
-            // url to registry
-            final Registry registry = getRegistry(originInvoker);
-            final URL registeredProviderUrl = getRegistedProviderUrl(providerUrl, registryUrl);
-            ProviderConsumerRegTable.registerProvider(originInvoker, registryUrl, registeredProviderUrl);
-            //to judge if we need to delay publish
-            boolean register = registeredProviderUrl.getParameter("register", true);
-            if (register) {
-                register(registryUrl, registeredProviderUrl);
-                ProviderConsumerRegTable.getProviderWrapper(originInvoker).setReg(true);
-            }
+        providerUrl = overrideUrlWithConfig(providerUrl, overrideSubscribeListener);
+        //export invoker
+        final ExporterChangeableWrapper<T> exporter = doLocalExport(originInvoker, providerUrl);
 
-            // Deprecated! Subscribe to override rules in 2.6.x or before.
-            registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener);
-
-            exporter.setRegisterUrl(registeredProviderUrl);
-            exporter.setSubscribeUrl(overrideSubscribeUrl);
-            //Ensure that a new exporter instance is returned every time export
-            return new DestroyableExporter<>(exporter);
+        // url to registry
+        final Registry registry = getRegistry(originInvoker);
+        final URL registeredProviderUrl = getRegistedProviderUrl(providerUrl, registryUrl);
+        ProviderConsumerRegTable.registerProvider(originInvoker, registryUrl, registeredProviderUrl);
+        //to judge if we need to delay publish
+        boolean register = registeredProviderUrl.getParameter("register", true);
+        if (register) {
+            register(registryUrl, registeredProviderUrl);
+            ProviderConsumerRegTable.getProviderWrapper(registeredProviderUrl, originInvoker).setReg(true);
         }
-    }
 
-    /**
-     * Get existing configuration rule and override provider url before exporting.
-     *
-     * @param providerUrl
-     * @param <T>
-     * @return
-     */
-    private <T> URL overrideUrlWithConfig(URL providerUrl, OverrideListener listener) {
-        List<Configurator> configurators = new LinkedList<>();
-        String appKey = providerUrl.getParameter(Constants.APPLICATION_KEY) + Constants.CONFIGURATORS_SUFFIX;
-        dynamicConfiguration.addListener(appKey, listener);
-        String appRawConfig = dynamicConfiguration.getConfig(appKey);
-        if (!StringUtils.isEmpty(appRawConfig)) {
-            List<Configurator> appDynamicConfigurators = RegistryDirectory.configToConfiguratiors(appRawConfig, providerUrl.getServiceKey());
-            configurators.addAll(appDynamicConfigurators);
-        }
+        // Deprecated! Subscribe to override rules in 2.6.x or before.
+        registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener);
 
-        String serviceKey = providerUrl.getEncodedServiceKey() + Constants.CONFIGURATORS_SUFFIX;
-        dynamicConfiguration.addListener(serviceKey, listener);
-        String rawConfig = dynamicConfiguration.getConfig(serviceKey);
-        if (!StringUtils.isEmpty(rawConfig)) {
-            List<Configurator> dynamicConfigurators = RegistryDirectory.configToConfiguratiors(rawConfig, providerUrl.getServiceKey());
-            configurators.addAll(dynamicConfigurators);
-        }
-        providerUrl = getConfigedInvokerUrl(configurators, providerUrl);
-        return providerUrl;
+        exporter.setRegisterUrl(registeredProviderUrl);
+        exporter.setSubscribeUrl(overrideSubscribeUrl);
+        //Ensure that a new exporter instance is returned every time export
+        return new DestroyableExporter<>(exporter);
+    }
+
+    private URL overrideUrlWithConfig(URL providerUrl, NotifyListener listener) {
+        providerUrl = providerConfigurationListener.overrideUrl(providerUrl);
+        ServiceConfigurationListener serviceConfigurationListener = new ServiceConfigurationListener(providerUrl, listener);
+        serviceConfigurationListeners.put(providerUrl.getServiceKey(), serviceConfigurationListener);
+        return serviceConfigurationListener.overrideUrl(providerUrl);
     }
 
     @SuppressWarnings("unchecked")
@@ -244,7 +216,7 @@ public class RegistryProtocol implements Protocol {
         final URL registeredProviderUrl = getRegistedProviderUrl(newInvokerUrl, registryUrl);
 
         //decide if we need to re-publish
-        ProviderInvokerWrapper<T> providerInvokerWrapper = ProviderConsumerRegTable.getProviderWrapper(originInvoker);
+        ProviderInvokerWrapper<T> providerInvokerWrapper = ProviderConsumerRegTable.getProviderWrapper(registeredProviderUrl, originInvoker);
         ProviderConsumerRegTable.registerProvider(originInvoker, registryUrl, registeredProviderUrl);
         /**
          * Only if the new url going to Registry is different with the previous one should we do unregister and register.
@@ -376,8 +348,6 @@ public class RegistryProtocol implements Protocol {
         RegistryDirectory<T> directory = new RegistryDirectory<T>(type, url);
         directory.setRegistry(registry);
         directory.setProtocol(protocol);
-        directory.setDynamicConfiguration(dynamicConfiguration);
-        directory.buildRouterChain(dynamicConfiguration);
         // all attributes of REFER_KEY
         Map<String, String> parameters = new HashMap<String, String>(directory.getUrl().getParameters());
         URL subscribeUrl = new URL(Constants.CONSUMER_PROTOCOL, parameters.remove(Constants.REGISTER_IP_KEY), 0, type.getName(), parameters);
@@ -385,6 +355,7 @@ public class RegistryProtocol implements Protocol {
                 && url.getParameter(Constants.REGISTER_KEY, true)) {
             registry.register(getRegistedConsumerUrl(subscribeUrl, url));
         }
+        directory.buildRouterChain(subscribeUrl);
         directory.subscribe(subscribeUrl.addParameter(Constants.CATEGORY_KEY,
                 Constants.PROVIDERS_CATEGORY
                         + "," + Constants.CONFIGURATORS_CATEGORY
@@ -421,6 +392,9 @@ public class RegistryProtocol implements Protocol {
             exporter.unexport();
         }
         bounds.clear();
+
+        DynamicConfiguration.getDynamicConfiguration()
+                .removeListener(ApplicationModel.getApplication() + CONFIGURATORS_SUFFIX, providerConfigurationListener);
     }
 
     //Merge the urls of configurators
@@ -479,10 +453,11 @@ public class RegistryProtocol implements Protocol {
      * 2.No need to re-register to the registry after notify
      * 3.The invoker passed by the export method , would better to be the invoker of exporter
      */
-    private class OverrideListener implements NotifyListener, ConfigurationListener {
+    private class OverrideListener implements NotifyListener {
 
         private final URL subscribeUrl;
         private final Invoker originInvoker;
+
         private List<Configurator> configurators;
         private List<Configurator> dynamicConfigurators;
         private List<Configurator> appDynamicConfigurators;
@@ -494,32 +469,25 @@ public class RegistryProtocol implements Protocol {
 
         /**
          * @param urls The list of registered information , is always not empty, The meaning is the same as the return value of {@link org.apache.dubbo.registry.RegistryService#lookup(URL)}.
+         *             configurators
          */
         @Override
         public synchronized void notify(List<URL> urls) {
             logger.debug("original override urls: " + urls);
-            List<URL> matchedUrls = getMatchedUrls(urls, subscribeUrl.addParameter(Constants.CATEGORY_KEY,
-                    Constants.CONFIGURATORS_CATEGORY
-                            + "," + Constants.DYNAMIC_CONFIGURATORS_CATEGORY
-                            + "," + Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY));
+            List<URL> matchedUrls = getMatchedUrls(urls, subscribeUrl.addParameter(Constants.CATEGORY_KEY, Constants.CONFIGURATORS_CATEGORY + "," + Constants.DYNAMIC_CONFIGURATORS_CATEGORY + "," + Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY));
             logger.debug("subscribe url: " + subscribeUrl + ", override urls: " + matchedUrls);
             // No matching results
             if (matchedUrls.isEmpty()) {
                 return;
             }
-            List<URL> configuratorUrls = matchedUrls.stream().filter(u -> u.getParameter(Constants.CATEGORY_KEY).equals(Constants.CONFIGURATORS_CATEGORY)).collect(Collectors.toList());
-            List<URL> dynamicConfiguratorUrls = matchedUrls.stream().filter(u -> u.getParameter(Constants.CATEGORY_KEY).equals(Constants.DYNAMIC_CONFIGURATORS_CATEGORY)).collect(Collectors.toList());
-            List<URL> appDynamicConfiguratorUrls = matchedUrls.stream().filter(u -> u.getParameter(Constants.CATEGORY_KEY).equals(Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY)).collect(Collectors.toList());
 
-            if (CollectionUtils.isNotEmpty(configuratorUrls)) {
-                configurators = RegistryDirectory.toConfigurators(configuratorUrls);
-            }
-            if (CollectionUtils.isNotEmpty(dynamicConfiguratorUrls)) {
-                dynamicConfigurators = RegistryDirectory.toConfigurators(dynamicConfiguratorUrls);
-            }
-            if (CollectionUtils.isNotEmpty(appDynamicConfiguratorUrls)) {
-                appDynamicConfigurators = RegistryDirectory.toConfigurators(appDynamicConfiguratorUrls);
-            }
+            // configurators dynamic-configurators, app-dynamic-configurators
+            this.configurators = RegistryDirectory.toConfigurators(classifyUrls(matchedUrls, u -> u.getParameter(CATEGORY_KEY)
+                    .equals(CONFIGURATORS_CATEGORY))).orElse(configurators);
+            this.dynamicConfigurators = RegistryDirectory.toConfigurators(classifyUrls(matchedUrls, u -> u.getParameter(CATEGORY_KEY)
+                    .equals(DYNAMIC_CONFIGURATORS_CATEGORY))).orElse(dynamicConfigurators);
+            this.appDynamicConfigurators = RegistryDirectory.toConfigurators(classifyUrls(matchedUrls, u -> u.getParameter(CATEGORY_KEY)
+                    .equals(APP_DYNAMIC_CONFIGURATORS_CATEGORY))).orElse(appDynamicConfigurators);
 
             final Invoker<?> invoker;
             if (originInvoker instanceof InvokerDelegete) {
@@ -552,8 +520,7 @@ public class RegistryProtocol implements Protocol {
             for (URL url : configuratorUrls) {
                 URL overrideUrl = url;
                 // Compatible with the old version
-                if (url.getParameter(Constants.CATEGORY_KEY) == null
-                        && Constants.OVERRIDE_PROTOCOL.equals(url.getProtocol())) {
+                if (url.getParameter(Constants.CATEGORY_KEY) == null && Constants.OVERRIDE_PROTOCOL.equals(url.getProtocol())) {
                     overrideUrl = url.addParameter(Constants.CATEGORY_KEY, Constants.CONFIGURATORS_CATEGORY);
                 }
 
@@ -564,41 +531,77 @@ public class RegistryProtocol implements Protocol {
             }
             return result;
         }
+    }
+
+    private class ServiceConfigurationListener extends AbstractConfiguratorListener {
+        private URL providerUrl;
+        private NotifyListener notifyListener;
+        private List<Configurator> configurators = new LinkedList<>();
+
+        public ServiceConfigurationListener(URL providerUrl, NotifyListener notifyListener) {
+            this.providerUrl = providerUrl;
+            this.notifyListener = notifyListener;
+            this.init();
+        }
 
-        @Override
-        public synchronized void process(ConfigChangeEvent event) {
-            if (logger.isInfoEnabled()) {
-                logger.info("Notification of overriding rule, change type is: " + event.getChangeType() + ", raw config content is:\n " + event.getNewValue());
+        private synchronized void init() {
+            DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration();
+            String key = providerUrl.getEncodedServiceKey() + Constants.CONFIGURATORS_SUFFIX;
+            String rawConfig = dynamicConfiguration.getConfig(key);
+            if (!StringUtils.isEmpty(rawConfig)) {
+                List<Configurator> appDynamicConfigurators = RegistryDirectory.configToConfiguratiors(rawConfig);
+                configurators.addAll(appDynamicConfigurators);
             }
 
-            List<URL> urls;
-            if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
-                URL originUrl = RegistryProtocol.this.getProviderUrl(originInvoker);
-                originUrl = originUrl.clearParameters().setProtocol(Constants.EMPTY_PROTOCOL);
-                // determine it's a app level or service level change.
-                if (event.getKey().endsWith(originUrl.getParameter(APPLICATION_KEY) + CONFIGURATORS_SUFFIX)) {
-                    originUrl = originUrl.addParameter(Constants.CATEGORY_KEY, Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY);
-                } else {
-                    originUrl = originUrl.addParameter(Constants.CATEGORY_KEY, Constants.DYNAMIC_CONFIGURATORS_CATEGORY);
-                }
-                urls = new ArrayList<>();
-                urls.add(originUrl);
-            } else {
-                try {
-                    // parseConfigurators will recognize app/service config automatically.
-                    urls = ConfigParser.parseConfigurators(event.getNewValue(), subscribeUrl.getServiceKey());
-                } catch (Exception e) {
-                    logger.error("Failed to parse raw dynamic config and it will not take effect, the raw config is: " + event.getNewValue(), e);
-                    return;
-                }
-            }
+            dynamicConfiguration.addListener(key, this);
+        }
 
-            logger.debug("Successfully transformed override rule to urls, will do override now, the urls are: " + urls);
+        private <T> URL overrideUrl(URL providerUrl) {
+            return RegistryProtocol.this.getConfigedInvokerUrl(configurators, providerUrl);
+        }
 
-            notify(urls);
+        @Override
+        protected void notifyOverrides(List<URL> urls) {
+            urls.forEach(u -> u.addParameter(CATEGORY_KEY, DYNAMIC_CONFIGURATORS_CATEGORY));
+            notifyListener.notify(urls);
         }
     }
 
+    private class ProviderConfigurationListener extends AbstractConfiguratorListener {
+        private final List<Configurator> configurators = new LinkedList<>();
+
+        public ProviderConfigurationListener() {
+            this.init();
+        }
+
+        private synchronized void init() {
+            DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration();
+            String appKey = ApplicationModel.getApplication() + Constants.CONFIGURATORS_SUFFIX;
+            dynamicConfiguration.addListener(appKey, this);
+            String appRawConfig = dynamicConfiguration.getConfig(appKey);
+            if (!StringUtils.isEmpty(appRawConfig)) {
+                List<Configurator> appDynamicConfigurators = RegistryDirectory.configToConfiguratiors(appRawConfig);
+                configurators.addAll(appDynamicConfigurators);
+            }
+        }
+
+        /**
+         * Get existing configuration rule and override provider url before exporting.
+         *
+         * @param providerUrl
+         * @param <T>
+         * @return
+         */
+        private <T> URL overrideUrl(URL providerUrl) {
+            return RegistryProtocol.this.getConfigedInvokerUrl(configurators, providerUrl);
+        }
+
+        @Override
+        protected void notifyOverrides(List<URL> urls) {
+            urls.forEach(u -> u.addParameter(CATEGORY_KEY, APP_DYNAMIC_CONFIGURATORS_CATEGORY));
+            overrideListeners.values().forEach(listener -> listener.notify(urls));
+        }
+    }
     /**
      * exporter proxy, establish the corresponding relationship between the returned exporter and the exporter exported by the protocol, and can modify the relationship at the time of override.
      *
@@ -645,6 +648,9 @@ public class RegistryProtocol implements Protocol {
             try {
                 NotifyListener listener = RegistryProtocol.INSTANCE.overrideListeners.remove(subscribeUrl);
                 registry.unsubscribe(subscribeUrl, listener);
+                DynamicConfiguration.getDynamicConfiguration()
+                        .removeListener(subscribeUrl.getServiceKey() + CONFIGURATORS_SUFFIX, serviceConfigurationListeners
+                                .get(subscribeUrl.getServiceKey()));
             } catch (Throwable t) {
                 logger.warn(t.getMessage(), t);
             }
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ProviderConsumerRegTable.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ProviderConsumerRegTable.java
index 9bf1e3f..0870abe 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ProviderConsumerRegTable.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ProviderConsumerRegTable.java
@@ -16,7 +16,6 @@
  */
 package org.apache.dubbo.registry.support;
 
-import org.apache.dubbo.common.Constants;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.utils.ConcurrentHashSet;
 import org.apache.dubbo.registry.integration.RegistryDirectory;
@@ -52,7 +51,7 @@ public class ProviderConsumerRegTable {
         if (invokers == null) {
             return null;
         }
-        return invokers.remove(new ProviderInvokerWrapper(invoker, null, null));
+        return invokers.remove(new ProviderIndvokerWrapper(invoker, null, null));
     }*/
 
     public static Set<ProviderInvokerWrapper> getProviderInvoker(String serviceUniqueName) {
@@ -63,12 +62,8 @@ public class ProviderConsumerRegTable {
         return new HashSet<>(invokers.values());
     }
 
-    public static ProviderInvokerWrapper getProviderWrapper(Invoker invoker) {
-        URL providerUrl = invoker.getUrl();
-        if (Constants.REGISTRY_PROTOCOL.equals(providerUrl.getProtocol())) {
-            providerUrl = URL.valueOf(providerUrl.getParameterAndDecoded(Constants.EXPORT_KEY));
-        }
-        String serviceUniqueName = providerUrl.getServiceKey();
+    public static ProviderInvokerWrapper getProviderWrapper(URL registeredProviderUrl, Invoker invoker) {
+        String serviceUniqueName = registeredProviderUrl.getServiceKey();
         ConcurrentMap<Invoker, ProviderInvokerWrapper> invokers = providerInvokers.get(serviceUniqueName);
         if (invokers == null) {
             return null;
diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ZKTools.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ZKTools.java
index 15c002e..e3dfe64 100644
--- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ZKTools.java
+++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ZKTools.java
@@ -16,20 +16,25 @@
  */
 package org.apache.dubbo.registry;
 
+import org.apache.dubbo.common.utils.NamedThreadFactory;
+import org.apache.dubbo.common.utils.StringUtils;
+
 import org.apache.curator.framework.CuratorFramework;
 import org.apache.curator.framework.CuratorFrameworkFactory;
+import org.apache.curator.framework.api.CuratorEvent;
+import org.apache.curator.framework.api.CuratorListener;
 import org.apache.curator.framework.recipes.cache.ChildData;
 import org.apache.curator.framework.recipes.cache.PathChildrenCache;
 import org.apache.curator.framework.recipes.cache.TreeCache;
 import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
 import org.apache.curator.framework.recipes.cache.TreeCacheListener;
 import org.apache.curator.retry.ExponentialBackoffRetry;
-import org.apache.dubbo.common.utils.StringUtils;
 
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 
 /**
@@ -37,18 +42,29 @@ import java.util.concurrent.Executors;
  */
 public class ZKTools {
     private static CuratorFramework client;
+    private static ExecutorService executor = Executors.newFixedThreadPool(1, new NamedThreadFactory("ZKTools-test", true));
 
     public static void main(String[] args) throws Exception {
         client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 60 * 1000, 60 * 1000,
                 new ExponentialBackoffRetry(1000, 3));
         client.start();
 
+        client.getCuratorListenable().addListener(new CuratorListener() {
+            @Override
+            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
+                System.out.println("event notification: " + event.getPath());
+                System.out.println(event);
+            }
+        }, executor);
+
+        tesConditionRule();
+
 //        testStartupConfig();
-        testProviderConfig();
+//        testProviderConfig();
 //        testPathCache();
 //        testTreeCache();
 //        testCuratorListener();
-        System.in.read();
+//       Thread.sleep(100000);
     }
 
     public static void testStartupConfig() {
@@ -58,7 +74,7 @@ public class ZKTools {
                 "dubbo.protocol.port=20990\n" +
                 "dubbo.service.org.apache.dubbo.demo.DemoService.timeout=9999\n";
 
-        System.out.println(str);
+//        System.out.println(str);
 
         try {
             String path = "/dubboregistrygroup1/config/dubbo/dubbo.properties";
@@ -84,14 +100,26 @@ public class ZKTools {
                 "    timeout: 6000\n" +
                 "...";
 
-        System.out.println(str);
+//        System.out.println(str);
 
         try {
             String path = "/dubbo/config/dd-test*org.apache.dubbo.demo.DemoService:1.0.4/configurators";
             if (client.checkExists().forPath(path) == null) {
-                client.create().creatingParentsIfNeeded().forPath(path);
+                client.create().creatingParentsIfNeeded().inBackground().forPath(path);
             }
             setData(path, str);
+
+            String pathaa = "/dubboregistrygroup1/config/aaa/dubbo.properties";
+            if (client.checkExists().forPath(pathaa) == null) {
+                client.create().creatingParentsIfNeeded().forPath(pathaa);
+            }
+            setData(pathaa, "aaaa");
+
+            String pathaaa = "/dubboregistrygroup1/config/aaa";
+            if (client.checkExists().forPath(pathaaa) == null) {
+                client.create().creatingParentsIfNeeded().inBackground().forPath(pathaaa);
+            }
+            setData(pathaaa, "aaaa");
         } catch (Exception e) {
             e.printStackTrace();
         }
@@ -154,7 +182,7 @@ public class ZKTools {
                 "  - method=routeMethod1 => 30.5.121.156:20880\n" +
                 "...";
         try {
-            String servicePath = "/dubbo/config/globalrule/";
+            String servicePath = "/dubbo/config/demo-consumer/routers";
             if (client.checkExists().forPath(servicePath) == null) {
                 client.create().creatingParentsIfNeeded().forPath(servicePath);
             }
@@ -165,7 +193,7 @@ public class ZKTools {
     }
 
     public static void setData(String path, String data) throws Exception {
-        client.setData().forPath(path, data.getBytes());
+        client.setData().inBackground().forPath(path, data.getBytes());
     }
 
     public static void testPathCache() throws Exception {
diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java
index d2c0064..3a65eb9 100644
--- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java
+++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java
@@ -32,6 +32,7 @@ import org.apache.dubbo.rpc.RpcInvocation;
 import org.apache.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance;
 import org.apache.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance;
 import org.apache.dubbo.rpc.cluster.router.script.ScriptRouterFactory;
+
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
@@ -409,10 +410,10 @@ public class RegistryDirectoryTest {
         Assert.assertEquals(false, invokers.get(0).isAvailable());
         registryDirectory.destroy();
 
-        Map<String, List<Invoker<RegistryDirectoryTest>>> methodInvokerMap = registryDirectory.getMethodInvokerMap();
+        List<Invoker<RegistryDirectoryTest>> cachedInvokers = registryDirectory.getInvokers();
         Map<String, Invoker<RegistryDirectoryTest>> urlInvokerMap = registryDirectory.getUrlInvokerMap();
 
-        Assert.assertTrue(methodInvokerMap == null);
+        Assert.assertTrue(cachedInvokers == null);
         Assert.assertEquals(0, urlInvokerMap.size());
         // List<U> urls = mockRegistry.getSubscribedUrls();
 
diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContext.java
index bf16606..cf79c15 100644
--- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContext.java
+++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContext.java
@@ -32,6 +32,7 @@ public interface AsyncContext {
      *
      * @return the internal future
      */
+    // FIXME
     CompletableFuture getInternalFuture();
 
     /**
diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java
index 75422d7..a9000ec 100644
--- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java
+++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java
@@ -50,12 +50,15 @@ public class RpcContext {
     /**
      * use internal thread local to improve performance
      */
+    // FIXME REQUEST_CONTEXT
     private static final InternalThreadLocal<RpcContext> LOCAL = new InternalThreadLocal<RpcContext>() {
         @Override
         protected RpcContext initialValue() {
             return new RpcContext();
         }
     };
+
+    // FIXME RESPONSE_CONTEXT
     private static final InternalThreadLocal<RpcContext> SERVER_LOCAL = new InternalThreadLocal<RpcContext>() {
         @Override
         protected RpcContext initialValue() {
diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java
index 74a52d7..7c63bc7 100644
--- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java
+++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java
@@ -45,6 +45,8 @@ public class ApplicationModel {
      */
     private static final ConcurrentMap<String, ConsumerModel> consumedServices = new ConcurrentHashMap<>();
 
+    private static String application;
+
     public static Collection<ConsumerModel> allConsumerModels() {
         return consumedServices.values();
     }
@@ -72,4 +74,12 @@ public class ApplicationModel {
             LOGGER.warn("Already register the same:" + serviceName);
         }
     }
+
+    public static String getApplication() {
+        return application;
+    }
+
+    public static void setApplication(String application) {
+        ApplicationModel.application = application;
+    }
 }


[incubator-dubbo] 02/07: Optimize ConfigCenter api and implementation 1. add group to api definition. 2. add removeListener implementation. 3. fix Zookeeper implementation

Posted by li...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

liujun pushed a commit to branch dev-metadata
in repository https://gitbox.apache.org/repos/asf/incubator-dubbo.git

commit c94ac7acfb4151e0d40ad4666f369ad47b690099
Author: ken.lj <ke...@gmail.com>
AuthorDate: Mon Dec 17 11:22:08 2018 +0800

    Optimize ConfigCenter api and implementation
    1. add group to api definition.
    2. add removeListener implementation.
    3. fix Zookeeper implementation
---
 .../configcenter/AbstractDynamicConfiguration.java | 35 +++++++++++-----
 .../dubbo/configcenter/ConfigChangeEvent.java      | 13 +++---
 .../dubbo/configcenter/DynamicConfiguration.java   | 47 ++++++++++++++++++++--
 .../support/nop/NopDynamicConfiguration.java       | 12 +++---
 .../mock/MockDynamicConfiguration.java             | 12 +++---
 .../support/apollo/ApolloDynamicConfiguration.java | 43 +++++++++++++++-----
 .../support/zookeeper/CacheListener.java           | 11 ++++-
 .../zookeeper/ZookeeperDynamicConfiguration.java   | 31 +++++++++-----
 .../ZookeeperDynamicConfigurationTest.java         |  2 +-
 9 files changed, 153 insertions(+), 53 deletions(-)

diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/AbstractDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/AbstractDynamicConfiguration.java
index 6d711ba..dda0905 100644
--- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/AbstractDynamicConfiguration.java
+++ b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/AbstractDynamicConfiguration.java
@@ -16,6 +16,7 @@
  */
 package org.apache.dubbo.configcenter;
 
+import org.apache.dubbo.common.Constants;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.config.AbstractConfiguration;
 
@@ -26,8 +27,8 @@ import java.util.concurrent.ConcurrentMap;
  * Dynamic configuration template class. The concrete implementation needs to provide implementation for three methods.
  *
  * @see AbstractDynamicConfiguration#getTargetConfig(String, String, long)
- * @see AbstractDynamicConfiguration#addConfigurationListener(String key, TargetListener, ConfigurationListener)
- * @see AbstractDynamicConfiguration#createTargetListener(String)
+ * @see AbstractDynamicConfiguration#addConfigurationListener(String key, String group, TargetListener, ConfigurationListener)
+ * @see AbstractDynamicConfiguration#createTargetListener(String, String group)
  */
 public abstract class AbstractDynamicConfiguration<TargetListener> extends AbstractConfiguration
         implements DynamicConfiguration {
@@ -49,8 +50,13 @@ public abstract class AbstractDynamicConfiguration<TargetListener> extends Abstr
 
     @Override
     public void addListener(String key, ConfigurationListener listener) {
-        TargetListener targetListener = targetListeners.computeIfAbsent(key, this::createTargetListener);
-        addConfigurationListener(key, targetListener, listener);
+        addListener(key, Constants.DUBBO, listener);
+    }
+
+    @Override
+    public void addListener(String key, String group, ConfigurationListener listener) {
+        TargetListener targetListener = targetListeners.computeIfAbsent(group + key, ignoreK -> this.createTargetListener(key, group));
+        addConfigurationListener(key, group, targetListener, listener);
     }
 
     @Override
@@ -75,14 +81,19 @@ public abstract class AbstractDynamicConfiguration<TargetListener> extends Abstr
 
     @Override
     public void removeListener(String key, ConfigurationListener listener) {
+        removeListener(key, Constants.DUBBO, listener);
+    }
 
+    @Override
+    public void removeListener(String key, String group, ConfigurationListener listener) {
+        TargetListener targetListener = targetListeners.get(group + key);
+        if (targetListener != null) {
+            removeConfigurationListener(key, group, targetListener, listener);
+        }
     }
 
     protected abstract void initWith(URL url);
 
-    // FIXME do wo need this?
-    protected abstract void recover();
-
     /**
      * Fetch dynamic configuration from backend config storage. If timeout exceeds, exception should be thrown.
      *
@@ -96,19 +107,23 @@ public abstract class AbstractDynamicConfiguration<TargetListener> extends Abstr
     /**
      * Register a native listener to the backend config storage so that Dubbo has chance to get notified when the
      * value changes.
-     * @param key
+     * @param key property key the native listener will listen on
+     * @param group to distinguish different set of properties
      * @param targetListener Implementation dependent listener, such as, zookeeper watcher, Apollo listener, ...
      * @param configurationListener Listener in Dubbo that will handle notification.
      */
-    protected abstract void addConfigurationListener(String key, TargetListener targetListener, ConfigurationListener configurationListener);
+    protected abstract void addConfigurationListener(String key, String group, TargetListener targetListener, ConfigurationListener configurationListener);
+
+    protected abstract void removeConfigurationListener(String key, String group, TargetListener targetListener, ConfigurationListener configurationListener);
 
     /**
      * Create a native listener for the backend config storage, eventually ConfigurationListener will get notified once
      * the value changes.
      *
      * @param key      property key the native listener will listen on
+     * @param group    to distinguish different set of properties
      * @return native listener for the backend config storage
      */
-    protected abstract TargetListener createTargetListener(String key);
+    protected abstract TargetListener createTargetListener(String key, String group);
 
 }
diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigChangeEvent.java b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigChangeEvent.java
index 068f21d..9502275 100644
--- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigChangeEvent.java
+++ b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigChangeEvent.java
@@ -23,7 +23,8 @@ package org.apache.dubbo.configcenter;
  */
 public class ConfigChangeEvent {
     private String key;
-    private String newValue;
+
+    private String value;
     private ConfigChangeType changeType;
 
     public ConfigChangeEvent(String key, String value) {
@@ -32,7 +33,7 @@ public class ConfigChangeEvent {
 
     public ConfigChangeEvent(String key, String value, ConfigChangeType changeType) {
         this.key = key;
-        this.newValue = value;
+        this.value = value;
         this.changeType = changeType;
     }
 
@@ -44,12 +45,12 @@ public class ConfigChangeEvent {
         this.key = key;
     }
 
-    public String getNewValue() {
-        return newValue;
+    public String getValue() {
+        return value;
     }
 
-    public void setNewValue(String newValue) {
-        this.newValue = newValue;
+    public void setValue(String value) {
+        this.value = value;
     }
 
     public ConfigChangeType getChangeType() {
diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java
index 6b4b476..66ea5c3 100644
--- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java
+++ b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java
@@ -17,6 +17,10 @@
 package org.apache.dubbo.configcenter;
 
 import org.apache.dubbo.common.config.Configuration;
+import org.apache.dubbo.common.config.Environment;
+import org.apache.dubbo.common.extension.ExtensionLoader;
+
+import java.util.Optional;
 
 /**
  * Dynamic configuration
@@ -24,19 +28,42 @@ import org.apache.dubbo.common.config.Configuration;
 public interface DynamicConfiguration extends Configuration {
 
     /**
-     * Register a configuration listener for a specified key
-     * The listener only works for service governance purpose, so the target group would always be the value user specifies at startup or 'dubbo' by default.
-     * This method will only register listener, which means it will not trigger a notification that contains the current value.
-     *
+     * {@link #addListener(String, String, ConfigurationListener)}
      * @param key      the key to represent a configuration
      * @param listener configuration listener
      */
     void addListener(String key, ConfigurationListener listener);
 
 
+    /**
+     * {@link #removeListener(String, String, ConfigurationListener)}
+     *
+     * @param key
+     * @param listener
+     */
     void removeListener(String key, ConfigurationListener listener);
 
     /**
+     * Register a configuration listener for a specified key
+     * The listener only works for service governance purpose, so the target group would always be the value user specifies at startup or 'dubbo' by default.
+     * This method will only register listener, which means it will not trigger a notification that contains the current value.
+     *
+     * @param key
+     * @param group
+     * @param listener
+     */
+    void addListener(String key, String group, ConfigurationListener listener);
+
+    /**
+     * Stops one listener from listening to value changes in the specified key.
+     *
+     * @param key
+     * @param group
+     * @param listener
+     */
+    void removeListener(String key, String group, ConfigurationListener listener);
+
+    /**
      * Get the configuration mapped to the given key
      *
      * @param key property key
@@ -64,4 +91,16 @@ public interface DynamicConfiguration extends Configuration {
      * if timeout exceeds.
      */
     String getConfig(String key, String group, long timeout) throws IllegalStateException;
+
+    /**
+     * I think this method is strongly related to DynamicConfiguration, so we should put it directly in the definition of this interface instead of a separated utility class.
+     *
+     * @return
+     */
+    static DynamicConfiguration getDynamicConfiguration() {
+        Optional<Configuration> optional = Environment.getInstance().getDynamicConfiguration();
+        return (DynamicConfiguration) optional.orElseGet(() -> ExtensionLoader.getExtensionLoader(DynamicConfigurationFactory.class)
+                .getDefaultExtension()
+                .getDynamicConfiguration(null));
+    }
 }
diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java
index 1c061a4..ebe9d0d 100644
--- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java
+++ b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java
@@ -45,22 +45,22 @@ public class NopDynamicConfiguration extends AbstractDynamicConfiguration {
     }
 
     @Override
-    protected void addConfigurationListener(String key, Object targetListener, ConfigurationListener configurationListener) {
+    protected void addConfigurationListener(String key, String group, Object targetListener, ConfigurationListener configurationListener) {
         // no-op
     }
 
     @Override
-    protected Object createTargetListener(String key) {
-        return null;
+    protected void removeConfigurationListener(String key, String group, Object o, ConfigurationListener configurationListener) {
+
     }
 
     @Override
-    protected Object getInternalProperty(String key) {
+    protected Object createTargetListener(String key, String group) {
         return null;
     }
 
     @Override
-    protected void recover() {
-
+    protected Object getInternalProperty(String key) {
+        return null;
     }
 }
diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java
index f2ad4c8..387f49d 100644
--- a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java
+++ b/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java
@@ -38,22 +38,22 @@ public class MockDynamicConfiguration extends AbstractDynamicConfiguration {
     }
 
     @Override
-    protected void recover() {
-
+    protected String getTargetConfig(String key, String group, long timeout) {
+        return null;
     }
 
     @Override
-    protected String getTargetConfig(String key, String group, long timeout) {
-        return null;
+    protected void addConfigurationListener(String key, String group, Object o, ConfigurationListener configurationListener) {
+
     }
 
     @Override
-    protected void addConfigurationListener(String key, Object o, ConfigurationListener configurationListener) {
+    protected void removeConfigurationListener(String key, String group, Object o, ConfigurationListener configurationListener) {
 
     }
 
     @Override
-    protected Object createTargetListener(String key) {
+    protected Object createTargetListener(String key, String group) {
         return null;
     }
 
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 8b34d55..59d2658 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
@@ -112,20 +112,37 @@ public class ApolloDynamicConfiguration extends AbstractDynamicConfiguration<Apo
         return dubboConfig.getProperty(key, null);
     }
 
+    /**
+     * Since all governance rules will lay under dubbo group, this method now always uses the default dubboConfig and ignores the group parameter.
+     *
+     * @param key                   property key the native listener will listen on
+     * @param group                 to distinguish different set of properties
+     * @param listener
+     * @param configurationListener Listener in Dubbo that will handle notification.
+     */
     @Override
-    protected void addConfigurationListener(String key, ApolloListener listener, ConfigurationListener configurationListener) {
+    protected void addConfigurationListener(String key, String group, ApolloListener listener, ConfigurationListener configurationListener) {
         listener.addListener(configurationListener);
         this.dubboConfig.addChangeListener(listener);
     }
 
     @Override
-    protected ApolloListener createTargetListener(String key) {
-        return new ApolloListener();
+    protected void removeConfigurationListener(String key, String group, ApolloListener listener, ConfigurationListener configurationListener) {
+        listener.removeListener(configurationListener);
+        if (!listener.hasInternalListener()) {
+            dubboConfig.removeChangeListener(listener);
+        }
     }
 
+    /**
+     * Ignores the group parameter.
+     * @param key      property key the native listener will listen on
+     * @param group    to distinguish different set of properties
+     * @return
+     */
     @Override
-    protected void recover() {
-        // Apollo will handle things well.
+    protected ApolloListener createTargetListener(String key, String group) {
+        return new ApolloListener();
     }
 
     public class ApolloListener implements ConfigChangeListener {
@@ -135,10 +152,6 @@ public class ApolloDynamicConfiguration extends AbstractDynamicConfiguration<Apo
         ApolloListener() {
         }
 
-        public void addListener(ConfigurationListener configurationListener) {
-            this.listeners.add(configurationListener);
-        }
-
         @Override
         public void onChange(com.ctrip.framework.apollo.model.ConfigChangeEvent changeEvent) {
             for (String key : changeEvent.changedKeys()) {
@@ -161,6 +174,18 @@ public class ApolloDynamicConfiguration extends AbstractDynamicConfiguration<Apo
             }
             return ConfigChangeType.MODIFIED;
         }
+
+        public void addListener(ConfigurationListener configurationListener) {
+            this.listeners.add(configurationListener);
+        }
+
+        public void removeListener(ConfigurationListener configurationListener) {
+            this.listeners.remove(configurationListener);
+        }
+
+        public boolean hasInternalListener() {
+            return listeners != null && listeners.size() > 0;
+        }
     }
 
 }
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 b2d1d09..d08fe8f 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
@@ -92,8 +92,15 @@ public class CacheListener implements TreeCacheListener {
     }
 
     public void addListener(String key, ConfigurationListener configurationListener) {
-        Set<ConfigurationListener> set = this.keyListeners.computeIfAbsent(key, k -> new CopyOnWriteArraySet<>());
-        set.add(configurationListener);
+        Set<ConfigurationListener> listeners = this.keyListeners.computeIfAbsent(key, k -> new CopyOnWriteArraySet<>());
+        listeners.add(configurationListener);
+    }
+
+    public void removeListener(String key, ConfigurationListener configurationListener) {
+        Set<ConfigurationListener> listeners = this.keyListeners.get(key);
+        if (listeners != null) {
+            listeners.remove(configurationListener);
+        }
     }
 
     /**
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 f43e606..0bc9b99 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
@@ -18,6 +18,7 @@ package org.apache.dubbo.configcenter.support.zookeeper;
 
 import org.apache.dubbo.common.Constants;
 import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.utils.NamedThreadFactory;
 import org.apache.dubbo.common.utils.StringUtils;
 import org.apache.dubbo.configcenter.AbstractDynamicConfiguration;
 import org.apache.dubbo.configcenter.ConfigurationListener;
@@ -88,7 +89,7 @@ public class ZookeeperDynamicConfiguration extends AbstractDynamicConfiguration<
 
         initializedLatch = new CountDownLatch(1);
         this.cacheListener = new CacheListener(rootPath, initializedLatch);
-        this.executor = Executors.newFixedThreadPool(1);
+        this.executor = Executors.newFixedThreadPool(1, new NamedThreadFactory(this.getClass().getSimpleName(), true));
         // build local cache
         try {
             this.buildCache();
@@ -100,19 +101,35 @@ public class ZookeeperDynamicConfiguration extends AbstractDynamicConfiguration<
     @Override
     protected String getTargetConfig(String key, String group, long timeout) {
         if (StringUtils.isNotEmpty(group)) {
-            key = group + "." + key;
+            key = group + "/" + key;
+        } else {
+            int i = key.lastIndexOf(".");
+            key = key.substring(0, i) + "/" + key.substring(i + 1);
         }
 
-        return (String) getInternalProperty(rootPath + "/" + key.replaceFirst("\\.", "/"));
+        return (String) getInternalProperty(rootPath + "/" + key);
     }
 
+    /**
+     * For service governance, multi group is not supported by this implementation. So group is not used at present.
+     *
+     * @param key
+     * @param group
+     * @param cacheListener
+     * @param listener
+     */
     @Override
-    protected void addConfigurationListener(String key, CacheListener cacheListener, ConfigurationListener listener) {
+    protected void addConfigurationListener(String key, String group, CacheListener cacheListener, ConfigurationListener listener) {
         cacheListener.addListener(key, listener);
     }
 
     @Override
-    protected CacheListener createTargetListener(String key) {
+    protected void removeConfigurationListener(String key, String group, CacheListener cacheListener, ConfigurationListener configurationListener) {
+        cacheListener.removeListener(key, configurationListener);
+    }
+
+    @Override
+    protected CacheListener createTargetListener(String key, String group) {
         return cacheListener;
     }
 
@@ -129,10 +146,6 @@ public class ZookeeperDynamicConfiguration extends AbstractDynamicConfiguration<
         return null;
     }
 
-    protected void recover() {
-
-    }
-
     /**
      * Adds a listener to the pathChildrenCache, initializes the cache, then starts the cache-management background
      * thread
diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java
index e3b137b..8b82c09 100644
--- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java
+++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java
@@ -135,7 +135,7 @@ public class ZookeeperDynamicConfigurationTest {
             Integer count = countMap.computeIfAbsent(event.getKey(), k -> new Integer(0));
             countMap.put(event.getKey(), ++count);
 
-            value = event.getNewValue();
+            value = event.getValue();
             latch.countDown();
         }