Guava 重試機制加入
阿新 • • 發佈:2022-05-19
參考
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 = new Callable<Boolean>() {
public Boolean call() throws Exception {
return pushSccData();
}
};
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;
}
}
}