容错机制

  • Failover:当出现失败时,会重试其他服务器。用户可以通过retries=”2” 设置重试次数。这是Dubbo的默认容错机制,会对请求做负载均衡。通常使用在读操作或幕等的写操作上, 但在进行重试的时候,如果系统的并发比较高,那么下流的机器压力将会很大。可以通过 retries 属性来设置最大重试次数。可以设置在 dubbo: reference 标签上,也可以设置在细粒度的方法标签 dubbo:method 上。
  • Failfast :快速失败,当请求失败后,快速返回异常结果,不做任何重试。该容错机制会对请求做负载均衡,通常使用在非幕等接口的调用上。该机制受网络抖动的影响较大。
  • Failsafe :当出现异常时,直接忽略异常。会对请求做负载均衡。通常使用在“佛系”调用场景, 不关心调用是否成功,不抛异常影响主线程业务逻辑的执行。
  • Fallback:请求失败,会将失败的请求记录到一个队列,然后由一个定时任务去执行重试,请求会做负载均衡。这种容错机制适合用在最终一致性的业务场景。
  • Forking :同时调用多个相同的服务,只要其中一个返回,则立即返回结果。用户可以配置最大请求的并行数参数来确定最大并行调用的服务数量。通常使用在对接口实时性要求极高的调用上,但也会浪费更多的资源。通过 forks=”最大并行数” 属性来设置最大并行数。假设设置的 forks 数为 n 可用的服务数为 v,当 n<v 时,既可用的服务数大于配置的并行数,则并行请求 n 个服务。当 n >v 时,即可用的服务数小于配置的并行数,则请求所有可用的服务 v。
  • Broadcast :广播调用所有可用的服务,任意一个节点报错则报错。由于是广播,因此请求不需要做负载均衡。通常用于服务状态更新后的广播。
  • Mock:提供调用失败时,返回伪造的响应结果。也可以直接强制返回伪造的结果,不会发起远程调用。这就是服务降级。
  • Available :请求不会做负载均衡,遍历所有服务列表,找到第一个可用的节点, 直接请求并返回结果。如果没有可用的节点,则直接抛出异常。
  • Mergeable :Mergeable可以自动把多个节点请求得到的结果进行合并。

源码阅读

需要记住的是:不论是服务降级,服务路由,还是集群容错,以及负载均衡,它们都是发生在调用提供者方法的这个地方,也就是远程调用。所以直接找InvokerInvocationHandler 类

13.Dubbo集群容错源码阅读 - 图1

  1. 同理,只要发起远程RPC调用,不论怎么执行,都会执行这两个中的一个。跟踪这里的 **AbstractClusterInvoker** 类中的 **invoke** 实现

13.Dubbo集群容错源码阅读 - 图2

13.Dubbo集群容错源码阅读 - 图3

Failover 策略

FailoverClusterInvoker.java

  1. public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  2. // 先复制一份Invoker
  3. List<Invoker<T>> copyInvokers = invokers;
  4. // 校验传入的invoke是否为空,为空则抛RPCException
  5. checkInvokers(copyInvokers, invocation);
  6. // 从Invoker中获取调用的方法名称
  7. String methodName = RpcUtils.getMethodName(invocation);
  8. // 从URL中解析出配置,重试的最大次数
  9. int len = getUrl().getMethodParameter(methodName, RETRIES_KEY, DEFAULT_RETRIES) + 1;
  10. // 如果没有配置则默认为1次
  11. if (len <= 0) {
  12. len = 1;
  13. }
  14. // 记录调用过程中出现的异常
  15. RpcException le = null;
  16. // 记录调用的节点,然后去做负载均衡,思路就是下次做负载的时候排除这个节点。因为这个节点已经调用过了
  17. List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyInvokers.size()); // invoked invokers.
  18. Set<String> providers = new HashSet<String>(len);
  19. // 根据上面的次数来执行循环重试
  20. for (int i = 0; i < len; i++) {
  21. // 当前重试不是第一次
  22. if (i > 0) {
  23. // 看当前invoke是否已被销毁
  24. checkWhetherDestroyed();
  25. // 获取最新的invokers列表
  26. copyInvokers = list(invocation);
  27. // 获取完后在检查一遍 为空校验
  28. checkInvokers(copyInvokers, invocation);
  29. }
  30. // 负载均衡
  31. Invoker<T> invoker = select(loadbalance, invocation, copyInvokers, invoked);
  32. invoked.add(invoker);
  33. RpcContext.getContext().setInvokers((List) invoked);
  34. try { // 远程调用
  35. Result result = invoker.invoke(invocation);
  36. if (le != null && logger.isWarnEnabled()) {
  37. logger.warn("Although retry the method " + methodName
  38. + " in the service " + getInterface().getName()
  39. + " was successful by the provider " + invoker.getUrl().getAddress()
  40. + ", but there have been failed providers " + providers
  41. + " (" + providers.size() + "/" + copyInvokers.size()
  42. + ") from the registry " + directory.getUrl().getAddress()
  43. + " on the consumer " + NetUtils.getLocalHost()
  44. + " using the dubbo version " + Version.getVersion() + ". Last error is: "
  45. + le.getMessage(), le);
  46. }
  47. // 只要不执行到这个地方就会执行重试,当重试次数上限就抛出最下面那个RPCException异常
  48. // 调用成功,返回结果
  49. return result;
  50. } catch (RpcException e) {
  51. if (e.isBiz()) { // biz exception.
  52. throw e;
  53. }
  54. le = e;
  55. } catch (Throwable e) {
  56. le = new RpcException(e.getMessage(), e);
  57. } finally {
  58. providers.add(invoker.getUrl().getAddress());
  59. }
  60. }
  61. // 已执行最大重试基础,还是失败,抛出异常。
  62. throw new RpcException(le.getCode(), "Failed to invoke the method "
  63. + methodName + " in the service " + getInterface().getName()
  64. + ". Tried " + len + " times of the providers " + providers
  65. + " (" + providers.size() + "/" + copyInvokers.size()
  66. + ") from the registry " + directory.getUrl().getAddress()
  67. + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version "
  68. + Version.getVersion() + ". Last error is: "
  69. + le.getMessage(), le.getCause() != null ? le.getCause() : le);
  70. }

Failfast 策略

FailfastClusterInvoker.java

  1. public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  2. // 为空校验
  3. checkInvokers(invokers, invocation);
  4. // 负载均衡出一个调用节点
  5. Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
  6. try {
  7. // 执行调用
  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. throw new RpcException(e instanceof RpcException ? ((RpcException) e).getCode() : 0,
  15. "Failfast invoke providers " + invoker.getUrl() + " " + loadbalance.getClass().getSimpleName()
  16. + " select from all providers " + invokers + " for service " + getInterface().getName()
  17. + " method " + invocation.getMethodName() + " on consumer " + NetUtils.getLocalHost()
  18. + " use dubbo version " + Version.getVersion()
  19. + ", but no luck to perform the invocation. Last error is: " + e.getMessage(),
  20. e.getCause() != null ? e.getCause() : e);
  21. }
  22. }

Failsafe 策略

FailsafeClusterInvoker.java

  1. public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  2. try {
  3. // 为空校验
  4. checkInvokers(invokers, invocation);
  5. // 负载均衡出调用的节点
  6. Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
  7. // 进行调用
  8. return invoker.invoke(invocation);
  9. } catch (Throwable e) {
  10. // 吃掉异常。返回一个AsyncRpcResult结果集
  11. logger.error("Failsafe ignore exception: " + e.getMessage(), e);
  12. return AsyncRpcResult.newDefaultAsyncResult(null, null, invocation); // ignore
  13. }
  14. }

Fallback 策略

FailbackClusterInvoker.java

  1. protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  2. Invoker<T> invoker = null;
  3. try {
  4. // 为空校验
  5. checkInvokers(invokers, invocation);
  6. // 负载均衡出一个调用节点
  7. invoker = select(loadbalance, invocation, invokers, null);
  8. // 发起调用
  9. return invoker.invoke(invocation);
  10. } catch (Throwable e) {
  11. logger.error("Failback to invoke method " + invocation.getMethodName() + ", wait for retry in background. Ignored exception: "
  12. + e.getMessage() + ", ", e);
  13. // 发生异常是,定时任务执行重试
  14. addFailed(loadbalance, invocation, invokers, invoker);
  15. return AsyncRpcResult.newDefaultAsyncResult(null, null, invocation); // ignore
  16. }
  17. }
  18. private void addFailed(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, Invoker<T> lastInvoker) {
  19. // 是否有任务,如果没有则创建。有 则复用之前创建好的任务
  20. if (failTimer == null) {
  21. synchronized (this) {
  22. if (failTimer == null) {
  23. failTimer = new HashedWheelTimer(
  24. new NamedThreadFactory("failback-cluster-timer", true),
  25. 1,
  26. TimeUnit.SECONDS, 32, failbackTasks);
  27. }
  28. }
  29. }
  30. // 初始化任务线程
  31. RetryTimerTask retryTimerTask = new RetryTimerTask(loadbalance, invocation, invokers, lastInvoker, retries, RETRY_FAILED_PERIOD);
  32. try {
  33. // 创建定时任务并添加到队列
  34. failTimer.newTimeout(retryTimerTask, RETRY_FAILED_PERIOD, TimeUnit.SECONDS);
  35. } catch (Throwable e) {
  36. logger.error("Failback background works error,invocation->" + invocation + ", exception: " + e.getMessage());
  37. }
  38. }
  39. private class RetryTimerTask implements TimerTask {
  40. private final Invocation invocation;
  41. private final LoadBalance loadbalance;
  42. private final List<Invoker<T>> invokers;
  43. private final int retries;
  44. private final long tick;
  45. private Invoker<T> lastInvoker;
  46. private int retryTimes = 0;
  47. RetryTimerTask(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, Invoker<T> lastInvoker, int retries, long tick) {
  48. this.loadbalance = loadbalance; // 负载均衡算法
  49. this.invocation = invocation; // 远程RPC调用的信息
  50. this.invokers = invokers; // 集群节点服务列表
  51. this.retries = retries; // 设置的最大重试次数
  52. this.tick = tick; // 重试间隔时间 秒
  53. this.lastInvoker=lastInvoker; // 最后一次调用的时候使用的服务节点
  54. }
  55. @Override
  56. public void run(Timeout timeout) {
  57. try {
  58. // 轮询出调用的节点
  59. Invoker<T> retryInvoker = select(loadbalance, invocation, invokers, Collections.singletonList(lastInvoker));
  60. // 将本地选出的服务节点记录成最后一次调用的服务节点
  61. lastInvoker = retryInvoker;
  62. retryInvoker.invoke(invocation);
  63. } catch (Throwable e) {
  64. logger.error("Failed retry to invoke method " + invocation.getMethodName() + ", waiting again.", e);
  65. if ((++retryTimes) >= retries) {
  66. // 重试次数已经上限
  67. logger.error("Failed retry times exceed threshold (" + retries + "), We have to abandon, invocation->" + invocation);
  68. } else {
  69. // 再添加一次任务
  70. rePut(timeout);
  71. }
  72. }
  73. }
  74. private void rePut(Timeout timeout) {
  75. if (timeout == null) {
  76. return;
  77. }
  78. Timer timer = timeout.timer();
  79. if (timer.isStop() || timeout.isCancelled()) {
  80. return;
  81. }
  82. timer.newTimeout(timeout.task(), tick, TimeUnit.SECONDS);
  83. }
  84. }

Available 策略

AvailableClusterInvoker.java

  1. public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  2. // 遍历所有的服务节点列表
  3. for (Invoker<T> invoker : invokers) {
  4. // 只要是可用的服务就进行调用。不会进行负载均衡
  5. if (invoker.isAvailable()) {
  6. return invoker.invoke(invocation);
  7. }
  8. }
  9. throw new RpcException("No provider available in " + invokers);
  10. }

Broadcast 策略

BroadcastClusterInvoker.java

  1. public Result doInvoke(final Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  2. // 为空校验
  3. checkInvokers(invokers, invocation);
  4. // 记录RPC的上下文消息
  5. RpcContext.getContext().setInvokers((List) invokers);
  6. RpcException exception = null;
  7. Result result = null;
  8. // 遍历整个服务节点列表
  9. for (Invoker<T> invoker : invokers) {
  10. try {
  11. // 进行调用
  12. result = invoker.invoke(invocation);
  13. //如果在调用的过程中出现异常则直接抛出
  14. } catch (RpcException e) {
  15. exception = e;
  16. logger.warn(e.getMessage(), e);
  17. } catch (Throwable e) {
  18. exception = new RpcException(e.getMessage(), e);
  19. logger.warn(e.getMessage(), e);
  20. }
  21. }
  22. if (exception != null) {
  23. throw exception;
  24. }
  25. return result;
  26. }

Forking 策略

ForkingClusterInvoker.java

  1. public Result doInvoke(final Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  2. try {
  3. // 为空校验
  4. checkInvokers(invokers, invocation);
  5. final List<Invoker<T>> selected;
  6. // 从URL中解析配置,如果URL中没有配置则返回默认值。 (最大并行数,超时时间)
  7. final int forks = getUrl().getParameter(FORKS_KEY, DEFAULT_FORKS);
  8. final int timeout = getUrl().getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT);
  9. // 假设用户设置最大的并行数为: N 服务节点为: V
  10. // 则: N <=0 或者 N >= V。则最终调用的Invoker只能是N个
  11. if (forks <= 0 || forks >= invokers.size()) {
  12. selected = invokers;
  13. } else {
  14. // N <= V
  15. // 初始化一个列表, 经过负载均衡选出invoker并加入到列表中
  16. selected = new ArrayList<>();
  17. for (int i = 0; i < forks; i++) {
  18. Invoker<T> invoker = select(loadbalance, invocation, invokers, selected);
  19. // 监测选出来的invoker是否已经存在于列表中
  20. if (!selected.contains(invoker)) {
  21. selected.add(invoker);
  22. }
  23. }
  24. }
  25. RpcContext.getContext().setInvokers((List) selected);
  26. // 初始化一个异常计数器
  27. final AtomicInteger count = new AtomicInteger();
  28. // 初始化一个阻塞队列,用于记录并行调用的结果。
  29. final BlockingQueue<Object> ref = new LinkedBlockingQueue<>();
  30. // 执行调用
  31. for (final Invoker<T> invoker : selected) {
  32. executor.execute(new Runnable() {
  33. @Override
  34. public void run() {
  35. try {
  36. Result result = invoker.invoke(invocation);
  37. // 成功将调用结果添加到队列
  38. ref.offer(result);
  39. } catch (Throwable e) {
  40. // 如果失败次数 >= V。 (说明是最后一个服务节点了,才会将异常记录到队列中)
  41. int value = count.incrementAndGet();
  42. if (value >= selected.size()) {
  43. // 失败将异常记录到队列
  44. ref.offer(e);
  45. }
  46. }
  47. }
  48. });
  49. }
  50. try {
  51. // 在指定时间(秒)后弹出队列的首个元素
  52. Object ret = ref.poll(timeout, TimeUnit.MILLISECONDS);
  53. // 如果是异常则抛出。RPCException会产生降级
  54. if (ret instanceof Throwable) {
  55. Throwable e = (Throwable) ret;
  56. 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);
  57. }
  58. // 否则则返回调用结果
  59. return (Result) ret;
  60. } catch (InterruptedException e) {
  61. throw new RpcException("Failed to forking invoke provider " + selected + ", but no luck to perform the invocation. Last error is: " + e.getMessage(), e);
  62. }
  63. } finally {
  64. // clear attachments which is binding to current thread.
  65. RpcContext.getContext().clearAttachments();
  66. }
  67. }