Spring-Retry(重试机制)

发布时间 2023-03-29 12:00:53作者: SimonHu1993

​ 在实际工作中,重处理是一个非常常见的场景,比如:发送消息失败、调用远程服务失败、争抢锁失败。
这些错误可能是因为网络波动造成的,等待过后重处理就能成功。通常来说,会用try/catch,while循环之类的语法来进行重处理,但是这样的做法缺乏统一性,并且不是很方便,要多写很多代码。然而spring-retry却可以通过注解,在不入侵原有业务逻辑代码的方式下,优雅的实现重处理功能。

​ 业务背景:地推系统中,原有注册用户与地推用户绑定关系是在前端注册成功之后使用MQ消息,在MQ消息中进行消费,绑定注册用户与地推用户关系,MQ消费失败之后会使用消息重试,进行最多5次消费,因此次和商城对接地推服务商品,绑定关系逻辑需要在地推系统登录日志接口中记录,无法适用MQ消费重试,故需要在service方法中进行调用重试,保证绑定关系的成功率。

一、@Retryable是什么?
spring系列的spring-retry是另一个实用程序模块,可以帮助我们以标准方式处理任何特定操作的重试。在spring-retry中,所有配置都是基于简单注释的。

二、使用步骤

1.POM依赖

基于AOP实现,因此还需引入aop相关的依赖

<dependency>
  <groupId>org.springframework.retry</groupId>
  <artifactId>spring-retry</artifactId>
</dependency>

2.启用@Retryable
@SpringBootApplication
@Import(GlobalExceptionTranslator.class)
@EnableFeignClients(basePackages = {"com.jzt.jk"})
@EnableTransactionManagement
@EnableRocketMq
@EnableFaServer
@EnableSoaServiceClients(baseScanPackage = "com.jzt.jk")
@EnableRetry
public class DistributionApplication {

    public static void main(String[] args) {
        SpringApplication.run(DistributionApplication.class, args);
    }
}
3.在方法上添加@Retryable

1.原调用方引用RetryableCustomerUserService

@Slf4j
@Service
public class CustomerVisitLogService extends ServiceImpl<CustomerVisitLogDao, CustomerVisitLog> {

    @Resource
    RetryableCustomerUserService retryableCustomerUserService;

    /**
     * 新增用户访问日志
     *
     * @param request
     * @return
     */
    public void addCustomerVisitLog(CustomerVisitLogCreateReq request) {

        CustomerVisitLog customerVisitLog = modelMapper.map(request, CustomerVisitLog.class);
        //获取地推信息并组装
        getDistributionInfo(customerVisitLog);
        customerVisitLog.setEventName(CustomerVisitLogEventEnum.getCustomerVisitLogEventEnum(request.getEvent()).getName());
        customerVisitLog.setAppName(AppIdEnum.getAppIdEnum(request.getAppId()).getDesc());
        customerVisitLog.setSceneName(getSceneName(request.getAppId(), request.getScene()));
        customerVisitLog.setCreateTime(new Date());
        customerVisitLog.setRecommendNo(request.getRecommendNo());

        //有地推人员就把推荐标的信息放入日志
        if (request.getDistributorId() != null && (AppIdEnum.USER_WX_MINI_APP.getName().equals(request.getAppId())
                || AppIdEnum.USER_WX_OFFICIAL_ACCOUNT.getName().equals(request.getAppId()) || AppIdEnum.USER_WX_OFFICIAL_XFWY_ACCOUNT.getName()
                .equals(request.getAppId()))) {
            QrcodeExtraByIdResp resp = null;
            //兼容历史小程序,查询最早可用的二维码
            if (StringUtils.isNotBlank(request.getRecommendNo())) {
                resp = userQrcodeService.getQrcodeExtraByRecommendNo(request.getRecommendNo());
            } else {
                log.warn("有地推id没有推荐编码,取最早创建的可用的小程序码,request={}", JSON.toJSONString(request));
                resp = userQrcodeService.getQrcodeExtraById(request.getDistributorId());
            }
            log.info("resp={}", JSON.toJSONString(resp));
            if (resp != null) {
                customerVisitLog.setRecommendNo(resp.getRecommendNo());
                if (resp.getUserQrcodeExtDto() != null) {
                    customerVisitLog.setTeamDiseaseCenterId(resp.getUserQrcodeExtDto().getTeamDiseaseCenterId());
                    customerVisitLog.setTeamDiseaseCenterName(resp.getUserQrcodeExtDto().getTeamDiseaseCenterName());
                    customerVisitLog.setDiseaseTeamId(resp.getUserQrcodeExtDto().getTeamId());
                    customerVisitLog.setDiseaseTeamName(resp.getUserQrcodeExtDto().getTeamName());
                }
            }
        }

        if (!save(customerVisitLog)) {
            log.error("新增用户访问日志失败.request={}", request);
            throw new BusinessException("新增用户访问日志失败");
        }
        //注册事件添加绑定关系
        if (CustomerVisitLogEventEnum.REGISTER.getEvent().equals(request.getEvent()) && request.getDistributorId() != null) {
            DistributionThreadPoolExecutor.submit(() -> {
                log.info("appId:{},distributorId:{},customerUserId:{},访问日志记录注册事件,调用注册用户绑定地推用户关系开始", request.getAppId(), request.getDistributorId(),
                        request.getCustomerUserId());
                DistributionRegisterMsg registerMsg = new DistributionRegisterMsg();
                registerMsg.setAppId(request.getAppId());
                registerMsg.setRegisterTime(customerVisitLog.getCreateTime().getTime());
                registerMsg.setDistributorId(request.getDistributorId() + "");
                registerMsg.setCustomerUserId(request.getCustomerUserId());
                retryableCustomerUserService.retryableRecommendRegistry(registerMsg);
            });
        }
    }
}

2.创建service实现类并添加@Retryable,因为@Retryable是基于AOP切面实现,故不能在当前类中调用执行,不然不能生效

@Slf4j
@Service
public class RetryableCustomerUserService {

    @Resource
    private CustomerUserService customerUserService;

  /**
     * value:抛出指定异常才会重试
     * include:和value一样,默认为空,当exclude也为空时,默认所有异常
     * exclude:指定不处理的异常
     * maxAttempts:最大重试次数,默认3次
     * backoff:重试等待策略,
     * 默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000; 以毫秒为单位的延迟(默认 1000)
     * multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。
     * @param code
     * @return
     * @throws Exception
     */
    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public void retryableRecommendRegistry(DistributionRegisterMsg msgEntity) {
        log.info("调用可重试的推荐注册方法:{}", JSON.toJSONString(msgEntity));
        customerUserService.recommendRegistry(msgEntity);
    }
		
  	/**
     * Spring-Retry还提供了@Recover注解,用于@Retryable重试失败后处理方法。
     * 如果不需要回调方法,可以直接不写回调方法,那么实现的效果是,重试次数完了后,如果还是没成功没符合业务判断,就抛出异常。
     * 可以看到传参里面写的是 Exception e,这个是作为回调的接头暗号(重试次数用完了,还是失败,我们抛出这个Exception e通知触发这个回调方法)。
     * 注意事项:
     * 方法的返回值必须与@Retryable方法一致
     * 方法的第一个参数,必须是Throwable类型的,建议是与@Retryable配置的异常一致,其他的参数,需要哪个参数,写进去就可以了(@Recover方法中有的)
     * 该回调方法与重试方法写在同一个实现类里面
     *
     * 由于是基于AOP实现,所以不支持类里自调用方法
     * 如果重试失败需要给@Recover注解的方法做后续处理,那这个重试的方法不能有返回值,只能是void
     * 方法内不能使用try catch,只能往外抛异常
     * @Recover注解来开启重试失败后调用的方法(注意,需跟重处理方法在同一个类中),此注解注释的方法参数一定要是@Retryable抛出的异常,否则无法识别,可以在该方法中进行日志处理。
     * @param e
     * @param msgEntity 与被重试参数列表一致
     * @return
     */
    @Recover
    public void recover(Exception e, DistributionRegisterMsg msgEntity) {
        log.info("调用可重试的推荐注册方法异常回调:{}", JSON.toJSONString(msgEntity));
    }

}

来简单解释一下注解中几个参数的含义:

  • value:抛出指定异常才会重试
  • include:和value一样,默认为空,当exclude也为空时,默认所有异常
  • exclude:指定不处理的异常
  • maxAttempts:最大重试次数,默认3次
  • backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000(单位毫秒),我们设置为2000;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。

当重试耗尽时还是失败,会出现什么情况呢?

当重试耗尽时,RetryOperations可以将控制传递给另一个回调,即RecoveryCallback。Spring-Retry还提供了@Recover注解,用于@Retryable重试失败后处理方法。如果不需要回调方法,可以直接不写回调方法,那么实现的效果是,重试次数完了后,如果还是没成功没符合业务判断,就抛出异常。

  • 重试方法必须要使用 @Recover 注解;
  • 返回值必须和被重试的函数返回值一致;
  • 参数中除了第一个是触发的异常外,后面的参数需要和被重试函数的参数列表一致;
@Recover
public void recover(Exception e, DistributionRegisterMsg msgEntity) {
  log.info("调用可重试的推荐注册方法异常回调:{}", JSON.toJSONString(msgEntity));
 }

查看测试结果:


可以看到总共执行了三次,最后失败调用recover回调方法