欢迎来我的 Star Followers 后期后继续更新Dubbo别的文章

Dubbo 源码分析系列之一环境搭建 博客园
Dubbo 入门之二 ——- 项目结构解析 博客园
Dubbo 源码分析系列之三 —— 架构原理 博客园
Dubbo 源码解析四 —— 负载均衡LoadBalance 博客园

下面是个人博客地址,页面比博客园美观一些其他都是一样的

Dubbo 源码分析系列之一环境搭建" Dubbo 源码分析系列之一环境搭建 个人博客地址"

Dubbo 入门之二 ——- 项目结构解析"Dubbo 项目结构解析 个人博客地址"

Dubbo 源码分析系列之三 —— 架构原理" Dubbo 源码分析系列之三---架构原理 个人博客地址"

Dubbo 源码解析四 —— 负载均衡LoadBalance" dubbo源码解析四 --- 负载均衡LoadBalance 个人博客地址"

Dubbo 源码解析五 —— 集群容错" dubbo源码解析五 --- 集群容错架构设计与原理分析 个人博客地址"

目录

  • 面试中集群容错的经常的问题
  • Dubbo 官方文档关于集群容错的介绍
  • Dubbo集群容错的架构分析
  • Dubbo集群容错源码解析

面试中集群容错的经常的问题

  • 什么是集群容错
  • Dubbo的集群容错知道吗
  • Dubbo 集群容错是如何配置的
  • 集群容错如何实现的
  • Dubbo 集群容错介绍下
  • 介绍下 几种集群容错方式,分析下其优缺点
  • 你来设计一个容错算法,你会怎样的设计

Dubbo 官方文档关于集群容错的介绍

在集群调用失败时,Dubbo 提供了多种容错方案,缺省为 failover 重试。

各节点关系:

  • 这里的 InvokerProvider 的一个可调用 Service 的抽象,Invoker 封装了 Provider 地址及 Service 接口信息
  • Directory 代表多个 Invoker,可以把它看成 List<Invoker> ,但与 List 不同的是,它的值可能是动态变化的,比如注册中心推送变更
  • ClusterDirectory 中的多个 Invoker 伪装成一个 Invoker,对上层透明,伪装过程包含了容错逻辑,调用失败后,重试另一个
  • Router 负责从多个 Invoker 中按路由规则选出子集,比如读写分离,应用隔离等
  • LoadBalance 负责从多个 Invoker 中选出具体的一个用于本次调用,选的过程包含了负载均衡算法,调用失败后,需要重选

集群容错模式

可以自行扩展集群容错策略,参见:集群扩展

Failover Cluster

失败自动切换,当出现失败,重试其它服务器 [1]。通常用于读操作,但重试会带来更长延迟。可通过 retries="2" 来设置重试次数(不含第一次)。

重试次数配置如下:

  1. <dubbo:service retries="2" />

  1. <dubbo:reference retries="2" />

  1. <dubbo:reference>
  2. <dubbo:method name="findFoo" retries="2" />
  3. </dubbo:reference>

Failfast Cluster

快速失败,只发起一次调用,失败立即报错。通常用于非幂等性的写操作,比如新增记录。

Failsafe Cluster

失败安全,出现异常时,直接忽略。通常用于写入审计日志等操作。

Failback Cluster

失败自动恢复,后台记录失败请求,定时重发。通常用于消息通知操作。

Forking Cluster

并行调用多个服务器,只要一个成功即返回。通常用于实时性要求较高的读操作,但需要浪费更多服务资源。可通过 forks="2" 来设置最大并行数。

Broadcast Cluster

广播调用所有提供者,逐个调用,任意一台报错则报错 [2]。通常用于通知所有提供者更新缓存或日志等本地资源信息。

集群模式配置

按照以下示例在服务提供方和消费方配置集群模式

  1. <dubbo:service cluster="failsafe" />

  1. <dubbo:reference cluster="failsafe" />

Dubbo集群容错的架构分析

通过官网上这张图我们能大致的了解到一个请求过来,在集群中的调用过程。那么我们就根据这个调用过程来进行分析吧。

整个在调用的过程中 这三个关键词接下来会贯穿全文,他们就是Directory,Router,LoadBalance

我们只要牢牢的抓住这几个关键字就能贯穿整个调用链

先看下时序图,来看下调用的过程

最初我们一个方法调用

我们使用的是官方的dubbo-demodubbo-demo-consumer

  1. public static void main(String[] args) {
  2. DemoService demoService = (DemoService) context.getBean("demoService"); // get remote service proxy
  3. String hello = demoService.sayHello("world"); // call remote method
  4. System.out.println(hello); // get result
  5. }

调用 InvokerInvocationHandler#invoker方法代理类的调用

  1. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  2. String methodName = method.getName();
  3. Class<?>[] parameterTypes = method.getParameterTypes();
  4. if (method.getDeclaringClass() == Object.class) {
  5. return method.invoke(invoker, args);
  6. }
  7. if ("toString".equals(methodName) && parameterTypes.length == 0) {
  8. return invoker.toString();
  9. }
  10. if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
  11. return invoker.hashCode();
  12. }
  13. if ("equals".equals(methodName) && parameterTypes.length == 1) {
  14. return invoker.equals(args[0]);
  15. }
  16. RpcInvocation invocation;
  17. if (RpcUtils.hasGeneratedFuture(method)) {
  18. Class<?> clazz = method.getDeclaringClass();
  19. String syncMethodName = methodName.substring(0, methodName.length() - Constants.ASYNC_SUFFIX.length());
  20. Method syncMethod = clazz.getMethod(syncMethodName, method.getParameterTypes());
  21. invocation = new RpcInvocation(syncMethod, args);
  22. invocation.setAttachment(Constants.FUTURE_GENERATED_KEY, "true");
  23. invocation.setAttachment(Constants.ASYNC_KEY, "true");
  24. } else {
  25. invocation = new RpcInvocation(method, args);
  26. if (RpcUtils.hasFutureReturnType(method)) {
  27. invocation.setAttachment(Constants.FUTURE_RETURNTYPE_KEY, "true");
  28. invocation.setAttachment(Constants.ASYNC_KEY, "true");
  29. }
  30. }
  31. //这里使用的是动态代理的方式获取到指定的代理类
  32. // <1>
  33. return invoker.invoke(invocation).recreate();
  34. }

**1 执行invoke就要开始进入MockClusterInvoker#invoker **

  1. public Result invoke(Invocation invocation) throws RpcException {
  2. Result result = null;
  3. // 获得 “mock” 配置项,有多种配置方式
  4. String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), Constants.MOCK_KEY, Boolean.FALSE.toString()).trim();
  5. //【第一种】无 mock
  6. if (value.length() == 0 || value.equalsIgnoreCase("false")) {
  7. //no mock
  8. // 调用原 Invoker ,发起 RPC 调用
  9. // 调用 invoker方法,进入到集群也就是CLuster类中
  10. //<2>
  11. result = this.invoker.invoke(invocation);
  12. //【第二种】强制服务降级
  13. } else if (value.startsWith("force")) {
  14. if (logger.isWarnEnabled()) {
  15. logger.warn("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " + directory.getUrl());
  16. }
  17. //force:direct mock
  18. // 直接调用 Mock Invoker ,执行本地 Mock 逻辑
  19. result = doMockInvoke(invocation, null);
  20. } else {
  21. //fail-mock
  22. try {
  23. // 【第三种】失败服务降级
  24. result = this.invoker.invoke(invocation);
  25. } catch (RpcException e) {
  26. // 业务性异常,直接抛出
  27. if (e.isBiz()) {
  28. throw e;
  29. } else {
  30. if (logger.isWarnEnabled()) {
  31. logger.warn("fail-mock: " + invocation.getMethodName() + " fail-mock enabled , url : " + directory.getUrl(), e);
  32. }
  33. // 失败后,调用 Mock Invoker ,执行本地 Mock 逻辑
  34. result = doMockInvoke(invocation, e);
  35. }
  36. }
  37. }
  38. return result;
  39. }

**2 进入到 invoke就要开始进入到集群,也就是Cluster **

  1. /**
  2. * 调用服务提供者
  3. * @param invocation
  4. * @return
  5. * @throws RpcException
  6. */
  7. @Override
  8. public Result invoke(final Invocation invocation) throws RpcException {
  9. // 校验是否销毁
  10. checkWhetherDestroyed();
  11. //TODO
  12. // binding attachments into invocation.
  13. Map<String, String> contextAttachments = RpcContext.getContext().getAttachments();
  14. if (contextAttachments != null && contextAttachments.size() != 0) {
  15. ((RpcInvocation) invocation).addAttachments(contextAttachments);
  16. }
  17. // 获得所有服务提供者 Invoker 集合
  18. // <下面的list方法>
  19. List<Invoker<T>> invokers = list(invocation);
  20. // 获得 LoadBalance 对象
  21. LoadBalance loadbalance = initLoadBalance(invokers, invocation);
  22. // 设置调用编号,若是异步调用
  23. RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
  24. // 执行调用
  25. return doInvoke(invocation, invokers, loadbalance);
  26. }
  1. /**
  2. * 获得所有服务提供者 Invoker 集合
  3. * @param invocation
  4. * @return
  5. * @throws RpcException
  6. */
  7. protected List<Invoker<T>> list(Invocation invocation) throws RpcException {
  8. // 通过directory 进入到 AbstractDirectory 中选择 directory
  9. //<3 进入3 里面>
  10. return directory.list(invocation);
  11. }

3 进入到 AbstractDirectory 进行 directory的选择

  1. /**
  2. * 获得所有服务 Invoker 集合
  3. * @param invocation
  4. * @return Invoker 集合
  5. * @throws RpcException
  6. */
  7. @Override
  8. public List<Invoker<T>> list(Invocation invocation) throws RpcException {
  9. //当销毁时抛出异常
  10. if (destroyed) {
  11. throw new RpcException("Directory already destroyed .url: " + getUrl());
  12. }
  13. // 获得所有 Invoker 集合
  14. // <4 RegistryDirectory 选择 invoker>
  15. List<Invoker<T>> invokers = doList(invocation);
  16. //根据路由规则,筛选Invoker集合
  17. List<Router> localRouters = this.routers; // local reference 本地引用,避免并发问题
  18. if (localRouters != null && !localRouters.isEmpty()) {
  19. for (Router router : localRouters) {
  20. try {
  21. if (router.getUrl() == null || router.getUrl().getParameter(Constants.RUNTIME_KEY, false)) {
  22. invokers = router.route(invokers, getConsumerUrl(), invocation);
  23. }
  24. } catch (Throwable t) {
  25. logger.error("Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(), t);
  26. }
  27. }
  28. }
  29. //< 6 获取 router 即将进入 MockInvokersSelector 类中>
  30. return invokers;
  31. }

调用list方法会进入到 RegistryDirectory#doList

  1. /**
  2. * 获得对应的 Invoker 集合。
  3. * @param invocation
  4. * @return
  5. */
  6. @Override
  7. public List<Invoker<T>> doList(Invocation invocation) {
  8. if (forbidden) {
  9. // 1. No service provider 2. Service providers are disabled
  10. throw new RpcException(RpcException.FORBIDDEN_EXCEPTION,
  11. "No provider available from registry " + getUrl().getAddress() + " for service " + getConsumerUrl().getServiceKey() + " on consumer " + NetUtils.getLocalHost()
  12. + " use dubbo version " + Version.getVersion() + ", please check status of providers(disabled, not registered or in blacklist).");
  13. }
  14. List<Invoker<T>> invokers = null;
  15. //从methodInvokerMap中取出invokers
  16. Map<String, List<Invoker<T>>> localMethodInvokerMap = this.methodInvokerMap; // local reference
  17. // 获得 Invoker 集合
  18. if (localMethodInvokerMap != null && localMethodInvokerMap.size() > 0) {
  19. // 获得方法名、方法参数
  20. String methodName = RpcUtils.getMethodName(invocation);
  21. Object[] args = RpcUtils.getArguments(invocation);
  22. // 【第一】可根据第一个参数枚举路由
  23. if (args != null && args.length > 0 && args[0] != null
  24. && (args[0] instanceof String || args[0].getClass().isEnum())) {
  25. invokers = localMethodInvokerMap.get(methodName + "." + args[0]); // The routing can be enumerated according to the first parameter
  26. }
  27. // 【第二】根据方法名获得 Invoker 集合
  28. if (invokers == null) {
  29. invokers = localMethodInvokerMap.get(methodName);
  30. }
  31. // 【第三】使用全量 Invoker 集合。例如,`#$echo(name)` ,回声方法
  32. if (invokers == null) {
  33. invokers = localMethodInvokerMap.get(Constants.ANY_VALUE);
  34. }
  35. // 【第四】使用 `methodInvokerMap` 第一个 Invoker 集合。防御性编程。
  36. if (invokers == null) {
  37. Iterator<List<Invoker<T>>> iterator = localMethodInvokerMap.values().iterator();
  38. if (iterator.hasNext()) {
  39. invokers = iterator.next();
  40. }
  41. }
  42. }
  43. return invokers == null ? new ArrayList<Invoker<T>>(0) : invokers;
  44. }

6 进入 MockInvokersSelector 类中根据路由规则拿到正常执行的invokers

  1. /**
  2. * ,根据 "invocation.need.mock" 路由匹配对应类型的 Invoker 集合:
  3. * @param invokers Invoker 集合
  4. * @param url refer url
  5. * @param invocation
  6. * @param <T>
  7. * @return
  8. * @throws RpcException
  9. */
  10. @Override
  11. public <T> List<Invoker<T>> route(final List<Invoker<T>> invokers,
  12. URL url, final Invocation invocation) throws RpcException {
  13. // 获得普通 Invoker 集合
  14. if (invocation.getAttachments() == null) {
  15. //<7> 拿到能正常执行的invokers,并将其返回.也就是序号7
  16. return getNormalInvokers(invokers);
  17. } else {
  18. // 获得 "invocation.need.mock" 配置项
  19. String value = invocation.getAttachments().get(Constants.INVOCATION_NEED_MOCK);
  20. // 获得普通 Invoker 集合
  21. if (value == null)
  22. return getNormalInvokers(invokers);
  23. // 获得 MockInvoker 集合
  24. else if (Boolean.TRUE.toString().equalsIgnoreCase(value)) {
  25. return getMockedInvokers(invokers);
  26. }
  27. }
  28. // 其它,不匹配,直接返回 `invokers` 集合
  29. return invokers;
  30. }

<7> 拿到能正常执行的invokers,并将其返回

  1. /**
  2. * 获得普通 Invoker 集合
  3. * @param invokers
  4. * @param <T>
  5. * @return
  6. */
  7. private <T> List<Invoker<T>> getNormalInvokers(final List<Invoker<T>> invokers) {
  8. // 不包含 MockInvoker 的情况下,直接返回 `invokers` 集合
  9. if (!hasMockProviders(invokers)) {
  10. return invokers;
  11. } else {
  12. // 若包含 MockInvoker 的情况下,过滤掉 MockInvoker ,创建普通 Invoker 集合
  13. List<Invoker<T>> sInvokers = new ArrayList<Invoker<T>>(invokers.size());
  14. for (Invoker<T> invoker : invokers) {
  15. if (!invoker.getUrl().getProtocol().equals(Constants.MOCK_PROTOCOL)) {
  16. sInvokers.add(invoker);
  17. }
  18. }
  19. return sInvokers;
  20. }
  21. }

**8 拿到 invoker 返回到 AbstractClusterInvoker这个类 **

对于上面的这些步骤,主要用于做两件事

  • Directory中找出本次集群中的全部invokers
  • Router中,将上一步的全部invokers挑选出能正常执行的invokers

在 时序图的序号5和序号7处,做了上诉的处理。

在有多个集群的情况下,而且两个集群都是正常的,那么到底需要执行哪个?

AbstractClusterInvoker#invoke

  1. /**
  2. * 调用服务提供者
  3. * @param invocation
  4. * @return
  5. * @throws RpcException
  6. */
  7. @Override
  8. public Result invoke(final Invocation invocation) throws RpcException {
  9. // 校验是否销毁
  10. checkWhetherDestroyed();
  11. //TODO
  12. // binding attachments into invocation.
  13. Map<String, String> contextAttachments = RpcContext.getContext().getAttachments();
  14. if (contextAttachments != null && contextAttachments.size() != 0) {
  15. ((RpcInvocation) invocation).addAttachments(contextAttachments);
  16. }
  17. // 获得所有服务提供者 Invoker 集合
  18. List<Invoker<T>> invokers = list(invocation);
  19. // 获得 LoadBalance 对象
  20. LoadBalance loadbalance = initLoadBalance(invokers, invocation);
  21. // 设置调用编号,若是异步调用
  22. RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
  23. // 执行调用
  24. return doInvoke(invocation, invokers, loadbalance);
  25. }
  1. /**
  2. * 实现子 Cluster 的 Invoker 实现类的服务调用的差异逻辑,
  3. * @param invocation
  4. * @param invokers
  5. * @param loadbalance
  6. * @return
  7. * @throws RpcException
  8. */
  9. // 抽象方法,子类自行的实现 因为我们使用的默认配置,所以 我们将会是FailoverClusterInvoker 这个类
  10. //< 8 doInvoker 方法>
  11. protected abstract Result doInvoke(Invocation invocation, List<Invoker<T>> invokers,
  12. LoadBalance loadbalance) throws RpcException;

9 进入到 相应的集群容错方案 类中 因为我们使用的默认配置,所以 我们将会是FailoverClusterInvoker 这个类

  1. /**
  2. * 实际逻辑很简单:循环,查找一个 Invoker 对象,进行调用,直到成功
  3. * @param invocation
  4. * @param invokers
  5. * @param loadbalance
  6. * @return
  7. * @throws RpcException
  8. */
  9. @Override
  10. @SuppressWarnings({"unchecked", "rawtypes"})
  11. public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  12. List<Invoker<T>> copyinvokers = invokers;
  13. // 检查copyinvokers即可用Invoker集合是否为空,如果为空,那么抛出异常
  14. checkInvokers(copyinvokers, invocation);
  15. String methodName = RpcUtils.getMethodName(invocation);
  16. // 得到最大可调用次数:最大可重试次数+1,默认最大可重试次数Constants.DEFAULT_RETRIES=2
  17. int len = getUrl().getMethodParameter(methodName, Constants.RETRIES_KEY, Constants.DEFAULT_RETRIES) + 1;
  18. if (len <= 0) {
  19. len = 1;
  20. }
  21. // retry loop.
  22. // 保存最后一次调用的异常
  23. RpcException le = null; // last exception.
  24. List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyinvokers.size()); // invoked invokers.
  25. Set<String> providers = new HashSet<String>(len);
  26. // failover机制核心实现:如果出现调用失败,那么重试其他服务器
  27. for (int i = 0; i < len; i++) {
  28. //Reselect before retry to avoid a change of candidate `invokers`.
  29. //NOTE: if `invokers` changed, then `invoked` also lose accuracy.
  30. // 重试时,进行重新选择,避免重试时invoker列表已发生变化.
  31. // 注意:如果列表发生了变化,那么invoked判断会失效,因为invoker示例已经改变
  32. if (i > 0) {
  33. checkWhetherDestroyed();
  34. // 根据Invocation调用信息从Directory中获取所有可用Invoker
  35. copyinvokers = list(invocation);
  36. // check again
  37. // 重新检查一下
  38. checkInvokers(copyinvokers, invocation);
  39. }
  40. // 根据负载均衡机制从copyinvokers中选择一个Invoker
  41. //< 9 select ------------------------- 下面将进行 invoker选择----------------------------------->
  42. Invoker<T> invoker = select(loadbalance, invocation, copyinvokers, invoked);
  43. // 保存每次调用的Invoker
  44. invoked.add(invoker);
  45. // 设置已经调用的 Invoker 集合,到 Context 中
  46. RpcContext.getContext().setInvokers((List) invoked);
  47. try {
  48. // RPC 调用得到 Result
  49. Result result = invoker.invoke(invocation);
  50. // 重试过程中,将最后一次调用的异常信息以 warn 级别日志输出
  51. if (le != null && logger.isWarnEnabled()) {
  52. logger.warn("Although retry the method " + methodName
  53. + " in the service " + getInterface().getName()
  54. + " was successful by the provider " + invoker.getUrl().getAddress()
  55. + ", but there have been failed providers " + providers
  56. + " (" + providers.size() + "/" + copyinvokers.size()
  57. + ") from the registry " + directory.getUrl().getAddress()
  58. + " on the consumer " + NetUtils.getLocalHost()
  59. + " using the dubbo version " + Version.getVersion() + ". Last error is: "
  60. + le.getMessage(), le);
  61. }
  62. return result;
  63. } catch (RpcException e) {
  64. // 如果是业务性质的异常,不再重试,直接抛出
  65. if (e.isBiz()) { // biz exception.
  66. throw e;
  67. }
  68. // 其他性质的异常统一封装成RpcException
  69. le = e;
  70. } catch (Throwable e) {
  71. le = new RpcException(e.getMessage(), e);
  72. } finally {
  73. providers.add(invoker.getUrl().getAddress());
  74. }
  75. }
  76. // 最大可调用次数用完还得到Result的话,抛出RpcException异常:重试了N次还是失败,并输出最后一次异常信息
  77. throw new RpcException(le.getCode(), "Failed to invoke the method "
  78. + methodName + " in the service " + getInterface().getName()
  79. + ". Tried " + len + " times of the providers " + providers
  80. + " (" + providers.size() + "/" + copyinvokers.size()
  81. + ") from the registry " + directory.getUrl().getAddress()
  82. + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version "
  83. + Version.getVersion() + ". Last error is: "
  84. + le.getMessage(), le.getCause() != null ? le.getCause() : le);
  85. }

9 select 使用 loadbalance 选择 invoker


  1. /**
  2. * Select a invoker using loadbalance policy.</br>
  3. * a) Firstly, select an invoker using loadbalance. If this invoker is in previously selected list, or,
  4. * if this invoker is unavailable, then continue step b (reselect), otherwise return the first selected invoker</br>
  5. * <p>
  6. * b) Reselection, the validation rule for reselection: selected > available. This rule guarantees that
  7. * the selected invoker has the minimum chance to be one in the previously selected list, and also
  8. * guarantees this invoker is available.
  9. *
  10. * @param loadbalance load balance policy
  11. * @param invocation invocation
  12. * @param invokers invoker candidates
  13. * @param selected exclude selected invokers or not
  14. * @return the invoker which will final to do invoke.
  15. * @throws RpcException
  16. */
  17. /**
  18. * 使用 loadbalance 选择 invoker.
  19. * a)
  20. * @param loadbalance 对象,提供负责均衡策略
  21. * @param invocation 对象
  22. * @param invokers 候选的 Invoker 集合
  23. * @param selected 已选过的 Invoker 集合. 注意:输入保证不重复
  24. * @return 最终的 Invoker 对象
  25. * @throws RpcException
  26. */
  27. protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException {
  28. if (invokers == null || invokers.isEmpty())
  29. return null;
  30. // 获得 sticky 配置项,方法级
  31. String methodName = invocation == null ? "" : invocation.getMethodName();
  32. boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY);
  33. {
  34. //ignore overloaded method
  35. // 若 stickyInvoker 不存在于 invokers 中,说明不在候选中,需要置空,重新选择
  36. if (stickyInvoker != null && !invokers.contains(stickyInvoker)) {
  37. stickyInvoker = null;
  38. }
  39. //ignore concurrency problem
  40. // 若开启粘滞连接的特性,且 stickyInvoker 不存在于 selected 中,则返回 stickyInvoker 这个 Invoker 对象
  41. if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) {
  42. // 若开启排除非可用的 Invoker 的特性,则校验 stickyInvoker 是否可用。若可用,则进行返回
  43. if (availablecheck && stickyInvoker.isAvailable()) {
  44. return stickyInvoker;
  45. }
  46. }
  47. }
  48. // 执行选择
  49. //< 10 -----------------------------进行选择------------------------------------->
  50. Invoker<T> invoker = doSelect(loadbalance, invocation, invokers, selected);
  51. // 若开启粘滞连接的特性,记录最终选择的 Invoker 到 stickyInvoker
  52. if (sticky) {
  53. stickyInvoker = invoker;
  54. }
  55. return invoker;
  56. }

10 doSelect 从候选的 Invoker 集合,选择一个最终调用的 Invoker 对象

  1. /**
  2. * 从候选的 Invoker 集合,选择一个最终调用的 Invoker 对象
  3. * @param loadbalance
  4. * @param invocation
  5. * @param invokers
  6. * @param selected
  7. * @return
  8. * @throws RpcException
  9. */
  10. private Invoker<T> doSelect(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException {
  11. if (invokers == null || invokers.isEmpty())
  12. return null;
  13. // 如果只有一个 Invoker ,直接选择
  14. if (invokers.size() == 1)
  15. return invokers.get(0);
  16. // 使用 Loadbalance ,选择一个 Invoker 对象。
  17. //<11 ------------------ 根据LoadBalance(负载均衡) 选择一个合适的invoke>
  18. Invoker<T> invoker = loadbalance.select(invokers, getUrl(), invocation);
  19. //If the `invoker` is in the `selected` or invoker is unavailable && availablecheck is true, reselect.
  20. // 如果 selected中包含(优先判断) 或者 不可用&&availablecheck=true 则重试.
  21. if ((selected != null && selected.contains(invoker))
  22. || (!invoker.isAvailable() && getUrl() != null && availablecheck)) {
  23. try {
  24. //重选一个 Invoker 对象
  25. Invoker<T> rinvoker = reselect(loadbalance, invocation, invokers, selected, availablecheck);
  26. if (rinvoker != null) {
  27. invoker = rinvoker;
  28. } else {
  29. //Check the index of current selected invoker, if it's not the last one, choose the one at index+1.
  30. //看下第一次选的位置,如果不是最后,选+1位置.
  31. int index = invokers.indexOf(invoker);
  32. try {
  33. //Avoid collision
  34. // 最后在避免碰撞
  35. invoker = index < invokers.size() - 1 ? invokers.get(index + 1) : invokers.get(0);
  36. } catch (Exception e) {
  37. logger.warn(e.getMessage() + " may because invokers list dynamic change, ignore.", e);
  38. }
  39. }
  40. } catch (Throwable t) {
  41. logger.error("cluster reselect fail reason is :" + t.getMessage() + " if can not solve, you can set cluster.availablecheck=false in url", t);
  42. }
  43. }
  44. return invoker;
  45. }

11 AbstractLoadBalance#select

此方法是抽象方法,需要各种子类去实现

  1. /**
  2. * 抽象方法,下面的实现类来实现这个选择invoker 的方法
  3. * 各个负载均衡的类自行实现提供自定义的负载均衡策略。
  4. * @param invokers
  5. * @param url
  6. * @param invocation
  7. * @param <T>
  8. * @return
  9. */
  10. protected abstract <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation);

**12 RoundRobinLoadBalance 实现父类的抽象方法 **

  1. @Override
  2. protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  3. String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
  4. int length = invokers.size(); // Number of invokers
  5. int maxWeight = 0; // The maximum weight
  6. int minWeight = Integer.MAX_VALUE; // The minimum weight
  7. final LinkedHashMap<Invoker<T>, IntegerWrapper> invokerToWeightMap = new LinkedHashMap<Invoker<T>, IntegerWrapper>();
  8. int weightSum = 0;
  9. // 计算最小、最大权重,总的权重和。
  10. for (int i = 0; i < length; i++) {
  11. int weight = getWeight(invokers.get(i), invocation);
  12. maxWeight = Math.max(maxWeight, weight); // Choose the maximum weight
  13. minWeight = Math.min(minWeight, weight); // Choose the minimum weight
  14. if (weight > 0) {
  15. invokerToWeightMap.put(invokers.get(i), new IntegerWrapper(weight));
  16. weightSum += weight;
  17. }
  18. }
  19. // 计算最小、最大权重,总的权重和。
  20. AtomicPositiveInteger sequence = sequences.get(key);
  21. if (sequence == null) {
  22. sequences.putIfAbsent(key, new AtomicPositiveInteger());
  23. sequence = sequences.get(key);
  24. }
  25. // 获得当前顺序号,并递增 + 1
  26. int currentSequence = sequence.getAndIncrement();
  27. // 权重不相等,顺序根据权重分配
  28. if (maxWeight > 0 && minWeight < maxWeight) {
  29. int mod = currentSequence % weightSum;// 剩余权重
  30. for (int i = 0; i < maxWeight; i++) {// 循环最大权重
  31. for (Map.Entry<Invoker<T>, IntegerWrapper> each : invokerToWeightMap.entrySet()) {
  32. final Invoker<T> k = each.getKey();
  33. final IntegerWrapper v = each.getValue();
  34. // 剩余权重归 0 ,当前 Invoker 还有剩余权重,返回该 Invoker 对象
  35. if (mod == 0 && v.getValue() > 0) {
  36. return k;
  37. }
  38. // 若 Invoker 还有权重值,扣除它( value )和剩余权重( mod )。
  39. if (v.getValue() > 0) {
  40. v.decrement();
  41. mod--;
  42. }
  43. }
  44. }
  45. }
  46. // 权重相等,平均顺序获得
  47. // Round robin
  48. //<13 --------------------------->
  49. return invokers.get(currentSequence % length);
  50. }

14 FailoverClusterInvoker # doInvoke 方法

  1. /**
  2. * 实际逻辑很简单:循环,查找一个 Invoker 对象,进行调用,直到成功
  3. * @param invocation
  4. * @param invokers
  5. * @param loadbalance
  6. * @return
  7. * @throws RpcException
  8. */
  9. @Override
  10. @SuppressWarnings({"unchecked", "rawtypes"})
  11. public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  12. List<Invoker<T>> copyinvokers = invokers;
  13. // 检查copyinvokers即可用Invoker集合是否为空,如果为空,那么抛出异常
  14. checkInvokers(copyinvokers, invocation);
  15. String methodName = RpcUtils.getMethodName(invocation);
  16. // 得到最大可调用次数:最大可重试次数+1,默认最大可重试次数Constants.DEFAULT_RETRIES=2
  17. int len = getUrl().getMethodParameter(methodName, Constants.RETRIES_KEY, Constants.DEFAULT_RETRIES) + 1;
  18. if (len <= 0) {
  19. len = 1;
  20. }
  21. // retry loop.
  22. // 保存最后一次调用的异常
  23. RpcException le = null; // last exception.
  24. List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyinvokers.size()); // invoked invokers.
  25. Set<String> providers = new HashSet<String>(len);
  26. // failover机制核心实现:如果出现调用失败,那么重试其他服务器
  27. for (int i = 0; i < len; i++) {
  28. //Reselect before retry to avoid a change of candidate `invokers`.
  29. //NOTE: if `invokers` changed, then `invoked` also lose accuracy.
  30. // 重试时,进行重新选择,避免重试时invoker列表已发生变化.
  31. // 注意:如果列表发生了变化,那么invoked判断会失效,因为invoker示例已经改变
  32. if (i > 0) {
  33. checkWhetherDestroyed();
  34. // 根据Invocation调用信息从Directory中获取所有可用Invoker
  35. copyinvokers = list(invocation);
  36. // check again
  37. // 重新检查一下
  38. checkInvokers(copyinvokers, invocation);
  39. }
  40. // 根据负载均衡机制从copyinvokers中选择一个Invoker
  41. //< ------------------------- 下面将进行 invoker选择----------------------------------->
  42. Invoker<T> invoker = select(loadbalance, invocation, copyinvokers, invoked);
  43. // 保存每次调用的Invoker
  44. invoked.add(invoker);
  45. // 设置已经调用的 Invoker 集合,到 Context 中
  46. RpcContext.getContext().setInvokers((List) invoked);
  47. try {
  48. // RPC 调用得到 Result
  49. Result result = invoker.invoke(invocation);
  50. // 重试过程中,将最后一次调用的异常信息以 warn 级别日志输出
  51. if (le != null && logger.isWarnEnabled()) {
  52. logger.warn("Although retry the method " + methodName
  53. + " in the service " + getInterface().getName()
  54. + " was successful by the provider " + invoker.getUrl().getAddress()
  55. + ", but there have been failed providers " + providers
  56. + " (" + providers.size() + "/" + copyinvokers.size()
  57. + ") from the registry " + directory.getUrl().getAddress()
  58. + " on the consumer " + NetUtils.getLocalHost()
  59. + " using the dubbo version " + Version.getVersion() + ". Last error is: "
  60. + le.getMessage(), le);
  61. }
  62. return result;
  63. } catch (RpcException e) {
  64. // 如果是业务性质的异常,不再重试,直接抛出
  65. if (e.isBiz()) { // biz exception.
  66. throw e;
  67. }
  68. // 其他性质的异常统一封装成RpcException
  69. le = e;
  70. } catch (Throwable e) {
  71. le = new RpcException(e.getMessage(), e);
  72. } finally {
  73. providers.add(invoker.getUrl().getAddress());
  74. }
  75. }
  76. // 最大可调用次数用完还得到Result的话,抛出RpcException异常:重试了N次还是失败,并输出最后一次异常信息
  77. throw new RpcException(le.getCode(), "Failed to invoke the method "
  78. + methodName + " in the service " + getInterface().getName()
  79. + ". Tried " + len + " times of the providers " + providers
  80. + " (" + providers.size() + "/" + copyinvokers.size()
  81. + ") from the registry " + directory.getUrl().getAddress()
  82. + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version "
  83. + Version.getVersion() + ". Last error is: "
  84. + le.getMessage(), le.getCause() != null ? le.getCause() : le);
  85. }

以上是一个完成调用过程的源码分析 以及架构分析

Dubbo集群容错源码解析

** 我们 后面的分析重点就是Cluster的调用过程**

Cluster的作用

Cluster 将 Directory 中的多个 Invoker 伪装成一个 Invoker,对上层透明,伪装过程包含了容错逻辑,调用失败后,重试另一个

应对出错情况采取的策略,在某次出现错误后将会采用何种方式进行下次重试

集群模式 概括

下面对这些一个一个分析

Failover Cluster

失败自动切换,当出现失败,重试其它服务器 [1]。通常用于读操作,但重试会带来更长延迟。可通过 retries="2" 来设置重试次数(不含第一次)。

重试次数配置如下:

  1. <dubbo:service retries="2" />

  1. <dubbo:reference retries="2" />

  1. <dubbo:reference>
  2. <dubbo:method name="findFoo" retries="2" />
  3. </dubbo:reference>

核心调用类

  1. /**
  2. * 实际逻辑很简单:循环,查找一个 Invoker 对象,进行调用,直到成功
  3. * @param invocation
  4. * @param invokers
  5. * @param loadbalance
  6. * @return
  7. * @throws RpcException
  8. */
  9. @Override
  10. @SuppressWarnings({"unchecked", "rawtypes"})
  11. public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  12. List<Invoker<T>> copyinvokers = invokers;
  13. // 检查copyinvokers即可用Invoker集合是否为空,如果为空,那么抛出异常
  14. checkInvokers(copyinvokers, invocation);
  15. String methodName = RpcUtils.getMethodName(invocation);
  16. // 得到最大可调用次数:最大可重试次数+1,默认最大可重试次数Constants.DEFAULT_RETRIES=2
  17. int len = getUrl().getMethodParameter(methodName, Constants.RETRIES_KEY, Constants.DEFAULT_RETRIES) + 1;
  18. if (len <= 0) {
  19. len = 1;
  20. }
  21. // retry loop.
  22. // 保存最后一次调用的异常
  23. RpcException le = null; // last exception.
  24. List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyinvokers.size()); // invoked invokers.
  25. Set<String> providers = new HashSet<String>(len);
  26. // failover机制核心实现:如果出现调用失败,那么重试其他服务器
  27. for (int i = 0; i < len; i++) {
  28. //Reselect before retry to avoid a change of candidate `invokers`.
  29. //NOTE: if `invokers` changed, then `invoked` also lose accuracy.
  30. // 重试时,进行重新选择,避免重试时invoker列表已发生变化.
  31. // 注意:如果列表发生了变化,那么invoked判断会失效,因为invoker示例已经改变
  32. if (i > 0) {
  33. checkWhetherDestroyed();
  34. // 根据Invocation调用信息从Directory中获取所有可用Invoker
  35. copyinvokers = list(invocation);
  36. // check again
  37. // 重新检查一下
  38. checkInvokers(copyinvokers, invocation);
  39. }
  40. // 根据负载均衡机制从copyinvokers中选择一个Invoker
  41. //< ------------------------- 下面将进行 invoker选择----------------------------------->
  42. Invoker<T> invoker = select(loadbalance, invocation, copyinvokers, invoked);
  43. // 保存每次调用的Invoker
  44. invoked.add(invoker);
  45. // 设置已经调用的 Invoker 集合,到 Context 中
  46. RpcContext.getContext().setInvokers((List) invoked);
  47. try {
  48. // RPC 调用得到 Result
  49. Result result = invoker.invoke(invocation);
  50. // 重试过程中,将最后一次调用的异常信息以 warn 级别日志输出
  51. if (le != null && logger.isWarnEnabled()) {
  52. logger.warn("Although retry the method " + methodName
  53. + " in the service " + getInterface().getName()
  54. + " was successful by the provider " + invoker.getUrl().getAddress()
  55. + ", but there have been failed providers " + providers
  56. + " (" + providers.size() + "/" + copyinvokers.size()
  57. + ") from the registry " + directory.getUrl().getAddress()
  58. + " on the consumer " + NetUtils.getLocalHost()
  59. + " using the dubbo version " + Version.getVersion() + ". Last error is: "
  60. + le.getMessage(), le);
  61. }
  62. return result;
  63. } catch (RpcException e) {
  64. // 如果是业务性质的异常,不再重试,直接抛出
  65. if (e.isBiz()) { // biz exception.
  66. throw e;
  67. }
  68. // 其他性质的异常统一封装成RpcException
  69. le = e;
  70. } catch (Throwable e) {
  71. le = new RpcException(e.getMessage(), e);
  72. } finally {
  73. providers.add(invoker.getUrl().getAddress());
  74. }
  75. }
  76. // 最大可调用次数用完还得到Result的话,抛出RpcException异常:重试了N次还是失败,并输出最后一次异常信息
  77. throw new RpcException(le.getCode(), "Failed to invoke the method "
  78. + methodName + " in the service " + getInterface().getName()
  79. + ". Tried " + len + " times of the providers " + providers
  80. + " (" + providers.size() + "/" + copyinvokers.size()
  81. + ") from the registry " + directory.getUrl().getAddress()
  82. + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version "
  83. + Version.getVersion() + ". Last error is: "
  84. + le.getMessage(), le.getCause() != null ? le.getCause() : le);
  85. }

Failfast Cluster

快速失败,只发起一次调用,失败立即报错。通常用于非幂等性的写操作,比如新增记录。

  1. public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  2. // 检查 invokers集合
  3. checkInvokers(invokers, invocation);
  4. // 根据负载均衡机制从 invokers 中选择一个Invoker
  5. Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
  6. try {
  7. // RPC 调用得到 Result
  8. return invoker.invoke(invocation);
  9. } catch (Throwable e) {
  10. // 若是业务性质的异常,直接抛出
  11. if (e instanceof RpcException && ((RpcException) e).isBiz()) { // biz exception.
  12. throw (RpcException) e;
  13. }
  14. // 封装 RpcException 异常,并抛出
  15. throw new RpcException(e instanceof RpcException ? ((RpcException) e).getCode() : 0,
  16. "Failfast invoke providers " + invoker.getUrl() + " " + loadbalance.getClass().getSimpleName()
  17. + " select from all providers " + invokers + " for service " + getInterface().getName()
  18. + " method " + invocation.getMethodName() + " on consumer " + NetUtils.getLocalHost()
  19. + " use dubbo version " + Version.getVersion()
  20. + ", but no luck to perform the invocation. Last error is: " + e.getMessage(),
  21. e.getCause() != null ? e.getCause() : e);
  22. }
  23. }

Failsafe Cluster

失败安全,出现异常时,直接忽略。通常用于写入审计日志等操作。

  1. public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  2. try {
  3. // 检查 invokers 是否为空
  4. checkInvokers(invokers, invocation);
  5. // 根据负载均衡机制从 invokers 中选择一个Invoker
  6. Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
  7. // RPC 调用得到 Result
  8. return invoker.invoke(invocation);
  9. } catch (Throwable e) {
  10. // 打印异常日志
  11. logger.error("Failsafe ignore exception: " + e.getMessage(), e);
  12. // 忽略异常
  13. return new RpcResult(); // ignore
  14. }
  15. }

Failback Cluster

失败自动恢复,后台记录失败请求,定时重发。通常用于消息通知操作。

  1. /**
  2. * 当失败的时候会将invocation 添加到失败集合中
  3. * @param invocation 失败的invocation
  4. * @param router 对象自身
  5. */
  6. private void addFailed(Invocation invocation, AbstractClusterInvoker<?> router) {
  7. //如果定时任务未初始化,进行创建
  8. if (retryFuture == null) {
  9. synchronized (this) {
  10. if (retryFuture == null) {
  11. retryFuture = scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
  12. @Override
  13. public void run() {
  14. // collect retry statistics
  15. //创建的定时任务,会调用 #retryFailed() 方法,重试任务,发起 RCP 调用。
  16. try {
  17. retryFailed();
  18. } catch (Throwable t) { // Defensive fault tolerance
  19. logger.error("Unexpected error occur at collect statistic", t);
  20. }
  21. }
  22. }, RETRY_FAILED_PERIOD, RETRY_FAILED_PERIOD, TimeUnit.MILLISECONDS);
  23. }
  24. }
  25. }
  26. // 添加到失败任务
  27. failed.put(invocation, router);
  28. }
  29. /**
  30. * 重试任务,发起 RCP 调用
  31. */
  32. void retryFailed() {
  33. if (failed.size() == 0) {
  34. return;
  35. }
  36. // 循环重试任务,逐个调用
  37. for (Map.Entry<Invocation, AbstractClusterInvoker<?>> entry : new HashMap<>(failed).entrySet()) {
  38. Invocation invocation = entry.getKey();
  39. Invoker<?> invoker = entry.getValue();
  40. try {
  41. // RPC 调用得到 Result
  42. invoker.invoke(invocation);
  43. // 移除失败任务
  44. failed.remove(invocation);
  45. } catch (Throwable e) {
  46. logger.error("Failed retry to invoke method " + invocation.getMethodName() + ", waiting again.", e);
  47. }
  48. }
  49. }
  50. @Override
  51. protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  52. try {
  53. checkInvokers(invokers, invocation);
  54. // 根据负载均衡机制从 invokers 中选择一个Invoker
  55. Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
  56. // RPC 调用得到 Result
  57. return invoker.invoke(invocation);
  58. } catch (Throwable e) {
  59. logger.error("Failback to invoke method " + invocation.getMethodName() + ", wait for retry in background. Ignored exception: "
  60. + e.getMessage() + ", ", e);
  61. // 添加到失败任务
  62. addFailed(invocation, this);
  63. return new RpcResult(); // ignore
  64. }
  65. }

Forking Cluster

并行调用多个服务器,只要一个成功即返回。通常用于实时性要求较高的读操作,但需要浪费更多服务资源。可通过 forks="2" 来设置最大并行数。

  1. public Result doInvoke(final Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  2. try {
  3. // 检查 invokers 是否为空
  4. checkInvokers(invokers, invocation);
  5. // 保存选择的 Invoker 集合
  6. final List<Invoker<T>> selected;
  7. // 得到最大并行数,默认为 Constants.DEFAULT_FORKS = 2
  8. final int forks = getUrl().getParameter(Constants.FORKS_KEY, Constants.DEFAULT_FORKS);
  9. // 获得调用超时时间,默认为 DEFAULT_TIMEOUT = 1000 毫秒
  10. final int timeout = getUrl().getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
  11. //如果最大并行数小于 0 或者大于invokers的数量,直接调用invokers
  12. if (forks <= 0 || forks >= invokers.size()) {
  13. selected = invokers;
  14. } else {
  15. // 循环,根据负载均衡机制从 invokers,中选择一个个Invoker ,从而组成 Invoker 集合。
  16. // 注意,因为增加了排重逻辑,所以不能保证获得的 Invoker 集合的大小,小于最大并行数
  17. selected = new ArrayList<>();
  18. for (int i = 0; i < forks; i++) {
  19. // TODO. Add some comment here, refer chinese version for more details.
  20. // 在invoker列表(排除selected)后,如果没有选够,则存在重复循环问题.见select实现.
  21. Invoker<T> invoker = select(loadbalance, invocation, invokers, selected);
  22. if (!selected.contains(invoker)) {
  23. //Avoid add the same invoker several times.
  24. selected.add(invoker);
  25. }
  26. }
  27. }
  28. // 设置已经调用的 Invoker 集合,到 Context 中
  29. RpcContext.getContext().setInvokers((List) selected);
  30. // 异常计数器
  31. final AtomicInteger count = new AtomicInteger();
  32. // 创建阻塞队列
  33. final BlockingQueue<Object> ref = new LinkedBlockingQueue<>();
  34. // 循环 selected 集合,提交线程池,发起 RPC 调用
  35. for (final Invoker<T> invoker : selected) {
  36. executor.execute(new Runnable() {
  37. @Override
  38. public void run() {
  39. try {
  40. // RPC 调用,获得 Result 结果
  41. Result result = invoker.invoke(invocation);
  42. // 添加 Result 到 `ref` 阻塞队列
  43. ref.offer(result);
  44. } catch (Throwable e) {
  45. // 异常计数器 + 1
  46. int value = count.incrementAndGet();
  47. // 若 RPC 调用结果都是异常,则添加异常到 `ref` 阻塞队列
  48. if (value >= selected.size()) {
  49. ref.offer(e);
  50. }
  51. }
  52. }
  53. });
  54. }
  55. try {
  56. // 从 `ref` 队列中,阻塞等待结果
  57. Object ret = ref.poll(timeout, TimeUnit.MILLISECONDS);
  58. // 若是异常结果,抛出 RpcException 异常
  59. if (ret instanceof Throwable) {
  60. Throwable e = (Throwable) ret;
  61. throw new RpcException(e instanceof RpcException ? ((RpcException) e).getCode() : 0, "Failed to forking invoke provider " + selected + ", but no luck to perform the invocation. Last error is: " + e.getMessage(), e.getCause() != null ? e.getCause() : e);
  62. }
  63. // 若是正常结果,直接返回
  64. return (Result) ret;
  65. } catch (InterruptedException e) {
  66. throw new RpcException("Failed to forking invoke provider " + selected + ", but no luck to perform the invocation. Last error is: " + e.getMessage(), e);
  67. }
  68. } finally {
  69. // clear attachments which is binding to current thread.
  70. RpcContext.getContext().clearAttachments();
  71. }
  72. }

Broadcast Cluster

广播调用所有提供者,逐个调用,任意一台报错则报错 [2]。通常用于通知所有提供者更新缓存或日志等本地资源信息

  1. public Result doInvoke(final Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  2. // 检查 invokers 即可用Invoker集合是否为空,如果为空,那么抛出异常
  3. checkInvokers(invokers, invocation);
  4. // 设置已经调用的 Invoker 集合,到 Context 中
  5. RpcContext.getContext().setInvokers((List) invokers);
  6. // 保存最后一次调用的异常
  7. RpcException exception = null;
  8. // 保存最后一次调用的结果
  9. Result result = null;
  10. // 循环候选的 Invoker 集合,调用所有 Invoker 对象。
  11. for (Invoker<T> invoker : invokers) {
  12. try {
  13. // 发起 RPC 调用
  14. result = invoker.invoke(invocation);
  15. } catch (RpcException e) {
  16. exception = e;
  17. logger.warn(e.getMessage(), e);
  18. } catch (Throwable e) {
  19. // 封装成 RpcException 异常
  20. exception = new RpcException(e.getMessage(), e);
  21. logger.warn(e.getMessage(), e);
  22. }
  23. }
  24. // 若存在一个异常,抛出该异常
  25. if (exception != null) {
  26. throw exception;
  27. }
  28. return result;
  29. }

Available Cluster

遍历所有从Directory中list出来的Invoker集合,调用第一个isAvailable()Invoker,只发起一次调用,失败立即报错。

isAvailable()判断逻辑如下--Client处理连接状态,且不是READONLY:

  1. @Override
  2. public boolean isAvailable() {
  3. if (!super.isAvailable())
  4. return false;
  5. for (ExchangeClient client : clients){
  6. if (client.isConnected() && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)){
  7. //cannot write == not Available ?
  8. return true ;
  9. }
  10. }
  11. return false;
  12. }

参考文章

dubbo源码解析-集群容错架构设计

Dubbo 官方文档 集群容错

dubbo源码解析-cluster

13.dubbo源码-集群容错

dubbo源码解析五 --- 集群容错架构设计与原理分析的更多相关文章

  1. dubbo源码阅读之集群(故障处理策略)

    dubbo集群概述 dubbo集群功能的切入点在ReferenceConfig.createProxy方法以及Protocol.refer方法中. 在ReferenceConfig.createPro ...

  2. 基于.NetCore的Redis5.0.3(最新版)快速入门、源码解析、集群搭建与SDK使用【原创】

    1.[基础]redis能带给我们什么福利 Redis(Remote Dictionary Server)官网:https://redis.io/ Redis命令:https://redis.io/co ...

  3. Ejabberd源码解析前奏--集群

    一.如何工作 一个XMPP域是由一个或多个ejabberd节点伺服的. 这些节点可能运行在通过网络连接的不同机器上. 它们都必须有能力连接到所有其它节点的4369端口, 并且必须有相同的 magic ...

  4. Dubbo 源码解析四 —— 负载均衡LoadBalance

    欢迎来我的 Star Followers 后期后继续更新Dubbo别的文章 Dubbo 源码分析系列之一环境搭建 Dubbo 入门之二 --- 项目结构解析 Dubbo 源码分析系列之三 -- 架构原 ...

  5. dubbo源码解析-zookeeper创建节点

    前言 在之前dubbo源码解析-本地暴露中的前言部分提到了两道高频的面试题,其中一道dubbo中zookeeper做注册中心,如果注册中心集群都挂掉,那发布者和订阅者还能通信吗?在上周的dubbo源码 ...

  6. Dubbo 系列(07-5)集群容错 - Mock

    Dubbo 系列(07-5)集群容错 - Mock [toc] Spring Cloud Alibaba 系列目录 - Dubbo 篇 1. 背景介绍 相关文档推荐: Dubbo 实战 - 服务降级 ...

  7. Dubbo 系列(07-2)集群容错 - 服务路由

    目录 Dubbo 系列(07-2)集群容错 - 服务路由 1. 背景介绍 1.1 继承体系 1.2 SPI 2. 源码分析 2.1 创建路由规则 2.2 RouteChain 2.3 条件路由 Dub ...

  8. Dubbo 系列(07-4)集群容错 - 集群

    BDubbo 系列(07-4)集群容错 - 集群 [toc] Spring Cloud Alibaba 系列目录 - Dubbo 篇 1. 背景介绍 相关文档推荐: Dubbo 集群容错 - 实战 D ...

  9. Dubbo 系列(07-3)集群容错 - 负载均衡

    目录 Dubbo 系列(07-3)集群容错 - 负载均衡 Spring Cloud Alibaba 系列目录 - Dubbo 篇 1. 背景介绍 1.1 负载均衡算法 1.2 继承体系 2. 源码分析 ...

随机推荐

  1. 将Paul替换成Ringo

    <!DOCTYPE html><html><head lang="en">  <meta charset="UTF-8" ...

  2. 多线程.Thread.Sleep方法

    多线程执行中,调用Thread.Sleep()方法 分情况: 1. 单核的情况下 是把当前正在工作的主线程停止(也就是从把线程变成非工作线程). 其他需要工作的线程来争夺CPU这个闲下来的核.谁争夺到 ...

  3. admob sdk

    https://support.google.com/admob/answer/2993059?hl=zh-Hans admob sample http://china.inmobi.com/sdk/ ...

  4. php中ob_get_contents、curl_multi_init、curl_init多线程下载远程图片并保存记录

    php中三种方式测试图片下载效率 原文共24张不同图,每张大小在500K以上 使用时注意调整传入数组格式以及需要下载时保存地址的路径格式等 这三种方式无需额外安装扩展,方便快捷易操作[虽然效率看结果没 ...

  5. Python之路【第二篇】计算机组成

    硬件组成:输入单元.输出单元.中央处理单元.存储单元 南桥:I/O操作 北桥:CPU操作   0/1的单位称为bit(位) bit是计算机中能识别的最小单位. 字节是计算机中最小的存储单位. 8bit ...

  6. Postman导出Api文档

    一.最近离职要把做搞过的接口整理成文档,查了查postman好像不支持导出文档,于是写了个工具类,供大家参考! 前提你要先把postman里的接口导出来 如图: 二.所用到的包(主要Json相关的包) ...

  7. Java-异常初步练习

    案例一: package com.esandinfo; /** * 自定义一个Exception类 */ class MyCustomException extends RuntimeExceptio ...

  8. 【高速接口-RapidIO】5、Xilinx RapidIO核例子工程源码分析

    提示:本文的所有图片如果不清晰,请在浏览器的新建标签中打开或保存到本地打开 一.软件平台与硬件平台 软件平台: 操作系统:Windows 8.1 64-bit 开发套件:Vivado2015.4.2 ...

  9. Java中最常用的集合类框架之 HashMap

    一.HashMap的概述 HashMap可以说是Java中最常用的集合类框架之一,是Java语言中非常典型的数据结构.      HashMap是基于哈希表的Map接口实现的,此实现提供所有可选的映射 ...

  10. 盘点和反思在微信的阴影下艰难求生的移动端IM应用

    本文原作者:李越,由银杏财经原创发布,本次内容改动. 1.前言 上线一周完成1.5亿元融资,上线10天总激活用户数超400万,8月29日单日新增用户超100万,这是子弹短信交出的最新成绩单(详见< ...