- pom引入
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
- 初始化
/**
* @ClassName MyRetry
* Description guava接口重试
* (1)retryIfException:遇到异常重试
* (2)retryIfException: 返回结果为false重试
* (3)withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS)):等待3秒重试一次
* (4)withStopStrategy(StopStrategies.stopAfterAttempt(3)):重试三次
* (5)withRetryListener(new MyRetryListener()).build():MyRetryListener为自定义的重试监听类,监听重试成功失败的信息
* @Author xiangyp
* @Date 2020/3/26 9:45
* Version 1.0
**/
@Component
public class MyRetry {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Resource
private OrderRegMapper orderRegMapper;
@Resource
private RequestUtil requestUtil;
public Boolean queryOrderRetry(String orderNum) {
Boolean call=false;
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder().
retryIfException().
retryIfResult(Predicates.equalTo(false)).
withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS)).
withStopStrategy(StopStrategies.stopAfterAttempt(3)).
withRetryListener(new MyRetryListener()).build();
try {
call = retryer.call(new MyCallable(orderRegMapper,orderNum,requestUtil));//在此加入任务
} catch (Exception e) {
log.info(e.getMessage());
}
return call;
}
}
具体业务代码
public class MyCallable implements Callable {
private Logger log = LoggerFactory.getLogger(this.getClass());
private OrderRegMapper orderRegMapper;
private String orderNum;
private RequestUtil requestUtil;
public MyCallable(OrderRegMapper orderRegMapper,String orderNum,RequestUtil requestUtil) {
this.orderRegMapper = orderRegMapper;
this.orderNum=orderNum;
this.requestUtil=requestUtil;
}
@Override
public Boolean call() {
OrderReg orderReg = orderRegMapper.selectOne(new OrderReg(orderNum));
JSONObject jsonObject = new JSONObject();
jsonObject.put("OrderNo", orderReg.getOrderNumber());
log.info("眼视光查单接口入参{}", jsonObject.toJSONString(0));
String orderqueryResult = requestUtil.postUrl("register_orderquery", jsonObject.toJSONString(0));
JSONObject jsonQuery = JSONUtil.parseObj(orderqueryResult);
log.info("眼视光查单接口出参{}", jsonQuery.toString());
String orderStatus=jsonQuery.get("OrderStatus").toString();
if (orderStatus.equals("0")||orderStatus.equals("2")) {
log.info("眼视光查单接口返回失败orderNum{}", orderNum+(orderStatus.equals("0")?"订单不存在":"订单已退费"));
return false;
} else if(orderStatus.equals("1")) {
log.info("眼视光查单接口返回成功,订单已收费orderNum{}", orderNum);
orderReg.setRegPaySeq(jsonQuery.get("RegPaySeq").toString());
orderRegMapper.updateById(orderReg);
return true;
}else{
log.info("眼视光查单接口返回状态有误orderNum{}", orderNum);
return false;
}
}
}