You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dubbo.apache.org by al...@apache.org on 2021/11/21 07:55:18 UTC
[dubbo] branch 3.0 updated: [3.0] Refactor State Router (#9228)
This is an automated email from the ASF dual-hosted git repository.
albumenj pushed a commit to branch 3.0
in repository https://gitbox.apache.org/repos/asf/dubbo.git
The following commit(s) were added to refs/heads/3.0 by this push:
new b66509e [3.0] Refactor State Router (#9228)
b66509e is described below
commit b66509e4a43c6208dd5567242a6843fa80910c5f
Author: Albumen Kevin <jh...@gmail.com>
AuthorDate: Sun Nov 21 15:55:01 2021 +0800
[3.0] Refactor State Router (#9228)
* Refactor StateRouter, remove router cache
* Remove unused class
* refactor builtin routers to state routers
* add log
* remove unused method
* move order
* Add generics support
---
.../org/apache/dubbo/rpc/cluster/Constants.java | 4 -
.../org/apache/dubbo/rpc/cluster/RouterChain.java | 248 +++++---------------
.../rpc/cluster/directory/StaticDirectory.java | 3 +-
...ditionRouter.java => ConditionStateRouter.java} | 54 +++--
...ctory.java => ConditionStateRouterFactory.java} | 13 +-
.../config/{AppRouter.java => AppStateRouter.java} | 4 +-
...uterFactory.java => AppStateRouterFactory.java} | 14 +-
...nableRouter.java => ListenableStateRouter.java} | 41 ++--
.../router/condition/config/ServiceRouter.java | 2 +-
...Factory.java => ServiceStateRouterFactory.java} | 10 +-
...terFactory.java => FileStateRouterFactory.java} | 18 +-
.../cluster/router/mock/MockInvokersSelector.java | 80 +++----
...terFactory.java => MockStateRouterFactory.java} | 10 +-
.../{ScriptRouter.java => ScriptStateRouter.java} | 33 +--
...rFactory.java => ScriptStateRouterFactory.java} | 10 +-
.../cluster/router/state/AbstractStateRouter.java | 65 +-----
.../dubbo/rpc/cluster/router/state/AddrCache.java | 51 ----
.../router/state/CacheableStateRouterFactory.java | 12 +-
.../rpc/cluster/router/state/RouterCache.java | 49 ----
.../rpc/cluster/router/state/StateRouter.java | 65 ++----
.../cluster/router/state/StateRouterFactory.java | 3 +-
.../cluster/router/tag/TagDynamicStateRouter.java | 260 ---------------------
.../router/tag/TagDynamicStateRouterFactory.java | 37 ---
.../rpc/cluster/router/tag/TagRouterFactory.java | 36 ---
.../tag/{TagRouter.java => TagStateRouter.java} | 58 ++---
...uterFactory.java => TagStateRouterFactory.java} | 9 +-
.../cluster/router/tag/TagStaticStateRouter.java | 144 ------------
.../org.apache.dubbo.rpc.cluster.RouterFactory | 6 -
...bbo.rpc.cluster.router.state.StateRouterFactory | 8 +-
.../apache/dubbo/rpc/cluster/RouterChainTest.java | 7 +-
.../rpc/cluster/directory/StaticDirectoryTest.java | 20 +-
.../loadbalance/ConsistentHashLoadBalanceTest.java | 2 +-
.../router/condition/ConditionRouterTest.java | 209 +++++++++--------
.../cluster/router/file/FileRouterEngineTest.java | 8 +-
.../router/mock/MockInvokersSelectorTest.java | 6 +-
...tRouterTest.java => ScriptStateRouterTest.java} | 51 ++--
.../org.apache.dubbo.rpc.cluster.RouterFactory | 1 -
...bbo.rpc.cluster.router.state.StateRouterFactory | 1 +
.../dubbo/config/AbstractReferenceConfigTest.java | 19 +-
.../META-INF/native-image/reflect-config.json | 8 +-
.../router/state/StateRouterFactory$Adaptive.java | 6 +-
.../client/ServiceDiscoveryRegistryDirectory.java | 2 +-
.../registry/integration/DynamicDirectory.java | 2 +-
43 files changed, 482 insertions(+), 1207 deletions(-)
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java
index 7af4210..ad9bd0d 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java
@@ -109,10 +109,6 @@ public interface Constants {
String ROUTER_KEY = "router";
/**
- * The key for state router
- */
- String STATE_ROUTER_KEY = "stateRouter";
- /**
* The key name for reference URL in register center
*/
String REFER_KEY = "refer";
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 0522ace..fae9062 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
@@ -20,34 +20,23 @@ import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
-import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.router.RouterResult;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
-import org.apache.dubbo.rpc.cluster.router.state.AddrCache;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
-import org.apache.dubbo.rpc.cluster.router.state.RouterCache;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterResult;
import java.util.ArrayList;
import java.util.Collections;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY;
-import static org.apache.dubbo.rpc.cluster.Constants.STATE_ROUTER_KEY;
/**
* Router chain
@@ -69,31 +58,16 @@ public class RouterChain<T> {
* 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> builtinRouters = Collections.emptyList();
+ private volatile List<Router> builtinRouters = Collections.emptyList();
- private List<StateRouter> builtinStateRouters = Collections.emptyList();
- private List<StateRouter> stateRouters = Collections.emptyList();
- private final ExecutorRepository executorRepository;
+ private volatile List<StateRouter<T>> builtinStateRouters = Collections.emptyList();
+ private volatile List<StateRouter<T>> stateRouters = Collections.emptyList();
- protected URL url;
-
- private AtomicReference<AddrCache<T>> cache = new AtomicReference<>();
-
- private final Semaphore loopPermit = new Semaphore(1);
- private final Semaphore loopPermitNotify = new Semaphore(1);
-
- private final ExecutorService loopPool;
-
- private AtomicBoolean firstBuildCache = new AtomicBoolean(true);
-
- public static <T> RouterChain<T> buildChain(URL url) {
- return new RouterChain<>(url);
+ public static <T> RouterChain<T> buildChain(Class<T> interfaceClass, URL url) {
+ return new RouterChain<>(interfaceClass, url);
}
- private RouterChain(URL url) {
- executorRepository = url.getOrDefaultApplicationModel().getExtensionLoader(ExecutorRepository.class)
- .getDefaultExtension();
- loopPool = executorRepository.nextExecutorExecutor();
+ private RouterChain(Class<T> interfaceClass, URL url) {
List<RouterFactory> extensionFactories = url.getOrDefaultApplicationModel().getExtensionLoader(RouterFactory.class)
.getActivateExtension(url, ROUTER_KEY);
@@ -106,10 +80,10 @@ public class RouterChain<T> {
List<StateRouterFactory> extensionStateRouterFactories = url.getOrDefaultApplicationModel()
.getExtensionLoader(StateRouterFactory.class)
- .getActivateExtension(url, STATE_ROUTER_KEY);
+ .getActivateExtension(url, ROUTER_KEY);
- List<StateRouter> stateRouters = extensionStateRouterFactories.stream()
- .map(factory -> factory.getRouter(url, this))
+ List<StateRouter<T>> stateRouters = extensionStateRouterFactories.stream()
+ .map(factory -> factory.getRouter(interfaceClass, url))
.sorted(StateRouter::compareTo)
.collect(Collectors.toList());
@@ -119,16 +93,24 @@ public class RouterChain<T> {
/**
* the resident routers must being initialized before address notification.
- * FIXME: this method should not be public
+ * only for ut
*/
public void initWithRouters(List<Router> builtinRouters) {
this.builtinRouters = builtinRouters;
this.routers = new ArrayList<>(builtinRouters);
}
- private void initWithStateRouters(List<StateRouter> builtinRouters) {
+ /**
+ * the resident routers must being initialized before address notification.
+ * only for ut
+ */
+ public void initWithStateRouters(List<StateRouter<T>> builtinRouters) {
this.builtinStateRouters = builtinRouters;
- this.stateRouters = new ArrayList<>(builtinRouters);
+ setStateRouters(builtinStateRouters);
+ }
+
+ private void setStateRouters(List<StateRouter<T>> stateRouters) {
+ this.stateRouters = new ArrayList<>(stateRouters);
}
/**
@@ -147,19 +129,19 @@ public class RouterChain<T> {
this.routers = newRouters;
}
- public void addStateRouters(List<StateRouter> stateRouters) {
- List<StateRouter> newStateRouters = new ArrayList<>();
+ public void addStateRouters(List<StateRouter<T>> stateRouters) {
+ List<StateRouter<T>> newStateRouters = new ArrayList<>();
newStateRouters.addAll(builtinStateRouters);
newStateRouters.addAll(stateRouters);
CollectionUtils.sort(newStateRouters);
- this.stateRouters = newStateRouters;
+ setStateRouters(newStateRouters);
}
public List<Router> getRouters() {
return routers;
}
- public List<StateRouter> getStateRouters() {
+ public List<StateRouter<T>> getStateRouters() {
return stateRouters;
}
@@ -170,29 +152,24 @@ public class RouterChain<T> {
*/
public List<Invoker<T>> route(URL url, BitList<Invoker<T>> availableInvokers, Invocation invocation) {
- AddrCache<T> cache = this.cache.get();
BitList<Invoker<T>> resultInvokers = availableInvokers.clone();
// 1. route state router
- if (cache != null) {
- for (StateRouter stateRouter : stateRouters) {
- if (stateRouter.isEnable()) {
- RouterCache<T> routerCache = cache.getCache().get(stateRouter.getName());
- StateRouterResult<Invoker<T>> routeResult = stateRouter.route(resultInvokers, routerCache, url, invocation, false);
- resultInvokers = routeResult.getResult();
- if (resultInvokers.isEmpty()) {
- printRouterSnapshot(url, availableInvokers, invocation);
- return BitList.emptyList();
- }
-
- // stop continue routing
- if (!routeResult.isNeedContinueRoute()) {
- return routeResult.getResult();
- }
- }
+ for (StateRouter<T> stateRouter : stateRouters) {
+ StateRouterResult<Invoker<T>> routeResult = stateRouter.route(resultInvokers, url, invocation, false);
+ resultInvokers = routeResult.getResult();
+ if (resultInvokers.isEmpty()) {
+ printRouterSnapshot(url, availableInvokers, invocation);
+ return BitList.emptyList();
+ }
+
+ // stop continue routing
+ if (!routeResult.isNeedContinueRoute()) {
+ return routeResult.getResult();
}
}
+
List<Invoker<T>> commonRouterResult = new ArrayList<>(resultInvokers);
// 2. route common router
for (Router router : routers) {
@@ -223,37 +200,31 @@ public class RouterChain<T> {
* Build each router's result
*/
public RouterSnapshotNode<T> buildRouterSnapshot(URL url, BitList<Invoker<T>> availableInvokers, Invocation invocation) {
- AddrCache<T> cache = this.cache.get();
BitList<Invoker<T>> resultInvokers = availableInvokers.clone();
RouterSnapshotNode<T> snapshotNode = new RouterSnapshotNode<T>("Parent", resultInvokers.size());
snapshotNode.setOutputInvokers(resultInvokers.clone());
// 1. route state router
- if (cache != null) {
- for (StateRouter stateRouter : stateRouters) {
- if (stateRouter.isEnable()) {
- BitList<Invoker<T>> inputInvokers = resultInvokers.clone();
-
- RouterSnapshotNode<T> currentNode = new RouterSnapshotNode<T>(stateRouter.getName(), inputInvokers.size());
- snapshotNode.appendNode(currentNode);
-
- RouterCache<T> routerCache = cache.getCache().get(stateRouter.getName());
- StateRouterResult<Invoker<T>> routeResult = stateRouter.route(inputInvokers, routerCache, url, invocation, true);
- resultInvokers = routeResult.getResult();
- String routerMessage = routeResult.getMessage();
-
- currentNode.setOutputInvokers(resultInvokers);
- currentNode.setRouterMessage(routerMessage);
-
- // result is empty, log out
- if (resultInvokers.isEmpty()) {
- return snapshotNode;
- }
-
- if (!routeResult.isNeedContinueRoute()) {
- return snapshotNode;
- }
- }
+ for (StateRouter stateRouter : stateRouters) {
+ BitList<Invoker<T>> inputInvokers = resultInvokers.clone();
+
+ RouterSnapshotNode<T> currentNode = new RouterSnapshotNode<T>(stateRouter.getClass().getSimpleName(), inputInvokers.size());
+ snapshotNode.appendNode(currentNode);
+
+ StateRouterResult<Invoker<T>> routeResult = stateRouter.route(inputInvokers, url, invocation, true);
+ resultInvokers = routeResult.getResult();
+ String routerMessage = routeResult.getMessage();
+
+ currentNode.setOutputInvokers(resultInvokers);
+ currentNode.setRouterMessage(routerMessage);
+
+ // result is empty, log out
+ if (resultInvokers.isEmpty()) {
+ return snapshotNode;
+ }
+
+ if (!routeResult.isNeedContinueRoute()) {
+ return snapshotNode;
}
}
@@ -300,111 +271,8 @@ public class RouterChain<T> {
*/
public void setInvokers(BitList<Invoker<T>> invokers) {
this.invokers = (invokers == null ? BitList.emptyList() : invokers);
- stateRouters.forEach(router -> router.notify(this.invokers));
routers.forEach(router -> router.notify(this.invokers));
- loop(true);
- }
-
- /**
- * Build the asynchronous address cache for stateRouter.
- *
- * @param notify Whether the addresses in registry have changed.
- */
- private void buildCache(boolean notify) {
- if (CollectionUtils.isEmpty(invokers)) {
- return;
- }
- AddrCache<T> origin = cache.get();
- AddrCache<T> newCache = new AddrCache<T>();
- Map<String, RouterCache<T>> routerCacheMap = new HashMap<>((int) (stateRouters.size() / 0.75f) + 1);
- newCache.setInvokers(invokers);
- for (StateRouter stateRouter : stateRouters) {
- try {
- RouterCache routerCache = poolRouter(stateRouter, origin, invokers, notify);
- //file cache
- routerCacheMap.put(stateRouter.getName(), routerCache);
- } catch (Throwable t) {
- logger.error("Failed to pool router: " + stateRouter.getUrl() + ", cause: " + t.getMessage(), t);
- return;
- }
- }
-
- newCache.setCache(routerCacheMap);
- this.cache.set(newCache);
- }
-
- /**
- * Cache the address list for each StateRouter.
- *
- * @param router router
- * @param origin The original address cache
- * @param invokers The full address list
- * @param notify Whether the addresses in registry has changed.
- * @return
- */
- private RouterCache poolRouter(StateRouter router, AddrCache<T> origin, List<Invoker<T>> invokers, boolean notify) {
- String routerName = router.getName();
- RouterCache routerCache;
- if (isCacheMiss(origin, routerName) || router.shouldRePool() || notify) {
- return router.pool(invokers);
- } else {
- routerCache = origin.getCache().get(routerName);
- }
- if (routerCache == null) {
- return new RouterCache();
- }
- return routerCache;
- }
-
- private boolean isCacheMiss(AddrCache<T> cache, String routerName) {
- return cache == null || cache.getCache() == null || cache.getInvokers() == null || cache.getCache().get(
- routerName)
- == null;
- }
-
- /***
- * Build the asynchronous address cache for stateRouter.
- * @param notify Whether the addresses in registry has changed.
- */
- public void loop(boolean notify) {
- if (firstBuildCache.compareAndSet(true, false)) {
- buildCache(notify);
- }
-
- try {
- if (notify) {
- if (loopPermitNotify.tryAcquire()) {
- loopPool.submit(new NotifyLoopRunnable(true, loopPermitNotify));
- }
- } else {
- if (loopPermit.tryAcquire()) {
- loopPool.submit(new NotifyLoopRunnable(false, loopPermit));
- }
- }
- } catch (RejectedExecutionException e) {
- if (loopPool.isShutdown()) {
- logger.warn("loopPool executor service is shutdown, ignoring notify loop");
- return;
- }
- throw e;
- }
- }
-
- class NotifyLoopRunnable implements Runnable {
-
- private final boolean notify;
- private final Semaphore loopPermit;
-
- public NotifyLoopRunnable(boolean notify, Semaphore loopPermit) {
- this.notify = notify;
- this.loopPermit = loopPermit;
- }
-
- @Override
- public void run() {
- buildCache(notify);
- loopPermit.release();
- }
+ stateRouters.forEach(router -> router.notify(this.invokers));
}
public void destroy() {
@@ -426,7 +294,7 @@ public class RouterChain<T> {
logger.error("Error trying to stop stateRouter " + router.getClass(), e);
}
}
- stateRouters = Collections.emptyList();
+ setStateRouters(Collections.emptyList());
builtinStateRouters = Collections.emptyList();
}
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 ed6eb2d..58a2462 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
@@ -89,9 +89,8 @@ public class StaticDirectory<T> extends AbstractDirectory<T> {
}
public void buildRouterChain() {
- RouterChain<T> routerChain = RouterChain.buildChain(getUrl());
+ RouterChain<T> routerChain = RouterChain.buildChain(getInterface(), getUrl());
routerChain.setInvokers(getInvokers());
- routerChain.loop(true);
this.setRouterChain(routerChain);
}
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/ConditionStateRouter.java
similarity index 87%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouter.java
index 7144bc5..a96a579 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/ConditionStateRouter.java
@@ -27,14 +27,14 @@ import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Constants;
-import org.apache.dubbo.rpc.cluster.router.AbstractRouter;
-import org.apache.dubbo.rpc.cluster.router.RouterResult;
+import org.apache.dubbo.rpc.cluster.router.condition.config.AppStateRouter;
+import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
+import org.apache.dubbo.rpc.cluster.router.state.BitList;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouterResult;
import java.text.ParseException;
-import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
@@ -55,13 +55,13 @@ import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
* It supports the conditional routing configured by "override://", in 2.6.x,
* refer to https://dubbo.apache.org/en/docs/v2.7/user/examples/routing-rule/ .
* For 2.7.x and later, please refer to {@link org.apache.dubbo.rpc.cluster.router.condition.config.ServiceRouter}
- * and {@link org.apache.dubbo.rpc.cluster.router.condition.config.AppRouter}
+ * and {@link AppStateRouter}
* refer to https://dubbo.apache.org/zh/docs/v2.7/user/examples/routing-rule/ .
*/
-public class ConditionRouter extends AbstractRouter {
+public class ConditionStateRouter<T> extends AbstractStateRouter<T> {
public static final String NAME = "condition";
- private static final Logger logger = LoggerFactory.getLogger(ConditionRouter.class);
+ private static final Logger logger = LoggerFactory.getLogger(ConditionStateRouter.class);
protected static final Pattern ROUTE_PATTERN = Pattern.compile("([&!=,]*)\\s*([^&!=,\\s]+)");
protected static Pattern ARGUMENTS_PATTERN = Pattern.compile("arguments\\[([0-9]+)\\]");
protected Map<String, MatchPair> whenCondition;
@@ -69,7 +69,8 @@ public class ConditionRouter extends AbstractRouter {
private boolean enabled;
- public ConditionRouter(String rule, boolean force, boolean enabled) {
+ public ConditionStateRouter(URL url, String rule, boolean force, boolean enabled) {
+ super(url);
this.setForce(force);
this.enabled = enabled;
if (enabled) {
@@ -77,7 +78,8 @@ public class ConditionRouter extends AbstractRouter {
}
}
- public ConditionRouter(URL url) {
+ public ConditionStateRouter(URL url) {
+ super(url);
this.setUrl(url);
this.setPriority(url.getParameter(PRIORITY_KEY, 0));
this.setForce(url.getParameter(FORCE_KEY, false));
@@ -177,40 +179,44 @@ public class ConditionRouter extends AbstractRouter {
}
@Override
- public <T> RouterResult<Invoker<T>> route(List<Invoker<T>> invokers, URL url,
- Invocation invocation, boolean needToPrintMessage) throws RpcException {
+ public StateRouterResult<Invoker<T>> route(BitList<Invoker<T>> invokers, URL url,
+ Invocation invocation, boolean needToPrintMessage) throws RpcException {
if (!enabled) {
- return new RouterResult<>(invokers);
+ return new StateRouterResult<>(invokers,
+ needToPrintMessage ? "Directly return. Reason: ConditionRouter disabled." : null);
}
if (CollectionUtils.isEmpty(invokers)) {
- return new RouterResult<>(invokers);
+ return new StateRouterResult<>(invokers,
+ needToPrintMessage ? "Directly return. Reason: Invokers from previous router is empty." : null);
}
try {
if (!matchWhen(url, invocation)) {
- return new RouterResult<>(invokers);
+ return new StateRouterResult<>(invokers,
+ needToPrintMessage ? "Directly return. Reason: WhenCondition not match." : null);
}
- List<Invoker<T>> result = new ArrayList<Invoker<T>>();
if (thenCondition == null) {
logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey());
- return new RouterResult<>(result);
- }
- for (Invoker<T> invoker : invokers) {
- if (matchThen(invoker.getUrl(), url)) {
- result.add(invoker);
- }
+ return new StateRouterResult<>(BitList.emptyList(),
+ needToPrintMessage ? "Empty return. Reason: ThenCondition is empty." : null);
}
+ BitList<Invoker<T>> result = invokers.clone();
+ result.removeIf(invoker -> !matchThen(invoker.getUrl(), url));
+
if (!result.isEmpty()) {
- return new RouterResult<>(result);
+ return new StateRouterResult<>(result,
+ needToPrintMessage ? "Match return." : null);
} else if (this.isForce()) {
logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(RULE_KEY));
- return new RouterResult<>(result);
+ return new StateRouterResult<>(result,
+ needToPrintMessage ? "Empty return. Reason: Empty result from condition and condition is force." : null);
}
} catch (Throwable t) {
logger.error("Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + t.getMessage(), t);
}
- return new RouterResult<>(invokers);
+ return new StateRouterResult<>(invokers,
+ needToPrintMessage ? "Directly return. Reason: Error occurred ( or result is empty )." : null);
}
@Override
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterFactory.java
similarity index 70%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterFactory.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterFactory.java
index 71df97c..06a40e8 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterFactory.java
@@ -17,20 +17,19 @@
package org.apache.dubbo.rpc.cluster.router.condition;
import org.apache.dubbo.common.URL;
-import org.apache.dubbo.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
+import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
/**
* ConditionRouterFactory
- * Load when "override://" is configured {@link ConditionRouter}
+ * Load when "override://" is configured {@link ConditionStateRouter}
*/
-public class ConditionRouterFactory implements RouterFactory {
+public class ConditionStateRouterFactory extends CacheableStateRouterFactory {
public static final String NAME = "condition";
@Override
- public Router getRouter(URL url) {
- return new ConditionRouter(url);
+ protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
+ return new ConditionStateRouter<T>(url);
}
-
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouter.java
similarity index 92%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouter.java
index abc1925..a8117d7 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouter.java
@@ -21,14 +21,14 @@ import org.apache.dubbo.common.URL;
/**
* Application level router, "application.condition-router"
*/
-public class AppRouter extends ListenableRouter {
+public class AppStateRouter<T> extends ListenableStateRouter<T> {
public static final String NAME = "APP_ROUTER";
/**
* AppRouter should after ServiceRouter
*/
private static final int APP_ROUTER_DEFAULT_PRIORITY = 150;
- public AppRouter(URL url) {
+ public AppStateRouter(URL url) {
super(url, url.getApplication());
this.setPriority(APP_ROUTER_DEFAULT_PRIORITY);
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouterFactory.java
similarity index 76%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouterFactory.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouterFactory.java
index c0464d8..e35340a 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouterFactory.java
@@ -18,20 +18,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.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
/**
* Application level router factory
*/
@Activate(order = 200)
-public class AppRouterFactory implements RouterFactory {
+public class AppStateRouterFactory implements StateRouterFactory {
public static final String NAME = "app";
- private volatile Router router;
+ private volatile StateRouter router;
@Override
- public Router getRouter(URL url) {
+ public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
if (router != null) {
return router;
}
@@ -43,7 +43,7 @@ public class AppRouterFactory implements RouterFactory {
return router;
}
- private Router createRouter(URL url) {
- return new AppRouter(url);
+ private <T> StateRouter<T> createRouter(URL url) {
+ return new AppStateRouter<>(url);
}
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.java
similarity index 71%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableRouter.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.java
index ee08c94..9ca3eb3 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.java
@@ -28,12 +28,13 @@ import org.apache.dubbo.common.utils.StringUtils;
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.RouterResult;
-import org.apache.dubbo.rpc.cluster.router.condition.ConditionRouter;
+import org.apache.dubbo.rpc.cluster.router.condition.ConditionStateRouter;
import org.apache.dubbo.rpc.cluster.router.condition.config.model.ConditionRouterRule;
import org.apache.dubbo.rpc.cluster.router.condition.config.model.ConditionRuleParser;
+import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
+import org.apache.dubbo.rpc.cluster.router.state.BitList;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouterResult;
import java.util.Collections;
import java.util.List;
@@ -42,16 +43,16 @@ import java.util.stream.Collectors;
/**
* Abstract router which listens to dynamic configuration
*/
-public abstract class ListenableRouter extends AbstractRouter implements ConfigurationListener {
+public abstract class ListenableStateRouter<T> extends AbstractStateRouter<T> implements ConfigurationListener {
public static final String NAME = "LISTENABLE_ROUTER";
private static final String RULE_SUFFIX = ".condition-router";
- private static final Logger logger = LoggerFactory.getLogger(ListenableRouter.class);
+ private static final Logger logger = LoggerFactory.getLogger(ListenableStateRouter.class);
private volatile ConditionRouterRule routerRule;
- private volatile List<ConditionRouter> conditionRouters = Collections.emptyList();
+ private volatile List<ConditionStateRouter> conditionRouters = Collections.emptyList();
private String ruleKey;
- public ListenableRouter(URL url, String ruleKey) {
+ public ListenableStateRouter(URL url, String ruleKey) {
super(url);
this.setForce(false);
this.init(ruleKey);
@@ -80,18 +81,28 @@ public abstract class ListenableRouter extends AbstractRouter implements Configu
}
@Override
- public <T> RouterResult<Invoker<T>> route(List<Invoker<T>> invokers, URL url,
- Invocation invocation, boolean needToPrintMessage) throws RpcException {
+ public StateRouterResult<Invoker<T>> route(BitList<Invoker<T>> invokers, URL url,
+ Invocation invocation, boolean needToPrintMessage) throws RpcException {
if (CollectionUtils.isEmpty(invokers) || conditionRouters.size() == 0) {
- return new RouterResult<>(invokers);
+ return new StateRouterResult<>(invokers,
+ needToPrintMessage ? "Directly return. Reason: Invokers from previous router is empty or conditionRouters is empty." : null);
}
// We will check enabled status inside each router.
- for (Router router : conditionRouters) {
- invokers = router.route(invokers, url, invocation, needToPrintMessage).getResult();
+ StringBuilder resultMessage = null;
+ if (needToPrintMessage) {
+ resultMessage = new StringBuilder();
+ }
+ for (StateRouter router : conditionRouters) {
+ StateRouterResult<Invoker<T>> routerResult = router.route(invokers, url, invocation, needToPrintMessage);
+ invokers = routerResult.getResult();
+ if (needToPrintMessage) {
+ resultMessage.append(routerResult.getMessage());
+ }
}
- return new RouterResult<>(invokers);
+ return new StateRouterResult<>(invokers,
+ needToPrintMessage ? resultMessage.toString() : null);
}
@Override
@@ -107,7 +118,7 @@ public abstract class ListenableRouter extends AbstractRouter implements Configu
if (rule != null && rule.isValid()) {
this.conditionRouters = rule.getConditions()
.stream()
- .map(condition -> new ConditionRouter(condition, rule.isForce(), rule.isEnabled()))
+ .map(condition -> new ConditionStateRouter(getUrl(), condition, rule.isForce(), rule.isEnabled()))
.collect(Collectors.toList());
}
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouter.java
index 81e202d..1f24a87 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouter.java
@@ -22,7 +22,7 @@ import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
/**
* Service level router, "server-unique-name.condition-router"
*/
-public class ServiceRouter extends ListenableRouter {
+public class ServiceRouter<T> extends ListenableStateRouter<T> {
public static final String NAME = "SERVICE_ROUTER";
/**
* ServiceRouter should before AppRouter
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java
similarity index 76%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouterFactory.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java
index af971d7..a969fd3 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java
@@ -18,20 +18,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.rpc.cluster.CacheableRouterFactory;
-import org.apache.dubbo.rpc.cluster.Router;
+import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
/**
* Service level router factory
*/
@Activate(order = 300)
-public class ServiceRouterFactory extends CacheableRouterFactory {
+public class ServiceStateRouterFactory extends CacheableStateRouterFactory {
public static final String NAME = "service";
@Override
- protected Router createRouter(URL url) {
- return new ServiceRouter(url);
+ protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
+ return new ServiceRouter<T>(url);
}
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileStateRouterFactory.java
similarity index 80%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileStateRouterFactory.java
index 95d8100..9bdd5ca 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileStateRouterFactory.java
@@ -19,9 +19,9 @@ package org.apache.dubbo.rpc.cluster.router.file;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.utils.IOUtils;
-import org.apache.dubbo.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
-import org.apache.dubbo.rpc.cluster.router.script.ScriptRouterFactory;
+import org.apache.dubbo.rpc.cluster.router.script.ScriptStateRouterFactory;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
import java.io.File;
import java.io.FileReader;
@@ -32,22 +32,22 @@ import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY;
-public class FileRouterFactory implements RouterFactory {
+public class FileStateRouterFactory implements StateRouterFactory {
public static final String NAME = "file";
- private RouterFactory routerFactory;
+ private StateRouterFactory routerFactory;
- public void setRouterFactory(RouterFactory routerFactory) {
+ public void setRouterFactory(StateRouterFactory routerFactory) {
this.routerFactory = routerFactory;
}
@Override
- public Router getRouter(URL url) {
+ public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
try {
// Transform File URL into Script Route URL, and Load
// file:///d:/path/to/route.js?router=script ==> script:///d:/path/to/route.js?type=js&rule=<file-content>
- String protocol = url.getParameter(ROUTER_KEY, ScriptRouterFactory.NAME); // Replace original protocol (maybe 'file') with 'script'
+ String protocol = url.getParameter(ROUTER_KEY, ScriptStateRouterFactory.NAME); // Replace original protocol (maybe 'file') with 'script'
String type = null; // Use file suffix to config script type, e.g., js, groovy ...
String path = url.getPath();
if (path != null) {
@@ -67,7 +67,7 @@ public class FileRouterFactory implements RouterFactory {
.addParameterAndEncoded(RULE_KEY, rule)
.build();
- return routerFactory.getRouter(script);
+ return routerFactory.getRouter(interfaceClass, script);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
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 b3bd9f1..b70a4c4 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
@@ -21,11 +21,9 @@ 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.rpc.cluster.router.AbstractRouter;
-import org.apache.dubbo.rpc.cluster.router.RouterResult;
-
-import java.util.ArrayList;
-import java.util.List;
+import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
+import org.apache.dubbo.rpc.cluster.router.state.BitList;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouterResult;
import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK;
import static org.apache.dubbo.rpc.cluster.Constants.MOCK_PROTOCOL;
@@ -34,71 +32,61 @@ import static org.apache.dubbo.rpc.cluster.Constants.MOCK_PROTOCOL;
* A specific Router designed to realize mock feature.
* If a request is configured to use mock, then this router guarantees that only the invokers with protocol MOCK appear in final the invoker list, all other invokers will be excluded.
*/
-public class MockInvokersSelector extends AbstractRouter {
+public class MockInvokersSelector<T> extends AbstractStateRouter<T> {
public static final String NAME = "MOCK_ROUTER";
private static final int MOCK_INVOKERS_DEFAULT_PRIORITY = -100;
- public MockInvokersSelector() {
+ private volatile BitList<Invoker<T>> normalInvokers = BitList.emptyList();
+ private volatile BitList<Invoker<T>> mockedInvokers = BitList.emptyList();
+
+ public MockInvokersSelector(URL url) {
+ super(url);
this.setPriority(MOCK_INVOKERS_DEFAULT_PRIORITY);
}
@Override
- public <T> RouterResult<Invoker<T>> route(List<Invoker<T>> invokers, URL url,
- Invocation invocation, boolean needToPrintMessage) throws RpcException {
+ public StateRouterResult<Invoker<T>> route(BitList<Invoker<T>> invokers, URL url,
+ Invocation invocation, boolean needToPrintMessage) throws RpcException {
if (CollectionUtils.isEmpty(invokers)) {
- return new RouterResult<>(invokers);
+ return new StateRouterResult<>(invokers,
+ needToPrintMessage ? "Empty invokers. Directly return." : null);
}
if (invocation.getObjectAttachments() == null) {
- return new RouterResult<>(getNormalInvokers(invokers));
+ return new StateRouterResult<>(invokers.and(normalInvokers),
+ needToPrintMessage ? "ObjectAttachments from invocation are null. Return normal Invokers." : null);
} else {
String value = (String) invocation.getObjectAttachments().get(INVOCATION_NEED_MOCK);
if (value == null) {
- return new RouterResult<>(getNormalInvokers(invokers));
+ return new StateRouterResult<>(invokers.and(normalInvokers),
+ needToPrintMessage ? "invocation.need.mock not set. Return normal Invokers." : null);
} else if (Boolean.TRUE.toString().equalsIgnoreCase(value)) {
- return new RouterResult<>(getMockedInvokers(invokers));
+ return new StateRouterResult<>(invokers.and(mockedInvokers),
+ needToPrintMessage ? "invocation.need.mock is true. Return mocked Invokers." : null);
}
}
- return new RouterResult<>(invokers);
+ return new StateRouterResult<>(invokers,
+ needToPrintMessage ? "Directly Return. Reason: invocation.need.mock is set but not match true" : null);
}
- private <T> List<Invoker<T>> getMockedInvokers(final List<Invoker<T>> invokers) {
- if (!hasMockProviders(invokers)) {
- return null;
- }
- List<Invoker<T>> sInvokers = new ArrayList<Invoker<T>>(1);
- for (Invoker<T> invoker : invokers) {
- if (invoker.getUrl().getProtocol().equals(MOCK_PROTOCOL)) {
- sInvokers.add(invoker);
- }
- }
- return sInvokers;
+ @Override
+ public void notify(BitList<Invoker<T>> invokers) {
+ cacheMockedInvokers(invokers);
+ cacheNormalInvokers(invokers);
}
- private <T> List<Invoker<T>> getNormalInvokers(final List<Invoker<T>> invokers) {
- if (!hasMockProviders(invokers)) {
- return invokers;
- } else {
- List<Invoker<T>> sInvokers = new ArrayList<Invoker<T>>(invokers.size());
- for (Invoker<T> invoker : invokers) {
- if (!invoker.getUrl().getProtocol().equals(MOCK_PROTOCOL)) {
- sInvokers.add(invoker);
- }
- }
- return sInvokers;
- }
+ private void cacheMockedInvokers(BitList<Invoker<T>> invokers) {
+ BitList<Invoker<T>> clonedInvokers = invokers.clone();
+ clonedInvokers.removeIf((invoker) -> !invoker.getUrl().getProtocol().equals(MOCK_PROTOCOL));
+ mockedInvokers = clonedInvokers;
}
- private <T> boolean hasMockProviders(final List<Invoker<T>> invokers) {
- boolean hasMockProvider = false;
- for (Invoker<T> invoker : invokers) {
- if (invoker.getUrl().getProtocol().equals(MOCK_PROTOCOL)) {
- hasMockProvider = true;
- break;
- }
- }
- return hasMockProvider;
+ @SuppressWarnings("rawtypes")
+ private void cacheNormalInvokers(BitList<Invoker<T>> invokers) {
+ BitList<Invoker<T>> clonedInvokers = invokers.clone();
+ clonedInvokers.removeIf((invoker) -> invoker.getUrl().getProtocol().equals(MOCK_PROTOCOL));
+ normalInvokers = clonedInvokers;
}
}
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/MockStateRouterFactory.java
similarity index 76%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockRouterFactory.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.java
index d6f64df..8297700 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/MockStateRouterFactory.java
@@ -18,19 +18,19 @@ 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.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
/**
*
*/
@Activate
-public class MockRouterFactory implements RouterFactory {
+public class MockStateRouterFactory implements StateRouterFactory {
public static final String NAME = "mock";
@Override
- public Router getRouter(URL url) {
- return new MockInvokersSelector();
+ public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
+ return new MockInvokersSelector<T>(url);
}
}
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/ScriptStateRouter.java
similarity index 81%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.java
index aeecb22..ed4e413 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/ScriptStateRouter.java
@@ -24,8 +24,9 @@ import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
-import org.apache.dubbo.rpc.cluster.router.AbstractRouter;
-import org.apache.dubbo.rpc.cluster.router.RouterResult;
+import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
+import org.apache.dubbo.rpc.cluster.router.state.BitList;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouterResult;
import javax.script.Bindings;
import javax.script.Compilable;
@@ -57,10 +58,10 @@ import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY;
/**
* ScriptRouter
*/
-public class ScriptRouter extends AbstractRouter {
+public class ScriptStateRouter<T> extends AbstractStateRouter<T> {
public static final String NAME = "SCRIPT_ROUTER";
private static final int SCRIPT_ROUTER_DEFAULT_PRIORITY = 0;
- private static final Logger logger = LoggerFactory.getLogger(ScriptRouter.class);
+ private static final Logger logger = LoggerFactory.getLogger(ScriptStateRouter.class);
private static final Map<String, ScriptEngine> ENGINES = new ConcurrentHashMap<>();
@@ -81,7 +82,8 @@ public class ScriptRouter extends AbstractRouter {
accessControlContext = new AccessControlContext(new ProtectionDomain[]{domain});
}
- public ScriptRouter(URL url) {
+ public ScriptStateRouter(URL url) {
+ super(url);
this.setUrl(url);
this.setPriority(url.getParameter(PRIORITY_KEY, SCRIPT_ROUTER_DEFAULT_PRIORITY));
@@ -124,13 +126,14 @@ public class ScriptRouter extends AbstractRouter {
@Override
- public <T> RouterResult<Invoker<T>> route(List<Invoker<T>> invokers, URL url,
- Invocation invocation, boolean needToPrintMessage) throws RpcException {
+ public StateRouterResult<Invoker<T>> route(BitList<Invoker<T>> invokers, URL url,
+ Invocation invocation, boolean needToPrintMessage) throws RpcException {
if (engine == null || function == null) {
- return new RouterResult<>(invokers);
+ return new StateRouterResult<>(invokers,
+ needToPrintMessage ? "Directly Return. Reason: engine or function is null" : null);
}
Bindings bindings = createBindings(invokers, invocation);
- return new RouterResult<>(getRoutedInvokers(AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
+ return new StateRouterResult<>(getRoutedInvokers(invokers, AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
return function.eval(bindings);
} catch (ScriptException e) {
@@ -145,20 +148,22 @@ public class ScriptRouter extends AbstractRouter {
* get routed invokers from result of script rule evaluation
*/
@SuppressWarnings("unchecked")
- protected <T> List<Invoker<T>> getRoutedInvokers(Object obj) {
+ protected BitList<Invoker<T>> getRoutedInvokers(BitList<Invoker<T>> invokers, Object obj) {
+ BitList<Invoker<T>> result = invokers.clone();
if (obj instanceof Invoker[]) {
- return Arrays.asList((Invoker<T>[]) obj);
+ result.retainAll(Arrays.asList((Invoker<T>[]) obj));
} else if (obj instanceof Object[]) {
- return Arrays.stream((Object[]) obj).map(item -> (Invoker<T>) item).collect(Collectors.toList());
+ result.retainAll(Arrays.stream((Object[]) obj).map(item -> (Invoker<T>) item).collect(Collectors.toList()));
} else {
- return (List<Invoker<T>>) obj;
+ result.retainAll((List<Invoker<T>>) obj);
}
+ return result;
}
/**
* create bindings for script engine
*/
- private <T> Bindings createBindings(List<Invoker<T>> invokers, Invocation invocation) {
+ private Bindings createBindings(List<Invoker<T>> invokers, Invocation invocation) {
Bindings bindings = engine.createBindings();
// create a new List of invokers
bindings.put("invokers", new ArrayList<>(invokers));
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.java
similarity index 81%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterFactory.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.java
index 6621f05..43bcd30 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.java
@@ -17,8 +17,8 @@
package org.apache.dubbo.rpc.cluster.router.script;
import org.apache.dubbo.common.URL;
-import org.apache.dubbo.rpc.cluster.Router;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
/**
* ScriptRouterFactory
@@ -33,13 +33,13 @@ import org.apache.dubbo.rpc.cluster.RouterFactory;
* The host value in URL points out the address of the source content of the Script Router,Registry、File etc
*
*/
-public class ScriptRouterFactory implements RouterFactory {
+public class ScriptStateRouterFactory implements StateRouterFactory {
public static final String NAME = "script";
@Override
- public Router getRouter(URL url) {
- return new ScriptRouter(url);
+ public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
+ return new ScriptStateRouter<>(url);
}
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/AbstractStateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/AbstractStateRouter.java
index 686e598..9f6e4a8 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/AbstractStateRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/AbstractStateRouter.java
@@ -17,41 +17,26 @@
package org.apache.dubbo.rpc.cluster.router.state;
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.RouterChain;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicReference;
-
/***
* The abstract class of StateRoute.
* @since 3.0
*/
-public abstract class AbstractStateRouter implements StateRouter {
- final protected RouterChain chain;
- protected int priority = DEFAULT_PRIORITY;
- protected boolean force = false;
- protected URL url;
- protected List<Invoker> invokers;
- protected AtomicReference<AddrCache> cache;
- protected GovernanceRuleRepository ruleRepository;
+public abstract class AbstractStateRouter<T> implements StateRouter<T> {
+ private volatile int priority = DEFAULT_PRIORITY;
+ private volatile boolean force = false;
+ private volatile URL url;
+
+ private final GovernanceRuleRepository ruleRepository;
- public AbstractStateRouter(URL url, RouterChain chain) {
+ public AbstractStateRouter(URL url) {
this.ruleRepository = url.getOrDefaultModuleModel().getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension();
- this.chain = chain;
this.url = url;
}
@Override
- public <T> void notify(List<Invoker<T>> invokers) {
- this.invokers = (List)invokers;
- }
-
- @Override
public URL getUrl() {
return url;
}
@@ -83,40 +68,12 @@ public abstract class AbstractStateRouter implements StateRouter {
this.priority = priority;
}
- @Override
- public <T> StateRouterResult<Invoker<T>> route(BitList<Invoker<T>> invokers, RouterCache<T> cache, URL url,
- Invocation invocation, boolean needToPrintMessage) throws RpcException {
-
- List<String> tags = getTags(url, invocation);
-
- if (tags == null) {
- return new StateRouterResult<>(invokers);
- }
- for (String tag : tags) {
- BitList<Invoker<T>> tagInvokers = cache.getAddrPool().get(tag);
- if (tagMatchFail(tagInvokers)) {
- continue;
- }
- if (needToPrintMessage) {
- return new StateRouterResult<>(invokers.and(tagInvokers), "use tag " + tag + " to route");
- } else {
- return new StateRouterResult<>(invokers.and(tagInvokers));
- }
- }
-
- return new StateRouterResult<>(invokers);
- }
-
- protected List<String> getTags(URL url, Invocation invocation) {
- return new ArrayList<String>();
- }
-
- public <T> Boolean tagMatchFail(BitList<Invoker<T>> invokers) {
- return invokers == null || invokers.isEmpty();
+ public GovernanceRuleRepository getRuleRepository() {
+ return this.ruleRepository;
}
@Override
- public void pool() {
- chain.loop(false);
+ public void notify(BitList<Invoker<T>> invokers) {
+
}
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/AddrCache.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/AddrCache.java
deleted file mode 100644
index 5021d1a..0000000
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/AddrCache.java
+++ /dev/null
@@ -1,51 +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.state;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.dubbo.rpc.Invoker;
-
-/***
- * Address cache,
- * used to cache the results of the StaterRouter's asynchronous address list calculations.
- * @param <T>
- * @since 3.0
- */
-public class AddrCache<T> {
-
- private List<Invoker<T>> invokers;
- private Map<String, RouterCache<T>> cache = Collections.emptyMap();
-
- public List<Invoker<T>> getInvokers() {
- return invokers;
- }
-
- public void setInvokers(List<Invoker<T>> invokers) {
- this.invokers = invokers;
- }
-
- public Map<String, RouterCache<T>> getCache() {
- return cache;
- }
-
- public void setCache(Map<String, RouterCache<T>> cache) {
- this.cache = cache;
- }
-}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/CacheableStateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/CacheableStateRouterFactory.java
index 5f38ccb..422c77e 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/CacheableStateRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/CacheableStateRouterFactory.java
@@ -16,23 +16,23 @@
*/
package org.apache.dubbo.rpc.cluster.router.state;
+import org.apache.dubbo.common.URL;
+
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.rpc.cluster.RouterChain;
-
/**
* 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.
*/
public abstract class CacheableStateRouterFactory implements StateRouterFactory {
+ // TODO reuse StateRouter for all routerChain
private final ConcurrentMap<String, StateRouter> routerMap = new ConcurrentHashMap<>();
@Override
- public StateRouter getRouter(URL url, RouterChain chain) {
- return routerMap.computeIfAbsent(url.getServiceKey(), k -> createRouter(url, chain));
+ public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
+ return routerMap.computeIfAbsent(url.getServiceKey(), k -> createRouter(interfaceClass, url));
}
- protected abstract StateRouter createRouter(URL url, RouterChain chain);
+ protected abstract <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url);
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/RouterCache.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/RouterCache.java
deleted file mode 100644
index 82ccf58..0000000
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/RouterCache.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.dubbo.rpc.cluster.router.state;
-
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import org.apache.dubbo.rpc.Invoker;
-
-/***
- * Cache the address list for each Router.
- * @param <T>
- * @since 3.0
- */
-public class RouterCache<T> {
- private final static ConcurrentHashMap EMPTY_MAP = new ConcurrentHashMap<>();
- protected ConcurrentMap<String, BitList<Invoker<T>>> addrPool = EMPTY_MAP;
- protected Object addrMetadata;
-
- public ConcurrentMap<String, BitList<Invoker<T>>> getAddrPool() {
- return addrPool;
- }
-
- public void setAddrPool(ConcurrentHashMap<String, BitList<Invoker<T>>> addrPool) {
- this.addrPool = addrPool;
- }
-
- public Object getAddrMetadata() {
- return addrMetadata;
- }
-
- public void setAddrMetadata(Object addrMetadata) {
- this.addrMetadata = addrMetadata;
- }
-}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouter.java
index 10a1898..d84ac43 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouter.java
@@ -22,18 +22,16 @@ import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
-import java.util.List;
-
/**
* State Router. (SPI, Prototype, ThreadSafe)
* <p>
* <a href="http://en.wikipedia.org/wiki/Routing">Routing</a>
*
- * @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory)
+ * @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory, boolean)
* @see Directory#list(Invocation)
* @since 3.0
*/
-public interface StateRouter extends Comparable<StateRouter> {
+public interface StateRouter<T> extends Comparable<StateRouter<T>> {
int DEFAULT_PRIORITY = Integer.MAX_VALUE;
@@ -45,43 +43,18 @@ public interface StateRouter extends Comparable<StateRouter> {
URL getUrl();
/***
- * Filter invokers with current routing rule and only return the invokers that comply with the rule.
- * Caching address lists in BitMap mode improves routing performance.
- * @param invokers invoker bit list
- * @param cache router address cache
- * @param url refer url
- * @param invocation invocation
- * @param <T>
- * @return routed invokers
- * @throws RpcException
- * @Since 3.0
- */
- @Deprecated
- default <T> BitList<Invoker<T>> route(BitList<Invoker<T>> invokers, RouterCache<T> cache, URL url, Invocation invocation)
- throws RpcException {
- return null;
- }
-
- /***
* ** This method can return the state of whether routerChain needed to continue route. **
* Filter invokers with current routing rule and only return the invokers that comply with the rule.
* Caching address lists in BitMap mode improves routing performance.
* @param invokers invoker bit list
- * @param cache router address cache
* @param url refer url
* @param invocation invocation
* @param needToPrintMessage whether to print router state. Such as `use router branch a`.
* @return state with route result
* @since 3.0
*/
- default <T> StateRouterResult<Invoker<T>> route(BitList<Invoker<T>> invokers, RouterCache<T> cache, URL url, Invocation invocation,
- boolean needToPrintMessage) throws RpcException {
- return new StateRouterResult<>(route(invokers, cache, url, invocation));
- }
-
- default <T> void notify(List<Invoker<T>> invokers) {
-
- }
+ StateRouterResult<Invoker<T>> route(BitList<Invoker<T>> invokers, URL url, Invocation invocation,
+ boolean needToPrintMessage) throws RpcException;
/**
* To decide whether this router need to execute every time an RPC comes or should only execute when addresses or
@@ -91,12 +64,30 @@ public interface StateRouter extends Comparable<StateRouter> {
*/
boolean isRuntime();
- boolean isEnable();
-
+ /**
+ * To decide whether this router should take effect when none of the invoker can match the router rule, which
+ * means the {@link #route(BitList, URL, Invocation, boolean)} would be empty. Most of time, most router implementation would
+ * default this value to false.
+ *
+ * @return true to execute if none of invokers matches the current router
+ */
boolean isForce();
+ /**
+ * Router's priority, used to sort routers.
+ *
+ * @return router's priority
+ */
int getPriority();
+ /**
+ * Notify the router the invoker list. Invoker list may change from time to time. This method gives the router a
+ * chance to prepare before {@link StateRouter#route(BitList, URL, Invocation, boolean)} gets called.
+ *
+ * @param invokers invoker list
+ */
+ void notify(BitList<Invoker<T>> invokers);
+
@Override
default int compareTo(StateRouter o) {
if (o == null) {
@@ -105,14 +96,6 @@ public interface StateRouter extends Comparable<StateRouter> {
return Integer.compare(this.getPriority(), o.getPriority());
}
- String getName();
-
- boolean shouldRePool();
-
- <T> RouterCache<T> pool(List<Invoker<T>> invokers);
-
- void pool();
-
default void stop() {
//do nothing by default
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouterFactory.java
index 9780c36..7f61f36 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouterFactory.java
@@ -19,7 +19,6 @@ package org.apache.dubbo.rpc.cluster.router.state;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
-import org.apache.dubbo.rpc.cluster.RouterChain;
@SPI
public interface StateRouterFactory {
@@ -31,5 +30,5 @@ public interface StateRouterFactory {
* @since 3.0
*/
@Adaptive("protocol")
- <T> StateRouter getRouter(URL url, RouterChain<T> chain);
+ <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url);
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagDynamicStateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagDynamicStateRouter.java
deleted file mode 100644
index 5d4132e..0000000
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagDynamicStateRouter.java
+++ /dev/null
@@ -1,260 +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.tag;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
-import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
-import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
-import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
-import org.apache.dubbo.common.logger.Logger;
-import org.apache.dubbo.common.logger.LoggerFactory;
-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.rpc.Invocation;
-import org.apache.dubbo.rpc.Invoker;
-import org.apache.dubbo.rpc.RpcException;
-import org.apache.dubbo.rpc.cluster.RouterChain;
-import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
-import org.apache.dubbo.rpc.cluster.router.state.BitList;
-import org.apache.dubbo.rpc.cluster.router.state.RouterCache;
-import org.apache.dubbo.rpc.cluster.router.state.StateRouterResult;
-import org.apache.dubbo.rpc.cluster.router.tag.model.TagRouterRule;
-import org.apache.dubbo.rpc.cluster.router.tag.model.TagRuleParser;
-
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
-import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
-import static org.apache.dubbo.rpc.Constants.FORCE_USE_TAG;
-
-/**
- * TagDynamicStateRouter, "application.tag-router"
- */
-public class TagDynamicStateRouter extends AbstractStateRouter implements ConfigurationListener {
- public static final String NAME = "TAG_ROUTER";
- private static final int TAG_ROUTER_DEFAULT_PRIORITY = 100;
- private static final Logger logger = LoggerFactory.getLogger(TagDynamicStateRouter.class);
- private static final String RULE_SUFFIX = ".tag-router";
- private static final String NO_TAG = "noTag";
-
- private TagRouterRule tagRouterRule;
- private String application;
-
- public TagDynamicStateRouter(URL url, RouterChain chain) {
- super(url, chain);
- this.priority = TAG_ROUTER_DEFAULT_PRIORITY;
- }
-
- @Override
- public synchronized void process(ConfigChangedEvent event) {
- if (logger.isDebugEnabled()) {
- logger.debug("Notification of tag rule, change type is: " + event.getChangeType() + ", raw rule is:\n " +
- event.getContent());
- }
-
- try {
- if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
- this.tagRouterRule = null;
- } else {
- this.tagRouterRule = TagRuleParser.parse(event.getContent());
- }
- } 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);
- }
- }
-
- @Override
- public <T> StateRouterResult<Invoker<T>> route(BitList<Invoker<T>> invokers, RouterCache<T> cache, URL url,
- Invocation invocation, boolean needToPrintMessage) throws RpcException {
-
- final TagRouterRule tagRouterRuleCopy = (TagRouterRule) cache.getAddrMetadata();
-
- String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) ? url.getParameter(TAG_KEY) :
- invocation.getAttachment(TAG_KEY);
-
- ConcurrentMap<String, BitList<Invoker<T>>> addrPool = cache.getAddrPool();
-
- if (StringUtils.isEmpty(tag)) {
- return new StateRouterResult<>(invokers.and(addrPool.get(NO_TAG)));
- } else {
- BitList<Invoker<T>> result = addrPool.get(tag);
-
- if (CollectionUtils.isNotEmpty(result) || (tagRouterRuleCopy != null && tagRouterRuleCopy.isForce())
- || isForceUseTag(invocation)) {
- return new StateRouterResult<>(invokers.and(result));
- } else {
- invocation.setAttachment(TAG_KEY, NO_TAG);
- return new StateRouterResult<>(invokers);
- }
- }
- }
-
- private boolean isForceUseTag(Invocation invocation) {
- return Boolean.parseBoolean(invocation.getAttachment(FORCE_USE_TAG, url.getParameter(FORCE_USE_TAG, "false")));
- }
-
- @Override
- public boolean isRuntime() {
- return tagRouterRule != null && tagRouterRule.isRuntime();
- }
-
- @Override
- public boolean isEnable() {
- return tagRouterRule != null && tagRouterRule.isEnabled();
- }
-
- @Override
- public boolean isForce() {
- return tagRouterRule != null && tagRouterRule.isForce();
- }
-
- @Override
- public String getName() {
- return "TagDynamic";
- }
-
- @Override
- public boolean shouldRePool() {
- return false;
- }
-
- @Override
- public <T> RouterCache<T> pool(List<Invoker<T>> invokers) {
-
- RouterCache<T> routerCache = new RouterCache<>();
- ConcurrentHashMap<String, BitList<Invoker<T>>> addrPool = new ConcurrentHashMap<>();
-
- final TagRouterRule tagRouterRuleCopy = tagRouterRule;
-
-
- if (tagRouterRuleCopy == null || !tagRouterRuleCopy.isValid() || !tagRouterRuleCopy.isEnabled()) {
- BitList<Invoker<T>> noTagList = new BitList<>(invokers, false);
- addrPool.put(NO_TAG, noTagList);
- routerCache.setAddrPool(addrPool);
- return routerCache;
- }
-
- List<String> tagNames = tagRouterRuleCopy.getTagNames();
- Map<String, List<String>> tagnameToAddresses = tagRouterRuleCopy.getTagnameToAddresses();
-
- for (String tag : tagNames) {
- List<String> addresses = tagnameToAddresses.get(tag);
- BitList<Invoker<T>> list = new BitList<>(invokers, true);
-
- if (CollectionUtils.isEmpty(addresses)) {
- list.addAll(invokers);
- } else {
- for (int index = 0; index < invokers.size(); index++) {
- Invoker<T> invoker = invokers.get(index);
- if (addressMatches(invoker.getUrl(), addresses)) {
- list.addIndex(index);
- }
- }
- }
-
- addrPool.put(tag, list);
- }
-
- List<String> addresses = tagRouterRuleCopy.getAddresses();
- BitList<Invoker<T>> noTagList = new BitList<>(invokers, true);
-
- for (int index = 0; index < invokers.size(); index++) {
- Invoker<T> invoker = invokers.get(index);
- if (addressNotMatches(invoker.getUrl(), addresses)) {
- noTagList.addIndex(index);
- }
- }
- addrPool.put(NO_TAG, noTagList);
- routerCache.setAddrPool(addrPool);
- routerCache.setAddrMetadata(tagRouterRuleCopy);
-
- return routerCache;
- }
-
- private boolean addressMatches(URL url, List<String> addresses) {
- return addresses != null && checkAddressMatch(addresses, url.getHost(), url.getPort());
- }
-
- private boolean addressNotMatches(URL url, List<String> addresses) {
- return addresses == null || !checkAddressMatch(addresses, url.getHost(), url.getPort());
- }
-
- private boolean checkAddressMatch(List<String> addresses, String host, int port) {
- for (String address : addresses) {
- try {
- if (NetUtils.matchIpExpression(address, host, port)) {
- return true;
- }
- if ((ANYHOST_VALUE + ":" + port).equals(address)) {
- return true;
- }
- } catch (Exception e) {
- logger.error("The format of ip address is invalid in tag route. Address :" + address, e);
- }
- }
- return false;
- }
-
- public void setApplication(String app) {
- this.application = app;
- }
-
- @Override
- public <T> void notify(List<Invoker<T>> invokers) {
- if (CollectionUtils.isEmpty(invokers)) {
- return;
- }
-
- Invoker<T> invoker = invokers.get(0);
- URL url = invoker.getUrl();
- String providerApplication = url.getRemoteApplication();
-
- if (StringUtils.isEmpty(providerApplication)) {
- logger.error("TagRouter must getConfig from or subscribe to a specific application, but the application " +
- "in this TagRouter is not specified.");
- return;
- }
-
- synchronized (this) {
- if (!providerApplication.equals(application)) {
- if (StringUtils.isNotEmpty(application)) {
- ruleRepository.removeListener(application + RULE_SUFFIX, this);
- }
- String key = providerApplication + RULE_SUFFIX;
- ruleRepository.addListener(key, this);
- application = providerApplication;
- String rawRule = ruleRepository.getRule(key, DynamicConfiguration.DEFAULT_GROUP);
- if (StringUtils.isNotEmpty(rawRule)) {
- this.process(new ConfigChangedEvent(key, DynamicConfiguration.DEFAULT_GROUP, rawRule));
- }
- }
- }
- }
-
- @Override
- public void stop() {
- if (StringUtils.isNotEmpty(application)) {
- ruleRepository.removeListener(application + RULE_SUFFIX, this);
- }
- }
-}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagDynamicStateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagDynamicStateRouterFactory.java
deleted file mode 100644
index cdcdb84..0000000
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagDynamicStateRouterFactory.java
+++ /dev/null
@@ -1,37 +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.tag;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.extension.Activate;
-import org.apache.dubbo.rpc.cluster.RouterChain;
-import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
-import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
-
-/**
- * Tag router factory
- */
-@Activate(order = 99)
-public class TagDynamicStateRouterFactory extends CacheableStateRouterFactory {
-
- public static final String NAME = "tag-dynamic";
-
- @Override
- protected StateRouter createRouter(URL url, RouterChain chain) {
- return new TagDynamicStateRouter(url, chain);
- }
-}
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
deleted file mode 100644
index 3c9a60e..0000000
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java
+++ /dev/null
@@ -1,36 +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.tag;
-
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.extension.Activate;
-import org.apache.dubbo.rpc.cluster.CacheableRouterFactory;
-import org.apache.dubbo.rpc.cluster.Router;
-
-/**
- * Tag router factory
- */
-@Activate(order = 100)
-public class TagRouterFactory extends CacheableRouterFactory {
-
- public static final String NAME = "tag";
-
- @Override
- protected Router createRouter(URL url) {
- return new TagRouter(url);
- }
-}
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/TagStateRouter.java
similarity index 80%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouter.java
index 08c0ef5..3655955 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/TagStateRouter.java
@@ -29,14 +29,14 @@ import org.apache.dubbo.common.utils.StringUtils;
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.AbstractRouter;
-import org.apache.dubbo.rpc.cluster.router.RouterResult;
+import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
+import org.apache.dubbo.rpc.cluster.router.state.BitList;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouterResult;
import org.apache.dubbo.rpc.cluster.router.tag.model.TagRouterRule;
import org.apache.dubbo.rpc.cluster.router.tag.model.TagRuleParser;
import java.util.List;
import java.util.function.Predicate;
-import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
@@ -45,16 +45,16 @@ import static org.apache.dubbo.rpc.Constants.FORCE_USE_TAG;
/**
* TagRouter, "application.tag-router"
*/
-public class TagRouter extends AbstractRouter implements ConfigurationListener {
+public class TagStateRouter<T> extends AbstractStateRouter<T> implements ConfigurationListener {
public static final String NAME = "TAG_ROUTER";
private static final int TAG_ROUTER_DEFAULT_PRIORITY = 100;
- private static final Logger logger = LoggerFactory.getLogger(TagRouter.class);
+ private static final Logger logger = LoggerFactory.getLogger(TagStateRouter.class);
private static final String RULE_SUFFIX = ".tag-router";
private TagRouterRule tagRouterRule;
private String application;
- public TagRouter(URL url) {
+ public TagStateRouter(URL url) {
super(url);
this.setPriority(TAG_ROUTER_DEFAULT_PRIORITY);
}
@@ -79,20 +79,21 @@ public class TagRouter extends AbstractRouter implements ConfigurationListener {
}
@Override
- public <T> RouterResult<Invoker<T>> route(List<Invoker<T>> invokers, URL url,
- Invocation invocation, boolean needToPrintMessage) throws RpcException {
-
+ public StateRouterResult<Invoker<T>> route(BitList<Invoker<T>> invokers, URL url,
+ Invocation invocation, boolean needToPrintMessage) throws RpcException {
if (CollectionUtils.isEmpty(invokers)) {
- return new RouterResult<>(invokers);
+ return new StateRouterResult<>(invokers,
+ needToPrintMessage ? "Directly Return. Reason: Invokers from previous router is empty." : null);
}
// since the rule can be changed by config center, we should copy one to use.
final TagRouterRule tagRouterRuleCopy = tagRouterRule;
if (tagRouterRuleCopy == null || !tagRouterRuleCopy.isValid() || !tagRouterRuleCopy.isEnabled()) {
- return new RouterResult<>(filterUsingStaticTag(invokers, url, invocation));
+ return new StateRouterResult<>(filterUsingStaticTag(invokers, url, invocation),
+ needToPrintMessage ? "Disable Tag Router. Reason: tagRouterRule is invalid or disabled" : null);
}
- List<Invoker<T>> result = invokers;
+ BitList<Invoker<T>> result = invokers;
String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) ? url.getParameter(TAG_KEY) :
invocation.getAttachment(TAG_KEY);
@@ -104,7 +105,8 @@ public class TagRouter extends AbstractRouter implements ConfigurationListener {
result = filterInvoker(invokers, invoker -> addressMatches(invoker.getUrl(), addresses));
// if result is not null OR it's null but force=true, return result directly
if (CollectionUtils.isNotEmpty(result) || tagRouterRuleCopy.isForce()) {
- return new RouterResult<>(result);
+ return new StateRouterResult<>(result,
+ needToPrintMessage ? "Use tag " + tag + " to route. Reason: result is not null OR it's null but force=true" : null);
}
} else {
// dynamic tag group doesn't have any item about the requested app OR it's null after filtered by
@@ -114,13 +116,15 @@ public class TagRouter extends AbstractRouter implements ConfigurationListener {
// 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) || isForceUseTag(invocation)) {
- return new RouterResult<>(result);
+ return new StateRouterResult<>(result,
+ needToPrintMessage ? "Use tag " + tag + " to route. Reason: result is not empty or ForceUseTag key is true in invocation" : null);
}
// FAILOVER: return all Providers without any tags.
else {
- List<Invoker<T>> tmp = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(),
+ BitList<Invoker<T>> tmp = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(),
tagRouterRuleCopy.getAddresses()));
- return new RouterResult<>(filterInvoker(tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY))));
+ return new StateRouterResult<>(filterInvoker(tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY))),
+ needToPrintMessage ? "FAILOVER: return all Providers without any tags" : null);
}
} else {
// List<String> addresses = tagRouterRule.filter(providerApp);
@@ -130,15 +134,16 @@ public class TagRouter extends AbstractRouter implements ConfigurationListener {
result = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(), addresses));
// 1. all addresses are in dynamic tag group, return empty list.
if (CollectionUtils.isEmpty(result)) {
- return new RouterResult<>(result);
+ return new StateRouterResult<>(result,
+ needToPrintMessage ? "all addresses are in dynamic tag group, return empty list" : null);
}
// 2. if there are some addresses that are not in any dynamic tag group, continue to filter using the
// static tag group.
}
- return new RouterResult<>(filterInvoker(result, invoker -> {
+ return new StateRouterResult<>(filterInvoker(result, invoker -> {
String localTag = invoker.getUrl().getParameter(TAG_KEY);
return StringUtils.isEmpty(localTag) || !tagRouterRuleCopy.getTagNames().contains(localTag);
- }));
+ }), needToPrintMessage ? "filter using the static tag group" : null);
}
}
@@ -156,8 +161,8 @@ public class TagRouter extends AbstractRouter implements ConfigurationListener {
* @param <T>
* @return
*/
- private <T> List<Invoker<T>> filterUsingStaticTag(List<Invoker<T>> invokers, URL url, Invocation invocation) {
- List<Invoker<T>> result;
+ private <T> BitList<Invoker<T>> filterUsingStaticTag(BitList<Invoker<T>> invokers, URL url, Invocation invocation) {
+ BitList<Invoker<T>> result;
// Dynamic param
String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) ? url.getParameter(TAG_KEY) :
invocation.getAttachment(TAG_KEY);
@@ -188,14 +193,15 @@ public class TagRouter extends AbstractRouter implements ConfigurationListener {
return Boolean.parseBoolean(invocation.getAttachment(FORCE_USE_TAG, this.getUrl().getParameter(FORCE_USE_TAG, "false")));
}
- private <T> List<Invoker<T>> filterInvoker(List<Invoker<T>> invokers, Predicate<Invoker<T>> predicate) {
+ private <T> BitList<Invoker<T>> filterInvoker(BitList<Invoker<T>> invokers, Predicate<Invoker<T>> predicate) {
if (invokers.stream().allMatch(predicate)) {
return invokers;
}
- return invokers.stream()
- .filter(predicate)
- .collect(Collectors.toList());
+ BitList<Invoker<T>> newInvokers = invokers.clone();
+ newInvokers.removeIf(invoker -> !predicate.test(invoker));
+
+ return newInvokers;
}
private boolean addressMatches(URL url, List<String> addresses) {
@@ -227,7 +233,7 @@ public class TagRouter extends AbstractRouter implements ConfigurationListener {
}
@Override
- public <T> void notify(List<Invoker<T>> invokers) {
+ public void notify(BitList<Invoker<T>> invokers) {
if (CollectionUtils.isEmpty(invokers)) {
return;
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStaticStateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterFactory.java
similarity index 79%
rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStaticStateRouterFactory.java
rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterFactory.java
index 21fe348..b05e09e 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStaticStateRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterFactory.java
@@ -18,7 +18,6 @@ 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.rpc.cluster.RouterChain;
import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
@@ -26,12 +25,12 @@ import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
* Tag router factory
*/
@Activate(order = 100)
-public class TagStaticStateRouterFactory extends CacheableStateRouterFactory {
+public class TagStateRouterFactory extends CacheableStateRouterFactory {
- public static final String NAME = "tag-static";
+ public static final String NAME = "tag";
@Override
- protected StateRouter createRouter(URL url, RouterChain chain) {
- return new TagStaticStateRouter(url, chain);
+ protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
+ return new TagStateRouter<T>(url);
}
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStaticStateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStaticStateRouter.java
deleted file mode 100644
index 5e0998c..0000000
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStaticStateRouter.java
+++ /dev/null
@@ -1,144 +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.tag;
-
-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 org.apache.dubbo.rpc.RpcException;
-import org.apache.dubbo.rpc.cluster.RouterChain;
-import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
-import org.apache.dubbo.rpc.cluster.router.state.BitList;
-import org.apache.dubbo.rpc.cluster.router.state.RouterCache;
-import org.apache.dubbo.rpc.cluster.router.state.StateRouterResult;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
-
-/**
- * TagStaticStateRouter, "application.tag-router"
- */
-public class TagStaticStateRouter extends AbstractStateRouter {
- public static final String NAME = "TAG_ROUTER";
- private static final int TAG_ROUTER_DEFAULT_PRIORITY = 100;
- private static final String NO_TAG = "noTag";
-
- public TagStaticStateRouter(URL url, RouterChain chain) {
- super(url, chain);
- this.priority = TAG_ROUTER_DEFAULT_PRIORITY;
- }
-
- @Override
- public URL getUrl() {
- return url;
- }
-
-
- @Override
- public <T> StateRouterResult<Invoker<T>> route(BitList<Invoker<T>> invokers, RouterCache<T> routerCache, URL url,
- Invocation invocation, boolean needToPrintMessage) throws RpcException {
-
- String tag = isNoTag(invocation.getAttachment(TAG_KEY)) ? url.getParameter(TAG_KEY) :
- invocation.getAttachment(TAG_KEY);
- if (StringUtils.isEmpty(tag)) {
- tag = NO_TAG;
- }
-
- ConcurrentMap<String, BitList<Invoker<T>>> pool = routerCache.getAddrPool();
- BitList<Invoker<T>> res = pool.get(tag);
- if (res == null) {
- return new StateRouterResult<>(invokers);
- }
- return new StateRouterResult<>(invokers.and(res));
- }
-
- private boolean isNoTag(String tag) {
- return StringUtils.isEmpty(tag) || NO_TAG.equals(tag);
- }
-
- @Override
- protected List<String> getTags(URL url, Invocation invocation) {
- List<String> tags = new ArrayList<>();
- String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) ? url.getParameter(TAG_KEY) :
- invocation.getAttachment(TAG_KEY);
- if (StringUtils.isEmpty(tag)) {
- tag = NO_TAG;
- }
- tags.add(tag);
- return tags;
- }
-
-
- @Override
- public boolean isEnable() {
- return true;
- }
-
- @Override
- public boolean isForce() {
- // FIXME
- return false;
- }
-
- @Override
- public String getName() {
- return "TagStatic";
- }
-
- @Override
- public boolean shouldRePool() {
- return false;
- }
-
- @Override
- public <T> RouterCache<T> pool(List<Invoker<T>> invokers) {
-
- RouterCache<T> routerCache = new RouterCache<>();
- ConcurrentHashMap<String, BitList<Invoker<T>>> addrPool = new ConcurrentHashMap<>();
-
- for (int index = 0; index < invokers.size(); index++) {
- Invoker<T> invoker = invokers.get(index);
- String tag = invoker.getUrl().getParameter(TAG_KEY);
- if (StringUtils.isEmpty(tag)) {
- BitList<Invoker<T>> noTagList = addrPool.computeIfAbsent(NO_TAG, k -> new BitList<>(invokers, true));
- noTagList.addIndex(index);
- } else {
- BitList<Invoker<T>> list = addrPool.computeIfAbsent(tag, k -> new BitList<>(invokers, true));
- list.addIndex(index);
- }
- }
-
- routerCache.setAddrPool(addrPool);
-
- return routerCache;
- }
-
-
- @Override
- public <T> void notify(List<Invoker<T>> invokers) {
- if (CollectionUtils.isEmpty(invokers)) {
- return;
- }
- }
-
-}
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 e229f2a..3fac72f 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,7 +1 @@
-file=org.apache.dubbo.rpc.cluster.router.file.FileRouterFactory
-condition=org.apache.dubbo.rpc.cluster.router.condition.ConditionRouterFactory
-service=org.apache.dubbo.rpc.cluster.router.condition.config.ServiceRouterFactory
-app=org.apache.dubbo.rpc.cluster.router.condition.config.AppRouterFactory
-tag=org.apache.dubbo.rpc.cluster.router.tag.TagRouterFactory
-mock=org.apache.dubbo.rpc.cluster.router.mock.MockRouterFactory
mesh-rule=org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleRouterFactory
diff --git a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory
index c69b3ab..f9489a8 100644
--- a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory
+++ b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory
@@ -1,2 +1,6 @@
-tag-dynamic=org.apache.dubbo.rpc.cluster.router.tag.TagDynamicStateRouterFactory
-tag-static=org.apache.dubbo.rpc.cluster.router.tag.TagStaticStateRouterFactory
\ No newline at end of file
+tag=org.apache.dubbo.rpc.cluster.router.tag.TagStateRouterFactory
+condition=org.apache.dubbo.rpc.cluster.router.condition.ConditionStateRouterFactory
+service=org.apache.dubbo.rpc.cluster.router.condition.config.ServiceStateRouterFactory
+app=org.apache.dubbo.rpc.cluster.router.condition.config.AppStateRouterFactory
+file=org.apache.dubbo.rpc.cluster.router.file.FileStateRouterFactory
+mock=org.apache.dubbo.rpc.cluster.router.mock.MockStateRouterFactory
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/RouterChainTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/RouterChainTest.java
index 4d431b6..633d7d3 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/RouterChainTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/RouterChainTest.java
@@ -20,6 +20,7 @@ package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.rpc.cluster.filter.DemoService;
+
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -45,8 +46,8 @@ public class RouterChainTest {
DemoService.class.getName(),
parameters);
- RouterChain<DemoService> routerChain = RouterChain.buildChain(url);
- Assertions.assertEquals(5, routerChain.getRouters().size());
- Assertions.assertEquals(2, routerChain.getStateRouters().size());
+ RouterChain<DemoService> routerChain = RouterChain.buildChain(DemoService.class, url);
+ Assertions.assertEquals(1, routerChain.getRouters().size());
+ Assertions.assertEquals(4, routerChain.getStateRouters().size());
}
}
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java
index 69022af..e4a8f1a 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java
@@ -20,9 +20,10 @@ import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
-import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
-import org.apache.dubbo.rpc.cluster.router.condition.ConditionRouterFactory;
+import org.apache.dubbo.rpc.cluster.router.condition.ConditionStateRouterFactory;
+import org.apache.dubbo.rpc.cluster.router.state.BitList;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -44,16 +45,19 @@ public class StaticDirectoryTest {
@Test
public void testStaticDirectory() {
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl(" => " + " host = " + NetUtils.getLocalHost()));
- List<Router> routers = new ArrayList<Router>();
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(" => " + " host = " + NetUtils.getLocalHost()));
+ List<StateRouter> routers = new ArrayList<StateRouter>();
routers.add(router);
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"));
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
+
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation(), false).getResult();
StaticDirectory<String> staticDirectory = new StaticDirectory<>(filteredInvokers);
boolean isAvailable = staticDirectory.isAvailable();
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java
index ea1d782..606437b 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java
@@ -51,7 +51,7 @@ public class ConsistentHashLoadBalanceTest extends LoadBalanceBaseTest {
void testNormalWhenRouterEnabled() {
ConsistentHashLoadBalance lb = (ConsistentHashLoadBalance) getLoadBalance(ConsistentHashLoadBalance.NAME);
URL url = invokers.get(0).getUrl();
- RouterChain<LoadBalanceBaseTest> routerChain = RouterChain.buildChain(url);
+ RouterChain<LoadBalanceBaseTest> routerChain = RouterChain.buildChain(LoadBalanceBaseTest.class, url);
Invoker<LoadBalanceBaseTest> result = lb.select(invokers, url, invocation);
int originalHashCode = lb.getCorrespondingHashCode(invokers);
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java
index 5d84f60..3674b69 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java
@@ -21,8 +21,9 @@ import org.apache.dubbo.common.URL;
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;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
+import org.apache.dubbo.rpc.cluster.router.state.BitList;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
@@ -55,67 +56,68 @@ public class ConditionRouterTest {
public void testRoute_matchWhen() {
Invocation invocation = new RpcInvocation();
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl(" => host = 1.2.3.4"));
- boolean matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(" => host = 1.2.3.4"));
+ boolean matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
- router = new ConditionRouterFactory().getRouter(getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
- matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
+ router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
+ matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
- router = new ConditionRouterFactory().getRouter(getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4"));
- matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
+ router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4"));
+ matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertFalse(matchWhen);
- router = new ConditionRouterFactory().getRouter(getRouteUrl("host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
- matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
+ router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
+ matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
- router = new ConditionRouterFactory().getRouter(getRouteUrl("host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
- matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
+ router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
+ matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
- router = new ConditionRouterFactory().getRouter(getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4"));
- matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
+ router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4"));
+ matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertFalse(matchWhen);
- router = new ConditionRouterFactory().getRouter(getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4"));
- matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
+ router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4"));
+ matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
}
@Test
public void testRoute_matchFilter() {
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf(
"dubbo://10.20.3.3:20880/com.foo.BarService?serialization=fastjson"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST
+ ":20880/com.foo.BarService"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST
+ ":20880/com.foo.BarService"));
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
System.err.println("The localhost address: " + invoker2.getUrl().getAddress());
System.err.println(invoker3.getUrl().getAddress());
- Router router1 = new ConditionRouterFactory().getRouter(getRouteUrl(
+ StateRouter router1 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(
"host = " + LOCAL_HOST + " => " + " host = 10.20.3.3").addParameter(FORCE_KEY,
String.valueOf(true)));
- Router router2 = new ConditionRouterFactory().getRouter(getRouteUrl(
+ StateRouter router2 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(
"host = " + LOCAL_HOST + " => " + " host = 10.20.3.* & host != 10.20.3.3").addParameter(
FORCE_KEY, String.valueOf(true)));
- Router router3 = new ConditionRouterFactory().getRouter(getRouteUrl(
+ StateRouter router3 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(
"host = " + LOCAL_HOST + " => " + " host = 10.20.3.3 & host != 10.20.3.3").addParameter(
FORCE_KEY, String.valueOf(true)));
- Router router4 = new ConditionRouterFactory().getRouter(getRouteUrl(
+ StateRouter router4 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(
"host = " + LOCAL_HOST + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4").addParameter(
FORCE_KEY, String.valueOf(true)));
- Router router5 = new ConditionRouterFactory().getRouter(getRouteUrl(
+ StateRouter router5 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(
"host = " + LOCAL_HOST + " => " + " host != 10.20.3.3").addParameter(FORCE_KEY,
String.valueOf(true)));
- Router router6 = new ConditionRouterFactory().getRouter(getRouteUrl(
+ StateRouter router6 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(
"host = " + LOCAL_HOST + " => " + " serialization = fastjson").addParameter(
FORCE_KEY, String.valueOf(true)));
@@ -139,45 +141,46 @@ public class ConditionRouterTest {
public void testRoute_methodRoute() {
Invocation invocation = new RpcInvocation("getFoo", "com.foo.BarService", "", new Class<?>[0], new Object[0]);
// More than one methods, mismatch
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl("methods=getFoo => host = 1.2.3.4"));
- boolean matchWhen = ((ConditionRouter) router).matchWhen(
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("methods=getFoo => host = 1.2.3.4"));
+ boolean matchWhen = ((ConditionStateRouter) router).matchWhen(
URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo"), invocation);
Assertions.assertTrue(matchWhen);
// Exactly one method, match
- matchWhen = ((ConditionRouter) router).matchWhen(
+ matchWhen = ((ConditionStateRouter) router).matchWhen(
URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation);
Assertions.assertTrue(matchWhen);
// Method routing and Other condition routing can work together
- Router router2 = new ConditionRouterFactory()
- .getRouter(getRouteUrl("methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4"));
- matchWhen = ((ConditionRouter) router2).matchWhen(
+ StateRouter router2 = new ConditionStateRouterFactory()
+ .getRouter(String.class, getRouteUrl("methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4"));
+ matchWhen = ((ConditionStateRouter) router2).matchWhen(
URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation);
Assertions.assertFalse(matchWhen);
- Router router3 = new ConditionRouterFactory()
- .getRouter(getRouteUrl("methods=getFoo & host=1.1.1.1 => host = 1.2.3.4"));
- matchWhen = ((ConditionRouter) router3).matchWhen(
+ StateRouter router3 = new ConditionStateRouterFactory()
+ .getRouter(String.class, getRouteUrl("methods=getFoo & host=1.1.1.1 => host = 1.2.3.4"));
+ matchWhen = ((ConditionStateRouter) router3).matchWhen(
URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation);
Assertions.assertTrue(matchWhen);
// Test filter condition
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST
+ ":20880/com.foo.BarService"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST
+ ":20880/com.foo.BarService"));
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
- Router router4 = new ConditionRouterFactory().getRouter(getRouteUrl(
+ StateRouter router4 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(
"host = " + LOCAL_HOST + " & methods = getFoo => " + " host = 10.20.3.3").addParameter(
FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> filteredInvokers1 = router4.route(invokers,
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false).getResult();
Assertions.assertEquals(1, filteredInvokers1.size());
- Router router5 = new ConditionRouterFactory().getRouter(getRouteUrl(
+ StateRouter router5 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(
"host = " + LOCAL_HOST + " & methods = unvalidmethod => " + " host = 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> filteredInvokers2 = router5.route(invokers,
@@ -188,47 +191,55 @@ public class ConditionRouterTest {
@Test
public void testRoute_ReturnFalse() {
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => false"));
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
- invokers.add(new MockInvoker<String>());
- invokers.add(new MockInvoker<String>());
- invokers.add(new MockInvoker<String>());
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => false"));
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
+ originInvokers.add(new MockInvoker<String>());
+ originInvokers.add(new MockInvoker<String>());
+ originInvokers.add(new MockInvoker<String>());
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false).getResult();
Assertions.assertEquals(0, filteredInvokers.size());
}
@Test
public void testRoute_ReturnEmpty() {
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => "));
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
- invokers.add(new MockInvoker<String>());
- invokers.add(new MockInvoker<String>());
- invokers.add(new MockInvoker<String>());
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => "));
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
+ originInvokers.add(new MockInvoker<String>());
+ originInvokers.add(new MockInvoker<String>());
+ originInvokers.add(new MockInvoker<String>());
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false).getResult();
Assertions.assertEquals(0, filteredInvokers.size());
}
@Test
public void testRoute_ReturnAll() {
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST));
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
- invokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")));
- invokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")));
- invokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")));
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST));
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
+ originInvokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")));
+ originInvokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")));
+ originInvokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")));
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false).getResult();
Assertions.assertEquals(invokers, filteredInvokers);
}
@Test
public void testRoute_HostFilter() {
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST));
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST));
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false).getResult();
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
@@ -237,14 +248,16 @@ public class ConditionRouterTest {
@Test
public void testRoute_Empty_HostFilter() {
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl(" => " + " host = " + LOCAL_HOST));
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(" => " + " host = " + LOCAL_HOST));
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false).getResult();
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
@@ -253,14 +266,16 @@ public class ConditionRouterTest {
@Test
public void testRoute_False_HostFilter() {
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl("true => " + " host = " + LOCAL_HOST));
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("true => " + " host = " + LOCAL_HOST));
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false).getResult();
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
@@ -269,14 +284,16 @@ public class ConditionRouterTest {
@Test
public void testRoute_Placeholder() {
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => " + " host = $host"));
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = $host"));
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false).getResult();
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
@@ -285,42 +302,48 @@ public class ConditionRouterTest {
@Test
public void testRoute_NoForce() {
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4"));
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4"));
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false).getResult();
Assertions.assertEquals(invokers, filteredInvokers);
}
@Test
public void testRoute_Force() {
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true)));
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true)));
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false).getResult();
Assertions.assertEquals(0, filteredInvokers.size());
}
@Test
public void testRoute_Arguments() {
- Router router = new ConditionRouterFactory().getRouter(getRouteUrl("arguments[0] = a " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true)));
- List<Invoker<String>> invokers = new ArrayList<>();
+ StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("arguments[0] = a " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true)));
+ List<Invoker<String>> originInvokers = new ArrayList<>();
Invoker<String> invoker1 = new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 = new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 = new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
RpcInvocation invocation = new RpcInvocation();
String p = "a";
invocation.setArguments(new Object[]{null});
@@ -331,17 +354,17 @@ public class ConditionRouterTest {
fileredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false).getResult();
Assertions.assertEquals(0, fileredInvokers.size());
- router = new ConditionRouterFactory().getRouter(getRouteUrl("arguments = b " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true)));
+ router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("arguments = b " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true)));
fileredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false).getResult();
Assertions.assertEquals(3, fileredInvokers.size());
- router = new ConditionRouterFactory().getRouter(getRouteUrl("arguments[10].inner = a " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true)));
+ router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("arguments[10].inner = a " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true)));
fileredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false).getResult();
Assertions.assertEquals(3, fileredInvokers.size());
int integer = 1;
invocation.setArguments(new Object[]{integer});
- router = new ConditionRouterFactory().getRouter(getRouteUrl("arguments[0].inner = 1 " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true)));
+ router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("arguments[0].inner = 1 " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true)));
fileredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false).getResult();
Assertions.assertEquals(0, fileredInvokers.size());
}
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 9eff618..eb4419c 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
@@ -27,8 +27,8 @@ import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
import org.junit.jupiter.api.AfterEach;
@@ -39,7 +39,7 @@ import org.junit.jupiter.api.Test;
import javax.script.ScriptEngineManager;
import java.util.ArrayList;
-import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_CONNECTIVITY_VALIDATION;
@@ -56,7 +56,7 @@ public class FileRouterEngineTest {
Invocation invocation;
StaticDirectory<FileRouterEngineTest> dic;
Result result = new AppResponse();
- private RouterFactory routerFactory = ExtensionLoader.getExtensionLoader(RouterFactory.class).getAdaptiveExtension();
+ private StateRouterFactory routerFactory = ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getAdaptiveExtension();
@BeforeAll
public static void setUpBeforeClass() throws Exception {
@@ -173,7 +173,7 @@ public class FileRouterEngineTest {
URL dicInitUrl = URL.valueOf("consumer://localhost:20880/org.apache.dubbo.rpc.cluster.router.file.FileRouterEngineTest?application=FileRouterEngineTest");
dic = new StaticDirectory<>(dicInitUrl, invokers);
dic.buildRouterChain();
- dic.getRouterChain().initWithRouters(Arrays.asList(routerFactory.getRouter(url)));
+ dic.getRouterChain().initWithStateRouters(Collections.singletonList(routerFactory.getRouter(FileRouterEngineTest.class, url)));
}
static class MockClusterInvoker<T> extends AbstractClusterInvoker<T> {
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java
index 3cd8e69..7cf5ecf 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java
@@ -19,6 +19,7 @@ package org.apache.dubbo.rpc.cluster.router.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
+import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -35,7 +36,7 @@ public class MockInvokersSelectorTest {
@Test
public void test() {
- MockInvokersSelector selector = new MockInvokersSelector();
+ MockInvokersSelector selector = new MockInvokersSelector(URL.valueOf(""));
// Data preparation
Invoker<DemoService> invoker1 = Mockito.mock(Invoker.class);
@@ -44,12 +45,13 @@ public class MockInvokersSelectorTest {
Mockito.when(invoker1.getUrl()).thenReturn(URL.valueOf("mock://127.0.0.1/test"));
Mockito.when(invoker2.getUrl()).thenReturn(URL.valueOf("mock://127.0.0.1/test"));
Mockito.when(invoker3.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1/test"));
- List<Invoker<DemoService>> providers = Arrays.asList(invoker1, invoker2, invoker3);
+ BitList<Invoker<DemoService>> providers = new BitList<>(Arrays.asList(invoker1, invoker2, invoker3));
RpcInvocation rpcInvocation = Mockito.mock(RpcInvocation.class);
URL consumerURL = URL.valueOf("test://127.0.0.1");
+ selector.notify(providers);
// rpcInvocation does not have an attached "invocation.need.mock" parameter, so normal invokers will be filtered out
List<Invoker<DemoService>> invokers = selector.route(providers, consumerURL, rpcInvocation, false).getResult();
Assertions.assertEquals(invokers.size(),1);
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.java
similarity index 73%
rename from dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java
rename to dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.java
index 91819e8..ba4a302 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.java
@@ -20,8 +20,9 @@ package org.apache.dubbo.rpc.cluster.router.script;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
-import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
+import org.apache.dubbo.rpc.cluster.router.state.BitList;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
@@ -33,7 +34,7 @@ import java.util.List;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
-public class ScriptRouterTest {
+public class ScriptStateRouterTest {
private URL SCRIPT_URL = URL.valueOf("script://javascript?type=javascript");
@@ -51,11 +52,13 @@ public class ScriptRouterTest {
@Test
public void testRouteReturnAll() {
- Router router = new ScriptRouterFactory().getRouter(getRouteUrl("function route(op1,op2){return op1} route(invokers)"));
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
- invokers.add(new MockInvoker<String>());
- invokers.add(new MockInvoker<String>());
- invokers.add(new MockInvoker<String>());
+ StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl("function route(op1,op2){return op1} route(invokers)"));
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
+ originInvokers.add(new MockInvoker<String>());
+ originInvokers.add(new MockInvoker<String>());
+ originInvokers.add(new MockInvoker<String>());
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
List<Invoker<String>> filteredInvokers = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation(), false).getResult();
Assertions.assertEquals(invokers, filteredInvokers);
}
@@ -70,15 +73,17 @@ public class ScriptRouterTest {
"} ; " +
"return result;";
String script = "function route(invokers,invocation,context){" + rule + "} route(invokers,invocation,context)";
- Router router = new ScriptRouterFactory().getRouter(getRouteUrl(script));
+ StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl(script));
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(false);
Invoker<String> invoker2 = new MockInvoker<String>(true);
Invoker<String> invoker3 = new MockInvoker<String>(true);
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
+
List<Invoker<String>> filteredInvokers = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation(), false).getResult();
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
@@ -87,13 +92,14 @@ public class ScriptRouterTest {
@Test
public void testRouteHostFilter() {
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
MockInvoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService"));
MockInvoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService"));
MockInvoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService"));
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
String script = "function route(invokers, invocation, context){ " +
" var result = new java.util.ArrayList(invokers.size()); " +
@@ -108,7 +114,7 @@ public class ScriptRouterTest {
"} " +
"route(invokers, invocation, context) ";
- Router router = new ScriptRouterFactory().getRouter(getRouteUrl(script));
+ StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl(script));
List<Invoker<String>> routeResult = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation(), false).getResult();
Assertions.assertEquals(1, routeResult.size());
Assertions.assertEquals(invoker2, routeResult.get(0));
@@ -116,16 +122,17 @@ public class ScriptRouterTest {
@Test
public void testRoute_throwException() {
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
MockInvoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService"));
MockInvoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService"));
MockInvoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService"));
- invokers.add(invoker1);
- invokers.add(invoker2);
- invokers.add(invoker3);
+ originInvokers.add(invoker1);
+ originInvokers.add(invoker2);
+ originInvokers.add(invoker3);
+ BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
String script = "/";
- Router router = new ScriptRouterFactory().getRouter(getRouteUrl(script));
+ StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl(script));
List<Invoker<String>> routeResult = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation(), false).getResult();
Assertions.assertEquals(3, routeResult.size());
}
diff --git a/dubbo-cluster/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RouterFactory b/dubbo-cluster/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RouterFactory
deleted file mode 100644
index 95a85f3..0000000
--- a/dubbo-cluster/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RouterFactory
+++ /dev/null
@@ -1 +0,0 @@
-script=org.apache.dubbo.rpc.cluster.router.script.ScriptRouterFactory
diff --git a/dubbo-cluster/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory b/dubbo-cluster/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory
new file mode 100644
index 0000000..fe1043e
--- /dev/null
+++ b/dubbo-cluster/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory
@@ -0,0 +1 @@
+script=org.apache.dubbo.rpc.cluster.router.script.ScriptStateRouterFactory
diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java
index f4dd078..8cfcaa7 100644
--- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java
+++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java
@@ -20,11 +20,12 @@ package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.remoting.Constants;
-import org.apache.dubbo.rpc.cluster.RouterFactory;
-import org.apache.dubbo.rpc.cluster.router.condition.ConditionRouterFactory;
-import org.apache.dubbo.rpc.cluster.router.condition.config.AppRouterFactory;
-import org.apache.dubbo.rpc.cluster.router.tag.TagRouterFactory;
+import org.apache.dubbo.rpc.cluster.router.condition.ConditionStateRouterFactory;
+import org.apache.dubbo.rpc.cluster.router.condition.config.AppStateRouterFactory;
+import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
+import org.apache.dubbo.rpc.cluster.router.tag.TagStateRouterFactory;
import org.apache.dubbo.rpc.model.FrameworkModel;
+
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -108,13 +109,13 @@ public class AbstractReferenceConfigTest {
assertThat(parameters, hasValue("tag,condition"));
URL url = mock(URL.class);
when(url.getParameter(ROUTER_KEY)).thenReturn("condition");
- List<RouterFactory> routerFactories = ExtensionLoader.getExtensionLoader(RouterFactory.class).getActivateExtension(url, ROUTER_KEY);
- assertThat(routerFactories.stream().anyMatch(routerFactory -> routerFactory.getClass().equals(ConditionRouterFactory.class)), is(true));
+ List<StateRouterFactory> routerFactories = ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getActivateExtension(url, ROUTER_KEY);
+ assertThat(routerFactories.stream().anyMatch(routerFactory -> routerFactory.getClass().equals(ConditionStateRouterFactory.class)), is(true));
when(url.getParameter(ROUTER_KEY)).thenReturn("-tag,-app");
- routerFactories = ExtensionLoader.getExtensionLoader(RouterFactory.class).getActivateExtension(url, ROUTER_KEY);
+ routerFactories = ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getActivateExtension(url, ROUTER_KEY);
assertThat(routerFactories.stream()
- .allMatch(routerFactory -> !routerFactory.getClass().equals(TagRouterFactory.class)
- && !routerFactory.getClass().equals(AppRouterFactory.class)), is(true));
+ .allMatch(routerFactory -> !routerFactory.getClass().equals(TagStateRouterFactory.class)
+ && !routerFactory.getClass().equals(AppStateRouterFactory.class)), is(true));
}
@Test
diff --git a/dubbo-native-plugin/src/main/resources/META-INF/native-image/reflect-config.json b/dubbo-native-plugin/src/main/resources/META-INF/native-image/reflect-config.json
index 9d000c1..72161e0 100644
--- a/dubbo-native-plugin/src/main/resources/META-INF/native-image/reflect-config.json
+++ b/dubbo-native-plugin/src/main/resources/META-INF/native-image/reflect-config.json
@@ -2194,7 +2194,7 @@
"name": "org.apache.dubbo.rpc.cluster.router.condition.ConditionRouterFactory"
},
{
- "name": "org.apache.dubbo.rpc.cluster.router.condition.config.AppRouterFactory",
+ "name": "org.apache.dubbo.rpc.cluster.router.condition.config.AppStateRouterFactory",
"allPublicMethods": true,
"methods": [
{
@@ -2204,7 +2204,7 @@
]
},
{
- "name": "org.apache.dubbo.rpc.cluster.router.condition.config.ServiceRouterFactory",
+ "name": "org.apache.dubbo.rpc.cluster.router.condition.config.ServiceStateRouterFactory",
"allPublicMethods": true,
"methods": [
{
@@ -2214,7 +2214,7 @@
]
},
{
- "name": "org.apache.dubbo.rpc.cluster.router.file.FileRouterFactory"
+ "name": "org.apache.dubbo.rpc.cluster.router.file.FileStateRouterFactory"
},
{
"name": "org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleAddressListenerInterceptor",
@@ -2237,7 +2237,7 @@
]
},
{
- "name": "org.apache.dubbo.rpc.cluster.router.mock.MockRouterFactory",
+ "name": "org.apache.dubbo.rpc.cluster.router.mock.MockStateRouterFactory",
"allPublicMethods": true,
"methods": [
{
diff --git a/dubbo-native/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouterFactory$Adaptive.java b/dubbo-native/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouterFactory$Adaptive.java
index f2dc4a3..afd4284 100644
--- a/dubbo-native/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouterFactory$Adaptive.java
+++ b/dubbo-native/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouterFactory$Adaptive.java
@@ -18,13 +18,13 @@ package org.apache.dubbo.rpc.cluster.router.state;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
public class StateRouterFactory$Adaptive implements org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory {
-public org.apache.dubbo.rpc.cluster.router.state.StateRouter getRouter(org.apache.dubbo.common.URL arg0, org.apache.dubbo.rpc.cluster.RouterChain arg1) {
+public org.apache.dubbo.rpc.cluster.router.state.StateRouter getRouter(java.lang.Class arg0, org.apache.dubbo.common.URL arg1) {
if (arg0 == null) throw new IllegalArgumentException("url == null");
-org.apache.dubbo.common.URL url = arg0;
+org.apache.dubbo.common.URL url = arg1;
String extName = ( url.getProtocol() == null ? "adaptive" : url.getProtocol() );
if(extName == null) throw new IllegalStateException("Failed to get extension (org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory) name from url (" + url.toString() + ") use keys([protocol])");
ScopeModel scopeModel = ScopeModelUtil.getOrDefault(url.getScopeModel(), org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory.class);
org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory extension = (org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory)scopeModel.getExtensionLoader(org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory.class).getExtension(extName);
-return extension.getRouter(arg0, arg1);
+return extension.getRouter(arg0,arg1);
}
}
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java
index 2e51f2d..82c0f43 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java
@@ -124,7 +124,7 @@ public class ServiceDiscoveryRegistryDirectory<T> extends DynamicDirectory<T> {
@Override
public void buildRouterChain(URL url) {
- this.setRouterChain(RouterChain.buildChain(url.addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)));
+ this.setRouterChain(RouterChain.buildChain(getInterface(), url.addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)));
}
@Override
diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DynamicDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DynamicDirectory.java
index 8689cbd..9a907d6 100644
--- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DynamicDirectory.java
+++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DynamicDirectory.java
@@ -249,7 +249,7 @@ public abstract class DynamicDirectory<T> extends AbstractDirectory<T> implement
}
public void buildRouterChain(URL url) {
- this.setRouterChain(RouterChain.buildChain(url));
+ this.setRouterChain(RouterChain.buildChain(getInterface(), url));
}
@Override