使用spring-retry实现支付系统异步通知

  • Post author:
  • Post category:其他


支付系统异步通知承接上文:

DelayQueue实现支付系统异步通知

本篇介绍通过spring-retry来实现支付系统异步通知功能。

1、添加所需的jar

Xml代码

收藏代码

  1. <dependency>
  2. <groupId>org.springframework.retry</groupId>
  3. <artifactId>spring-retry</artifactId>
  4. <version>1.1.2.RELEASE</version>
  5. </dependency>

2、实现任务重试服务

Java代码

收藏代码

  1. package com.huatech.service;
  2. import java.io.IOException;
  3. import java.net.URISyntaxException;
  4. import java.util.HashMap;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.retry.RetryException;
  8. import org.springframework.retry.annotation.Backoff;
  9. import org.springframework.retry.annotation.EnableRetry;
  10. import org.springframework.retry.annotation.Retryable;
  11. import org.springframework.stereotype.Service;
  12. import com.huatech.common.delay.RetMessage;
  13. import com.huatech.common.util.HttpsUtil;
  14. /**
  15. * 任务重试服务
  16. *
  17. *  第一次成功则不再重试;
  18. *  第一次失败,10分钟后重试第二次;
  19. *  第二次失败,20分钟后重试第三次;
  20. *  第三次失败,40分钟后重试第四次;
  21. *  第四次失败,60分钟后重试第五次;
  22. * @author lh
  23. *
  24. */
  25. //@Configuration
  26. @EnableRetry
  27. @Service
  28. public class TaskRetryService {
  29. private static final Logger LOGGER = LoggerFactory.getLogger(TaskRetryService.class);
  30. //返回结果
  31. private static final String RES_SUCCESS = “success”;
  32. //时间单位:10min
  33. private static final long TIME_UNIT = 1000 * 60 * 10;
  34. //重试次数
  35. private static final int MAX_ATTEMPTS = 5;
  36. @Retryable(value = {RetryException.class, RuntimeException.class},
  37. maxAttempts = MAX_ATTEMPTS,
  38. backoff = @Backoff(delay = TIME_UNIT, maxDelay=TIME_UNIT * 6, multiplier= 2 ))
  39. public void notice(RetMessage msg){
  40. HashMap<String, String> paramMap = new HashMap<String, String>();
  41. paramMap.put(“reqData”, msg.getReqData());
  42. String httpResult = null;
  43. try {
  44. httpResult = HttpsUtil.getInstance().doPostRetString(msg.getUrl(), null, paramMap);
  45. LOGGER.info(“第{}次异步回调,返回结果{},返回参数:{},响应结果:{}”, msg.getTimes(), httpResult,
  46. paramMap.get(“reqData”), RES_SUCCESS.equals(httpResult));
  47. if (!RES_SUCCESS.equals(httpResult)) {
  48. msg.setTimes(msg.getTimes() + 1);
  49. msg.setSuccess(false);
  50. throw new RetryException(“retry failed”);
  51. }else{
  52. msg.setSuccess(true);
  53. }
  54. } catch (URISyntaxException | IOException e) {
  55. }
  56. }
  57. }