spring 重试

199 阅读1分钟

springboot 开启重试@EnableRetry
@EnableRetry 默认是基于接口,proxyTargetClass = true,使用CGLIB代理,这样补偿方法pushTransferOrderToSwmsRecover就不需要声明接口了。

@SpringBootApplication
@EnableRetry(proxyTargetClass = true)
public class Application {
   public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
   }
}
/**
 * 推送取消的店店调拨给SWMS
 * @param storeorderId
 * @return
 */
@Override
@Retryable(value= {Exception.class},maxAttempts=3,backoff = @Backoff(delay = 1000L, multiplier = 1.5))
public int pushTransferOrderToSwms(String storeorderId) throws Exception {
    int updateResult = 0;
    StoreOrderCancleBean storeOrderCancleBean = getStoreOrderCancleBean(storeorderId);  
    String json = JSONObject.toJSONStringWithDateFormat(storeOrderCancleBean, "yyyy-MM-dd HH:mm:ss.SSS", SerializerFeature.WriteDateUseDateFormat);
    log.info("==开始推送取消的店店调拨给SWMS:" + json);
    boolean isPushSuccess=false;
    String returnJSON = E3apiPostUtil.doPostForm(swmsStoreordercancleUrl, swmsStoreordercanclePrivateKey, swmsStoreordercanclePublicKey, swmsStoreordercanclePk, json);
    log.info("==结束推送取消的店店调拨给SWMS:" + returnJSON);
    if (null != returnJSON) {
        JSONObject jsonObject = JSONObject.parseObject(returnJSON);
        if ((boolean) jsonObject.get("Success")) {
            updateResult = storeMovreqmstMapper.updateStoreCancleStatusBySync(storeorderId);
            isPushSuccess=true;
        }
    }
    if(!isPushSuccess){
        String  msg= "推送取消的店店调拨给SWMS异常,storeorderId="+storeorderId+",响应值="+returnJSON;
        throw new Exception(msg);
    }
    return updateResult;
}

重试失败后抛出异常,补偿方法,使用@Recover,且和原方法返回值和参数一样。

@Recover
public int pushTransferOrderToSwmsRecover(Throwable e, String storeorderId) throws ArithmeticException {
    log.info("推送取消的店店调拨给SWMS-全部重试失败,storeorderId={},{}", storeorderId, e.getMessage());
    //插入数据库,调度进行重试补偿
    StoreOrderCancleBean storeOrderCancleBean = getStoreOrderCancleBean(storeorderId);
    return 0;
    }