经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » 编程经验 » 查看文章
警惕看不见的重试机制:为什么使用RPC必须考虑幂等性
来源:cnblogs  作者:JAVA前线  时间:2023/5/26 9:53:49  对本文有异议

0 文章概述

在RPC场景中因为重试或者没有实现幂等机制而导致的重复数据问题,必须引起大家重视,有可能会造成例如一次购买创建多笔订单,一条通知信息被发送多次等问题,这是技术人员必须面对和解决的问题。

有人可能会说:当调用失败时程序并没有显示重试,为什么还会产生重复数据问题呢?这是因为即使没有显示重试,RPC框架在集群容错机制中自动进行了重试,这个问题必须引起关注。

本文我们以DUBBO框架为例分析为什么重试,怎么做重试,怎么做幂等三个问题。


看不见的重试机制.jpeg


1 为什么重试

如果简单对一个RPC交互过程进行分类,我们可以分为三类:响应成功、响应失败、没有响应。


RPC3.jpg


对于响应成功和响应失败这两种情况,消费者很好处理。因为响应信息明确,所以只要根据响应信息,继续处理成功或者失败逻辑即可。但是没有响应这种场景比较难处理,这是因为没有响应可能包含以下情况:

  1. (1) 生产者根本没有接收到请求
  2. (2) 生产者接收到请求并且已处理成功,但是消费者没有接收到响应
  3. (3) 生产者接收到请求并且已处理失败,但是消费者没有接收到响应

假设你是一名RPC框架设计者,究竟是选择重试还是放弃调用呢?其实最终如何选择取决于业务特性,有的业务本身就具有幂等性,但是有的业务不能允许重试否则会造成重复数据。

那么谁对业务特性最熟悉呢?答案是消费者,因为消费者作为调用方肯定最熟悉自身业务,所以RPC框架只要提供一些策略供消费者选择即可。


2 怎么做重试

2.1 集群容错策略

DUBBO作为一款优秀RPC框架,提供了如下集群容错策略供消费者选择:

  1. Failover: 故障转移
  2. Failfast: 快速失败
  3. Failsafe: 安全失败
  4. Failback: 异步重试
  5. Forking: 并行调用
  6. Broadcast:广播调用

(1) Failover

故障转移策略。作为默认策略当消费发生异常时通过负载均衡策略再选择一个生产者节点进行调用,直到达到重试次数

(2) Failfast

快速失败策略。消费者只消费一次服务,当发生异常时则直接抛出

(3) Failsafe

安全失败策略。消费者只消费一次服务,如果消费失败则包装一个空结果,不抛出异常

(4) Failback

异步重试策略。当消费发生异常时返回一个空结果,失败请求将会进行异步重试。如果重试超过最大重试次数还不成功,放弃重试并不抛出异常

(5) Forking

并行调用策略。消费者通过线程池并发调用多个生产者,只要有一个成功就算成功

(6) Broadcast

广播调用策略。消费者遍历调用所有生产者节点,任何一个出现异常则抛出异常


2.2 源码分析

2.2.1 Failover

Failover故障转移策略作为默认策略,当消费发生异常时通过负载均衡策略再选择一个生产者节点进行调用,直到达到重试次数。即使业务代码没有显示重试,也有可能多次执行消费逻辑从而造成重复数据:

  1. public class FailoverClusterInvoker<T> extends AbstractClusterInvoker<T> {
  2. public FailoverClusterInvoker(Directory<T> directory) {
  3. super(directory);
  4. }
  5. @Override
  6. public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  7. // 所有生产者Invokers
  8. List<Invoker<T>> copyInvokers = invokers;
  9. checkInvokers(copyInvokers, invocation);
  10. String methodName = RpcUtils.getMethodName(invocation);
  11. // 获取重试次数
  12. int len = getUrl().getMethodParameter(methodName, Constants.RETRIES_KEY, Constants.DEFAULT_RETRIES) + 1;
  13. if (len <= 0) {
  14. len = 1;
  15. }
  16. RpcException le = null;
  17. // 已经调用过的生产者
  18. List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyInvokers.size());
  19. Set<String> providers = new HashSet<String>(len);
  20. // 重试直到达到最大次数
  21. for (int i = 0; i < len; i++) {
  22. if (i > 0) {
  23. // 如果当前实例被销毁则抛出异常
  24. checkWhetherDestroyed();
  25. // 根据路由策略选出可用生产者Invokers
  26. copyInvokers = list(invocation);
  27. // 重新检查
  28. checkInvokers(copyInvokers, invocation);
  29. }
  30. // 负载均衡选择一个生产者Invoker
  31. Invoker<T> invoker = select(loadbalance, invocation, copyInvokers, invoked);
  32. invoked.add(invoker);
  33. RpcContext.getContext().setInvokers((List) invoked);
  34. try {
  35. // 服务消费发起远程调用
  36. Result result = invoker.invoke(invocation);
  37. if (le != null && logger.isWarnEnabled()) {
  38. logger.warn("Although retry the method " + methodName + " in the service " + getInterface().getName() + " was successful by the provider " + invoker.getUrl().getAddress() + ", but there have been failed providers " + providers + " (" + providers.size() + "/" + copyInvokers.size() + ") from the registry " + directory.getUrl().getAddress() + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version " + Version.getVersion() + ". Last error is: " + le.getMessage(), le);
  39. }
  40. // 有结果则返回
  41. return result;
  42. } catch (RpcException e) {
  43. // 业务异常直接抛出
  44. if (e.isBiz()) {
  45. throw e;
  46. }
  47. le = e;
  48. } catch (Throwable e) {
  49. // RpcException不抛出继续重试
  50. le = new RpcException(e.getMessage(), e);
  51. } finally {
  52. // 保存已经访问过的生产者
  53. providers.add(invoker.getUrl().getAddress());
  54. }
  55. }
  56. throw new RpcException(le.getCode(), "Failed to invoke the method " + methodName + " in the service " + getInterface().getName() + ". Tried " + len + " times of the providers " + providers + " (" + providers.size() + "/" + copyInvokers.size() + ") from the registry " + directory.getUrl().getAddress() + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version " + Version.getVersion() + ". Last error is: " + le.getMessage(), le.getCause() != null ? le.getCause() : le);
  57. }
  58. }

消费者调用生产者节点A发生RpcException异常时(例如超时异常),在未达到最大重试次数之前,消费者会通过负载均衡策略再次选择其它生产者节点消费。试想如果生产者节点A其实已经处理成功了,但是没有及时将成功结果返回给消费者,那么再次重试可能就会造成重复数据问题。


2.2.2 Failfast

快速失败策略。消费者只消费一次服务,当发生异常时则直接抛出,不会进行重试:

  1. public class FailfastClusterInvoker<T> extends AbstractClusterInvoker<T> {
  2. public FailfastClusterInvoker(Directory<T> directory) {
  3. super(directory);
  4. }
  5. @Override
  6. public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  7. // 检查生产者Invokers是否合法
  8. checkInvokers(invokers, invocation);
  9. // 负载均衡选择一个生产者Invoker
  10. Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
  11. try {
  12. // 服务消费发起远程调用
  13. return invoker.invoke(invocation);
  14. } catch (Throwable e) {
  15. // 服务消费失败不重试直接抛出异常
  16. if (e instanceof RpcException && ((RpcException) e).isBiz()) {
  17. throw (RpcException) e;
  18. }
  19. throw new RpcException(e instanceof RpcException ? ((RpcException) e).getCode() : 0,
  20. "Failfast invoke providers " + invoker.getUrl() + " " + loadbalance.getClass().getSimpleName()
  21. + " select from all providers " + invokers + " for service " + getInterface().getName()
  22. + " method " + invocation.getMethodName() + " on consumer " + NetUtils.getLocalHost()
  23. + " use dubbo version " + Version.getVersion()
  24. + ", but no luck to perform the invocation. Last error is: " + e.getMessage(),
  25. e.getCause() != null ? e.getCause() : e);
  26. }
  27. }
  28. }

2.2.3 Failsafe

安全失败策略。消费者只消费一次服务,如果消费失败则包装一个空结果,不抛出异常,不会进行重试:

  1. public class FailsafeClusterInvoker<T> extends AbstractClusterInvoker<T> {
  2. private static final Logger logger = LoggerFactory.getLogger(FailsafeClusterInvoker.class);
  3. public FailsafeClusterInvoker(Directory<T> directory) {
  4. super(directory);
  5. }
  6. @Override
  7. public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  8. try {
  9. // 检查生产者Invokers是否合法
  10. checkInvokers(invokers, invocation);
  11. // 负载均衡选择一个生产者Invoker
  12. Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
  13. // 服务消费发起远程调用
  14. return invoker.invoke(invocation);
  15. } catch (Throwable e) {
  16. // 消费失败包装为一个空结果对象
  17. logger.error("Failsafe ignore exception: " + e.getMessage(), e);
  18. return new RpcResult();
  19. }
  20. }
  21. }

2.2.4 Failback

异步重试策略。当消费发生异常时返回一个空结果,失败请求将会进行异步重试。如果重试超过最大重试次数还不成功,放弃重试并不抛出异常:

  1. public class FailbackClusterInvoker<T> extends AbstractClusterInvoker<T> {
  2. private static final Logger logger = LoggerFactory.getLogger(FailbackClusterInvoker.class);
  3. private static final long RETRY_FAILED_PERIOD = 5;
  4. private final int retries;
  5. private final int failbackTasks;
  6. private volatile Timer failTimer;
  7. public FailbackClusterInvoker(Directory<T> directory) {
  8. super(directory);
  9. int retriesConfig = getUrl().getParameter(Constants.RETRIES_KEY, Constants.DEFAULT_FAILBACK_TIMES);
  10. if (retriesConfig <= 0) {
  11. retriesConfig = Constants.DEFAULT_FAILBACK_TIMES;
  12. }
  13. int failbackTasksConfig = getUrl().getParameter(Constants.FAIL_BACK_TASKS_KEY, Constants.DEFAULT_FAILBACK_TASKS);
  14. if (failbackTasksConfig <= 0) {
  15. failbackTasksConfig = Constants.DEFAULT_FAILBACK_TASKS;
  16. }
  17. retries = retriesConfig;
  18. failbackTasks = failbackTasksConfig;
  19. }
  20. private void addFailed(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, Invoker<T> lastInvoker) {
  21. if (failTimer == null) {
  22. synchronized (this) {
  23. if (failTimer == null) {
  24. // 创建定时器
  25. failTimer = new HashedWheelTimer(new NamedThreadFactory("failback-cluster-timer", true), 1, TimeUnit.SECONDS, 32, failbackTasks);
  26. }
  27. }
  28. }
  29. // 构造定时任务
  30. RetryTimerTask retryTimerTask = new RetryTimerTask(loadbalance, invocation, invokers, lastInvoker, retries, RETRY_FAILED_PERIOD);
  31. try {
  32. // 定时任务放入定时器等待执行
  33. failTimer.newTimeout(retryTimerTask, RETRY_FAILED_PERIOD, TimeUnit.SECONDS);
  34. } catch (Throwable e) {
  35. logger.error("Failback background works error,invocation->" + invocation + ", exception: " + e.getMessage());
  36. }
  37. }
  38. @Override
  39. protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  40. Invoker<T> invoker = null;
  41. try {
  42. // 检查生产者Invokers是否合法
  43. checkInvokers(invokers, invocation);
  44. // 负责均衡选择一个生产者Invoker
  45. invoker = select(loadbalance, invocation, invokers, null);
  46. // 消费服务发起远程调用
  47. return invoker.invoke(invocation);
  48. } catch (Throwable e) {
  49. logger.error("Failback to invoke method " + invocation.getMethodName() + ", wait for retry in background. Ignored exception: " + e.getMessage() + ", ", e);
  50. // 如果服务消费失败则记录失败请求
  51. addFailed(loadbalance, invocation, invokers, invoker);
  52. // 返回空结果
  53. return new RpcResult();
  54. }
  55. }
  56. @Override
  57. public void destroy() {
  58. super.destroy();
  59. if (failTimer != null) {
  60. failTimer.stop();
  61. }
  62. }
  63. /**
  64. * RetryTimerTask
  65. */
  66. private class RetryTimerTask implements TimerTask {
  67. private final Invocation invocation;
  68. private final LoadBalance loadbalance;
  69. private final List<Invoker<T>> invokers;
  70. private final int retries;
  71. private final long tick;
  72. private Invoker<T> lastInvoker;
  73. private int retryTimes = 0;
  74. RetryTimerTask(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, Invoker<T> lastInvoker, int retries, long tick) {
  75. this.loadbalance = loadbalance;
  76. this.invocation = invocation;
  77. this.invokers = invokers;
  78. this.retries = retries;
  79. this.tick = tick;
  80. this.lastInvoker = lastInvoker;
  81. }
  82. @Override
  83. public void run(Timeout timeout) {
  84. try {
  85. // 负载均衡选择一个生产者Invoker
  86. Invoker<T> retryInvoker = select(loadbalance, invocation, invokers, Collections.singletonList(lastInvoker));
  87. lastInvoker = retryInvoker;
  88. // 服务消费发起远程调用
  89. retryInvoker.invoke(invocation);
  90. } catch (Throwable e) {
  91. logger.error("Failed retry to invoke method " + invocation.getMethodName() + ", waiting again.", e);
  92. // 超出最大重试次数记录日志不抛出异常
  93. if ((++retryTimes) >= retries) {
  94. logger.error("Failed retry times exceed threshold (" + retries + "), We have to abandon, invocation->" + invocation);
  95. } else {
  96. // 未超出最大重试次数重新放入定时器
  97. rePut(timeout);
  98. }
  99. }
  100. }
  101. private void rePut(Timeout timeout) {
  102. if (timeout == null) {
  103. return;
  104. }
  105. Timer timer = timeout.timer();
  106. if (timer.isStop() || timeout.isCancelled()) {
  107. return;
  108. }
  109. timer.newTimeout(timeout.task(), tick, TimeUnit.SECONDS);
  110. }
  111. }
  112. }

2.2.5 Forking

并行调用策略。消费者通过线程池并发调用多个生产者,只要有一个成功就算成功:

  1. public class ForkingClusterInvoker<T> extends AbstractClusterInvoker<T> {
  2. private final ExecutorService executor = Executors.newCachedThreadPool(new NamedInternalThreadFactory("forking-cluster-timer", true));
  3. public ForkingClusterInvoker(Directory<T> directory) {
  4. super(directory);
  5. }
  6. @Override
  7. public Result doInvoke(final Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  8. try {
  9. checkInvokers(invokers, invocation);
  10. final List<Invoker<T>> selected;
  11. // 获取配置参数
  12. final int forks = getUrl().getParameter(Constants.FORKS_KEY, Constants.DEFAULT_FORKS);
  13. final int timeout = getUrl().getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
  14. // 获取并行执行的Invoker列表
  15. if (forks <= 0 || forks >= invokers.size()) {
  16. selected = invokers;
  17. } else {
  18. selected = new ArrayList<>();
  19. for (int i = 0; i < forks; i++) {
  20. // 选择生产者
  21. Invoker<T> invoker = select(loadbalance, invocation, invokers, selected);
  22. // 防止重复增加Invoker
  23. if (!selected.contains(invoker)) {
  24. selected.add(invoker);
  25. }
  26. }
  27. }
  28. RpcContext.getContext().setInvokers((List) selected);
  29. final AtomicInteger count = new AtomicInteger();
  30. final BlockingQueue<Object> ref = new LinkedBlockingQueue<>();
  31. for (final Invoker<T> invoker : selected) {
  32. // 在线程池中并发执行
  33. executor.execute(new Runnable() {
  34. @Override
  35. public void run() {
  36. try {
  37. // 执行消费逻辑
  38. Result result = invoker.invoke(invocation);
  39. // 存储消费结果
  40. ref.offer(result);
  41. } catch (Throwable e) {
  42. // 如果异常次数大于等于forks参数值说明全部调用失败,则把异常放入队列
  43. int value = count.incrementAndGet();
  44. if (value >= selected.size()) {
  45. ref.offer(e);
  46. }
  47. }
  48. }
  49. });
  50. }
  51. try {
  52. // 从队列获取结果
  53. Object ret = ref.poll(timeout, TimeUnit.MILLISECONDS);
  54. // 如果异常类型表示全部调用失败则抛出异常
  55. if (ret instanceof Throwable) {
  56. Throwable e = (Throwable) ret;
  57. 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);
  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. RpcContext.getContext().clearAttachments();
  65. }
  66. }
  67. }

2.2.6 Broadcast

广播调用策略。消费者遍历调用所有生产者节点,任何一个出现异常则抛出异常:

  1. public class BroadcastClusterInvoker<T> extends AbstractClusterInvoker<T> {
  2. private static final Logger logger = LoggerFactory.getLogger(BroadcastClusterInvoker.class);
  3. public BroadcastClusterInvoker(Directory<T> directory) {
  4. super(directory);
  5. }
  6. @Override
  7. public Result doInvoke(final Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  8. checkInvokers(invokers, invocation);
  9. RpcContext.getContext().setInvokers((List) invokers);
  10. RpcException exception = null;
  11. Result result = null;
  12. // 遍历调用所有生产者节点
  13. for (Invoker<T> invoker : invokers) {
  14. try {
  15. // 执行消费逻辑
  16. result = invoker.invoke(invocation);
  17. } catch (RpcException e) {
  18. exception = e;
  19. logger.warn(e.getMessage(), e);
  20. } catch (Throwable e) {
  21. exception = new RpcException(e.getMessage(), e);
  22. logger.warn(e.getMessage(), e);
  23. }
  24. }
  25. // 任何一个出现异常则抛出异常
  26. if (exception != null) {
  27. throw exception;
  28. }
  29. return result;
  30. }
  31. }

3 怎么做幂等

经过上述分析我们知道,RPC框架自带的重试机制可能会造成数据重复问题,那么在使用中必须考虑幂等性。幂等性是指一次操作与多次操作产生结果相同,并不会因为多次操作而产生不一致性。常见幂等方案有取消重试、幂等表、数据库锁、状态机。


3.1 取消重试

取消重试有两种方法,第一是设置重试次数为零,第二是选择不重试的集群容错策略。

  1. <!-- 设置重试次数为零 -->
  2. <dubbo:reference id="helloService" interface="com.java.front.dubbo.demo.provider.HelloService" retries="0" />
  3. <!-- 选择集群容错方案 -->
  4. <dubbo:reference id="helloService" interface="com.java.front.dubbo.demo.provider.HelloService" cluster="failfast" />

3.2 幂等表

假设用户支付成功后,支付系统将支付成功消息,发送至消息队列。物流系统订阅到这个消息,准备为这笔订单创建物流单。

但是消息队列可能会重复推送,物流系统有可能接收到多次这条消息。我们希望达到效果是:无论接收到多少条重复消息,只能创建一笔物流单。

解决方案是幂等表方案。新建一张幂等表,该表就是用来做幂等,无其它业务意义,有一个字段名为key建有唯一索引,这个字段是幂等标准。

物流系统订阅到消息后,首先尝试插入幂等表,订单编号作为key字段。如果成功则继续创建物流单,如果订单编号已经存在则违反唯一性原则,无法插入成功,说明已经进行过业务处理,丢弃消息。

这张表数据量会比较大,我们可以通过定时任务对数据进行归档,例如只保留7天数据,其它数据存入归档表。

还有一种广义幂等表就是我们可以用Redis替代数据库,在创建物流单之前,我们可以检查Redis是否存在该订单编号数据,同时可以为这类数据设置7天过期时间。


3.3 状态机

物流单创建成功后会发送消息,订单系统订阅到消息后更新状态为完成,假设变更是将订单状态0更新至状态1。订单系统也可能收到多条消息,可能在状态已经被更新至状态1之后,依然收到物流单创建成功消息。

解决方案是状态机方案。首先绘制状态机图,分析状态流转形态。例如经过分析状态1已经是最终态,那么即使接收到物流单创建成功消息也不再处理,丢弃消息。


3.4 数据库锁

数据库锁又可以分为悲观锁和乐观锁两种类型,悲观锁是在获取数据时加锁:

  1. select * from table where col='xxx' for update

乐观锁是在更新时加锁,第一步首先查出数据,数据包含version字段。第二步进行更新操作,如果此时记录已经被修改则version字段已经发生变化,无法更新成功:

  1. update table set xxx,
  2. version = #{version} + 1
  3. where id = #{id}
  4. and version = #{version}

4 文章总结

本文首先分析了为什么重试这个问题,因为对于RPC交互无响应场景,重试是一种重要选择。然后分析了DUBBO提供的六种集群容错策略,Failover作为默认策略提供了重试机制,在业务代码没有显示重试情况下,仍有可能发起多次调用,这必须引起重视。最后我们分析了几种常用幂等方案,希望本文对大家有所帮助。


原文链接:https://www.cnblogs.com/javafront/p/17433507.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号