什么是服务路由

  1. 服务路由包含一条路由规则,路由规则决定了服务消费者的调用目标,即规定了服务消费者可调用哪些服务提供者。Dubbo 目前提供了三种服务路由实现,分别为:
  • 条件路由:ConditionRouter (最常使用)
  • 脚本路由:ScriptRouter
  • 标签路由:TagRouter

路由规则

  1. **应用粒度路由规则:**
  1. # application代表是应用粒度
  2. scope: application
  3. # 指定当路由结果为空时,是否强制执行。如果不强制执行,路由结果为空则路由规则自动失效,不使用路由。缺省为 false,不强制执行。
  4. force: true
  5. # 指定是否在每次调用时执行路由规则。若为 false 则表示只在提供者地址列表变更时会预先执行路由规则,并将路由结果进行缓存,消费者调用时直接从缓存中获取路由结果。
  6. # 若为 true 则表示每次调用都要重新计算路由规则,其将会直接影响调用的性能。缺省为 false。
  7. runtime: true
  8. enabled: true
  9. # 用于设置路由规则的优先级,数字越大,优先级越高,越靠前执行。缺省为 0。
  10. priority: 0
  11. # 路由规则由于的服务名称
  12. key: governance-conditionrouter-consumer
  13. # 规则体。定义具体的路由规则内容,由 1 到任意多条规则组成。
  14. conditions:
  15. # app1 的消费者只能消费所有端口为 20880 的服务提供实例
  16. - application=app1 => address=*:20880
  17. # app2 的消费者只能消费所有端口为 20881 的服务提供实例
  18. - application=app2 => address=*:20881
  1. **服务粒度路由规则:**
  1. scope: service
  2. force: true
  3. runtime: true
  4. enabled: true
  5. # 指定的消费接口名称
  6. key: org.apache.dubbo.samples.governance.api.DemoService
  7. conditions:
  8. # DemoService 的 sayHello 方法只能消费所有端口为 20880 的服务提供者实例
  9. - method=sayHello => address=*:20880
  10. # DemoService 的 sayHi 方法只能消费所有端口为 20881 的服务提供者实例
  11. - method=sayHi => address=*:20881

格式

11.Dubbo服务路由源码阅读 - 图1

实例

  1. 黑名单
    host = 10.20.153.10,10.20.153.11 =>
    IP 为 10.20.153.10 与 10.20.153.11 的主机将被禁用。

  2. 白名单
    host != 10.20.153.10,10.20.153.11 =>
    禁用 IP 为 10.20.153.10 与 10.20.153.11 之外的所有主机。

  3. 只暴露一部分的提供者
    => host = 172.22.3.1,172.22.3.2
    消费者只可访问 IP 为 172.22.3.1与 172.22.3.2的提供者主机。

  4. 为重要应用提供额外的机器
    application != kylin => host != 172.22.3.95,172.22.3.96
    应用名称不为 kylin 的应用不能访问 172.22.3.95 与 172.22.3.96 两台提供者主机。即只有名称为 kylin 的消费者可以访问 172.22.3.95 与 172.22.3.96 两台提供者主机。当然,kylin 还可以访问其它提供者主机,而其它消费者也可以访问 172.22.3.95 与 172.22.3.96 之外的所有提供者主机。

  5. 读写分离
    method = find,list,get,is => host = 172.22.3.94,172.22.3.95,172.22.3.96
    method != find,list,get,is => host = 172.22.3.97,172.22.3.98
    find、list、get、is 开头的消费者方法会被路由到 172.22.3.94、172.22.3.95 与 172.22.3.96三台提供者主机,而其它方法则会被路由到 172.22.3.97 与 172.22.3.98 两台提供者主机

  6. 前后台分离
    application = bops => host = 172.22.3.91,172.22.3.92,172.22.3.93
    application != bops => host = 172.22.3.94,172.22.3.95,172.22.3.96
    应用名称的 bops 的消费者会被路由到 172.22.3.91、172.22.3.92 与 172.22.3.93 三台提供者主机,而其它消费者则会被路由到 172.22.3.94、172.22.3.95 与 172.22.3.96 三台提供者。

  7. 隔离不同机房网段
    host != 172.22.3. => host != 172.22.3.
    不是 172.22.3 网段的消费者是不能访问 172.22.3 网段的提供者的。即只有 172.22.3 网段的消费者才可访问 172.22.3 网段的提供者。当然,172.22.3 网段的消费者也可访问其它网段的提供者。

  8. 只访问本机的服务
    => host = $host
    $host 表示获取消费者请求中的消费者主机 IP。故该规则就表示消费者只能访问本机的服务。

添加激活 RouterFactory 到 Directory

RegistryProtocol.java

11.Dubbo服务路由源码阅读 - 图2

RegistryDirectory.java

  1. public void buildRouterChain(URL url) {
  2. // 解析URL中的路由信息
  3. this.setRouterChain(RouterChain.buildChain(url));
  4. }

RouterChain.java

  1. public static <T> RouterChain<T> buildChain(URL url) {
  2. return new RouterChain<>(url);
  3. }
  4. private RouterChain(URL url) {
  5. // 获取RouterFactory的所有激活类实例
  6. List<RouterFactory> extensionFactories = ExtensionLoader.getExtensionLoader(RouterFactory.class)
  7. .getActivateExtension(url, (String[]) null);
  8. List<Router> routers = extensionFactories.stream() // 生成一个Stream,元素是factory
  9. .map(factory -> factory.getRouter(url)) // 将Stream中的factory映射为该factory生成的router
  10. .collect(Collectors.toList()); // 将Stream再变为List
  11. // 将创建的router列表初始化到Directory的routerChain中
  12. initWithRouters(routers);
  13. }

读取 注册中心 中的路由规则

11.Dubbo服务路由源码阅读 - 图3

11.Dubbo服务路由源码阅读 - 图4

11.Dubbo服务路由源码阅读 - 图5

11.Dubbo服务路由源码阅读 - 图6

  1. private List<URL> toUrlsWithEmpty(URL consumer, String path, List<String> providers) {
  2. // 获取到当前分类节点下的所有非空url
  3. List<URL> urls = toUrlsWithoutEmpty(consumer, providers);
  4. // 若当前分类节点下没有子节点,则系统为其创建一个形如 empty://... 的空url
  5. if (urls == null || urls.isEmpty()) {
  6. int i = path.lastIndexOf(PATH_SEPARATOR);
  7. String category = i < 0 ? path : path.substring(i + 1);
  8. URL empty = URLBuilder.from(consumer)
  9. .setProtocol(EMPTY_PROTOCOL)
  10. .addParameter(CATEGORY_KEY, category)
  11. .build();
  12. urls.add(empty);
  13. }
  14. return urls;
  15. }
  16. private List<URL> toUrlsWithoutEmpty(URL consumer, List<String> providers) {
  17. List<URL> urls = new ArrayList<>();
  18. if (CollectionUtils.isNotEmpty(providers)) {
  19. // 遍历所有子节点
  20. for (String provider : providers) {
  21. // 解码
  22. provider = URL.decode(provider);
  23. // 处理子节点名称为url形式的情况
  24. if (provider.contains(PROTOCOL_SEPARATOR)) {
  25. URL url = URL.valueOf(provider);
  26. if (UrlUtils.isMatch(consumer, url)) {
  27. urls.add(url);
  28. }
  29. }
  30. }
  31. }
  32. return urls;
  33. }

RegistryDirectory.java

  1. @Override
  2. public synchronized void notify(List<URL> urls) {
  3. Map<String, List<URL>> categoryUrls = urls.stream()
  4. .filter(Objects::nonNull)
  5. .filter(this::isValidCategory)
  6. .filter(this::isNotCompatibleFor26x)
  7. .collect(Collectors.groupingBy(url -> {
  8. if (UrlUtils.isConfigurator(url)) {
  9. return CONFIGURATORS_CATEGORY;
  10. } else if (UrlUtils.isRoute(url)) {
  11. return ROUTERS_CATEGORY;
  12. } else if (UrlUtils.isProvider(url)) {
  13. return PROVIDERS_CATEGORY;
  14. }
  15. return "";
  16. }));
  17. // 处理configurators分类节点情况
  18. List<URL> configuratorURLs = categoryUrls.getOrDefault(CONFIGURATORS_CATEGORY, Collections.emptyList());
  19. this.configurators = Configurator.toConfigurators(configuratorURLs).orElse(this.configurators);
  20. // 处理routers分类节点情况
  21. List<URL> routerURLs = categoryUrls.getOrDefault(ROUTERS_CATEGORY, Collections.emptyList());
  22. toRouters(routerURLs) // 返回Optional
  23. // 若Optional中封装的对象不空,则调用Lambda的实例方法引用addRouters(),即将这个路由添加到directory
  24. .ifPresent(this::addRouters);
  25. // providers
  26. // 处理providers分类节点情况
  27. List<URL> providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList());
  28. // 从zk中获取最新的提供者更新到directory
  29. refreshOverrideAndInvoker(providerURLs);
  30. }
  31. private void refreshOverrideAndInvoker(List<URL> urls) {
  32. // mock zookeeper://xxx?mock=return null
  33. overrideDirectoryUrl();
  34. refreshInvoker(urls); //
  35. }
  36. private Optional<List<Router>> toRouters(List<URL> urls) {
  37. if (urls == null || urls.isEmpty()) {
  38. return Optional.empty();
  39. }
  40. List<Router> routers = new ArrayList<>();
  41. for (URL url : urls) {
  42. // 若当前url以empty作为protocol,则说明其不是一个有效url
  43. if (EMPTY_PROTOCOL.equals(url.getProtocol())) {
  44. continue;
  45. }
  46. // 获取到url中的router属性值,当前值为condition,表示这是一个条件路由
  47. String routerType = url.getParameter(ROUTER_KEY);
  48. if (routerType != null && routerType.length() > 0) {
  49. // 将路由类型作为url的protocol,即当前的url变为了condition://...
  50. url = url.setProtocol(routerType);
  51. }
  52. try {
  53. // 创建路由
  54. Router router = ROUTER_FACTORY.getRouter(url);
  55. // 将该路由实例记录下来
  56. if (!routers.contains(router)) {
  57. routers.add(router);
  58. }
  59. } catch (Throwable t) {
  60. logger.error("convert router url to router error, url: " + url, t);
  61. }
  62. }
  63. return Optional.of(routers);
  64. }

路由规则生效

发生在调用方法的时候

InvokerInvocationHandler.java

  1. public class InvokerInvocationHandler implements InvocationHandler {
  2. private static final Logger logger = LoggerFactory.getLogger(InvokerInvocationHandler.class);
  3. private final Invoker<?> invoker;
  4. public InvokerInvocationHandler(Invoker<?> handler) {
  5. this.invoker = handler;
  6. }
  7. @Override
  8. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  9. // 获取到RPC远程调用的方法名
  10. String methodName = method.getName();
  11. Class<?>[] parameterTypes = method.getParameterTypes();
  12. // 若当前方法为Object的方法,则为本地方法调用
  13. if (method.getDeclaringClass() == Object.class) {
  14. return method.invoke(invoker, args);
  15. }
  16. if ("toString".equals(methodName) && parameterTypes.length == 0) {
  17. return invoker.toString();
  18. }
  19. if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
  20. return invoker.hashCode();
  21. }
  22. if ("equals".equals(methodName) && parameterTypes.length == 1) {
  23. return invoker.equals(args[0]);
  24. }
  25. // 远程调用
  26. return invoker.invoke(new RpcInvocation(method, args)).recreate();
  27. }
  28. }

MockClusterInvoker.java

  1. @Override
  2. public Result invoke(Invocation invocation) throws RpcException {
  3. Result result = null;
  4. String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), MOCK_KEY, Boolean.FALSE.toString()).trim();
  5. if (value.length() == 0 || value.equalsIgnoreCase("false")) {
  6. //no mock 远程调用
  7. result = this.invoker.invoke(invocation);
  8. } else if (value.startsWith("force")) {
  9. if (logger.isWarnEnabled()) {
  10. logger.warn("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " + directory.getUrl());
  11. }
  12. result = doMockInvoke(invocation, null);
  13. } else {
  14. //fail-mock
  15. try { // 远程调用
  16. result = this.invoker.invoke(invocation);
  17. } catch (RpcException e) {
  18. if (e.isBiz()) {
  19. throw e;
  20. }
  21. if (logger.isWarnEnabled()) {
  22. logger.warn("fail-mock: " + invocation.getMethodName() + " fail-mock enabled , url : " + directory.getUrl(), e);
  23. }
  24. result = doMockInvoke(invocation, e);
  25. }
  26. }
  27. return result;
  28. }

AbstractClusterInvoker.java

  1. public Result invoke(final Invocation invocation) throws RpcException {
  2. checkWhetherDestroyed();
  3. // binding attachments into invocation.
  4. Map<String, String> contextAttachments = RpcContext.getContext().getAttachments();
  5. if (contextAttachments != null && contextAttachments.size() != 0) {
  6. ((RpcInvocation) invocation).addAttachments(contextAttachments);
  7. }
  8. // 路由:根据路由规则过滤掉不可用的invoker,返回剩下的可用的invoker
  9. // 跟踪这个list
  10. List<Invoker<T>> invokers = list(invocation);
  11. // 获取负载均衡策略
  12. LoadBalance loadbalance = initLoadBalance(invokers, invocation);
  13. RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
  14. // 调用具体容错策略的doInvoke()
  15. return doInvoke(invocation, invokers, loadbalance);
  16. }

11.Dubbo服务路由源码阅读 - 图7

RegistryDirectory.java

  1. public List<Invoker<T>> doList(Invocation invocation) {
  2. if (forbidden) {
  3. // 1. No service provider 2. Service providers are disabled
  4. throw new RpcException(RpcException.FORBIDDEN_EXCEPTION, "No provider available from registry " +
  5. getUrl().getAddress() + " for service " + getConsumerUrl().getServiceKey() + " on consumer " +
  6. NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() +
  7. ", please check status of providers(disabled, not registered or in blacklist).");
  8. }
  9. if (multiGroup) {
  10. return this.invokers == null ? Collections.emptyList() : this.invokers;
  11. }
  12. List<Invoker<T>> invokers = null;
  13. try {
  14. // Get invokers from cache, only runtime routers will be executed.
  15. // 将路由规则应用到所有invokers中,过滤掉不满足规则的invoker
  16. invokers = routerChain.route(getConsumerUrl(), invocation);
  17. } catch (Throwable t) {
  18. logger.error("Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(), t);
  19. }
  20. return invokers == null ? Collections.emptyList() : invokers;
  21. }

RouterChain.java

  1. public List<Invoker<T>> route(URL url, Invocation invocation) {
  2. List<Invoker<T>> finalInvokers = invokers;
  3. for (Router router : routers) {
  4. finalInvokers = router.route(finalInvokers, url, invocation);
  5. }
  6. return finalInvokers;
  7. }

ConditionRouter.java

  1. public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation)
  2. throws RpcException {
  3. // 若路由规则中的enabled属性为false(即当前路由规则等同于没有),则返回所有invoker
  4. if (!enabled) {
  5. return invokers;
  6. }
  7. // 若没有提供者,则返回空
  8. if (CollectionUtils.isEmpty(invokers)) {
  9. return invokers;
  10. }
  11. try {
  12. // matcherWhen()方法用于判断当前的消费者是否与箭头(=>)前面部分相匹配,
  13. // 若不匹配,则说明当前规则对当前消费者不起作用,即无需通过路由过滤,直接返回所有invoker
  14. if (!matchWhen(url, invocation)) {
  15. return invokers;
  16. }
  17. // 代码走到这里,说明当前消费者已经与箭头(=>)前面部分匹配上了,现在看箭头(=>)后面的情况了
  18. // 该result集合将来用于存放通过路由过滤的invoker
  19. List<Invoker<T>> result = new ArrayList<Invoker<T>>();
  20. // thenCondition 中存放的是箭头(=>)后面部分,若其为null,
  21. // 则说明当前规则为黑/白名单,即所有invoker均不可用
  22. if (thenCondition == null) {
  23. logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey());
  24. return result;
  25. }
  26. // 代码走到这里,说明当前消费者已经匹配上了箭头(=>)前面,且后面也不为空,
  27. // 此时就需要遍历所有invoker,去尝试着匹配箭头(=>)后的规则条件
  28. for (Invoker<T> invoker : invokers) {
  29. // matchThen() 判断是否与箭头(=>)后的条件相匹配
  30. if (matchThen(invoker.getUrl(), url)) {
  31. // 匹配上了,则通过路由过滤,表示其是可用的
  32. result.add(invoker);
  33. }
  34. }
  35. if (!result.isEmpty()) {
  36. return result;
  37. } else if (force) {
  38. logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(RULE_KEY));
  39. return result;
  40. }
  41. } catch (Throwable t) {
  42. logger.error("Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + t.getMessage(), t);
  43. }
  44. return invokers;
  45. }