今天要比昨天吃苦的能力更强

Guava 重试机制加入

参考
https://www.isolves.com/it/cxkf/bk/2022-01-04/48256.html
https://www.jianshu.com/p/0ea2f20c1709

<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>

@Component
@EnableScheduling
@Slf4j
public class StoreQuartz{
@Autowired
private RedissonUtil redissonUtil;


private final String TASK_LOCK = "PUSH_SHOP_DATA_TO_SCCDEPT";


private static Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfResult(Boolean.FALSE::equals)//返回false重试
.retryIfException()
         //.retryIfResult(Predicates.<Boolean>isNull()) // callable返回null时重试
         // .retryIfExceptionOfType(IOException.class) // callable抛出IOException重试
         // .retryIfRuntimeException() // callable抛出RuntimeException重试
        //注册重试监听  
//.withRetryListener(new DiyRetryListener<Boolean>())
.withStopStrategy(StopStrategies.stopAfterAttempt(3)) // 重试3次后停止
.withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
        .build();
/**
*
*/
@Scheduled(cron = "*/20 * * * * ?")
public void pushShopDataToSccDept(){
//先判断键值是否存在,不存在执行定时任务
RLock lock = redissonUtil.getRLock(TASK_LOCK);
try {
boolean locked = lock.tryLock(0L, 5L, TimeUnit.SECONDS);
if (locked) {
      Callable<Boolean> callable = () -> pushSccData(shopInfo,  params);
        retryer.call(callable);
if(lock.isLocked() && lock.isHeldByCurrentThread()){
lock.unlock();
}
}
} catch (Exception e) {
//重试3次还是失败com.github.rholder.retry.RetryException: Retrying failed to complete successfully after 3 attempts.
log.error("执行门店推送定时任务异常" + e);

}finally {
if (lock.isLocked() && lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}

private Boolean pushSccData() {
String res = "远程调用Url返回结果";
JSONObject resObject = JSON.parseObject(res);
log.info("执行结果:{}",resObject);
if (resObject.getIntValue("code") == 200) {
return true;
} else {
return false;
}
}


}




posted @ 2022-05-19 16:42  野程序猿小刘  阅读(183)  评论(0编辑  收藏  举报