guava的重試機制guava-retrying使用


1,添加maven依賴

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

2,定義重試機制

Retryer<CMSResultDTO> smsRetryer = RetryerBuilder.<CMSResultDTO>newBuilder()      
.retryIfResult(cmsResultDTO->cmsResultDTO.getCode() != SM_SUCCESS_CODE)  // 短信返回的碼不是200要重試
.retryIfResult(Predicates.<CMSResultDTO>isNull())            // 返回的數據是null要重試
.retryIfExceptionOfType(Exception.class)                    // 返回的異常錯誤類
.withStopStrategy(StopStrategies.stopAfterAttempt(ATTEMPT_NUM))
.withWaitStrategy(WaitStrategies.fixedWait(SLEEP_TIME, TimeUnit.SECONDS))    // 隔1秒重試
.withRetryListener(new SMRetryListener<>())
.build();

3,定義要重試的任務

 Callable<CMSResultDTO> task = ()->{
            log.info("sm input param:type=>{}, interCode=>{}, mobile=>{}, pair=>{}",
                    type, interCode, mobile, pair);
            CMSResultDTO cmsResultDTO = cmsService.sendMessage(type, interCode, mobile, pair);
            log.info("sm return data:{}", JSON.toJSONString(cmsResultDTO));
            return cmsResultDTO;
        };

4,重試機制重試任務

CMSResultDTO cmsResultDTO = null;
        try {
            cmsResultDTO = smsRetryer.call(task);
        } catch (ExecutionException e) {
            log.error("SM ExecutionException", e);
        } catch (RetryException e) {
            log.error("SM RetryException", e);
        }
        return cmsResultDTO;

以下是一個關於重試發短信的完整例子

/**
     * 重試機制 發送短信接口支持國際碼
     * @param type 模版號
     * @param interCode 國際碼
     * @param mobile 手機號碼
     * @param pair 參數對
     * @return 消息發送結果,包括發送狀態和消息標識
     */
    public CMSResultDTO retrySendMessage(Integer type, String interCode, String mobile, Map<String, String> pair) throws CMSQueueException, CMSSendException {
        Preconditions.checkNotNull(type, "type不能為null");
        Preconditions.checkNotNull(interCode, "interCode不能為null");
        Preconditions.checkNotNull(mobile, "mobile不能為null");
        Preconditions.checkNotNull(pair, "pair不能為null");

        Callable<CMSResultDTO> task = ()->{
            log.info("sm input param:type=>{}, interCode=>{}, mobile=>{}, pair=>{}",
                    type, interCode, mobile, pair);
             //調用第三方發短信接口,得到返回值,第一時間記錄到log中
            CMSResultDTO cmsResultDTO = cmsService.sendMessage(type, interCode, mobile, pair);
            log.info("sm return data:{}", JSON.toJSONString(cmsResultDTO));
            return cmsResultDTO;
        };
        //定義重試的機制原理
        Retryer<CMSResultDTO> smsRetryer = RetryerBuilder.<CMSResultDTO>newBuilder()
                .retryIfResult(cmsResultDTO->cmsResultDTO.getCode() != SM_SUCCESS_CODE)  // 短信返回的碼不是200要重試
                .retryIfResult(Predicates.<CMSResultDTO>isNull())            // 返回的數據是null要重試
                .retryIfExceptionOfType(Exception.class)                    // 返回的異常錯誤類
                .withStopStrategy(StopStrategies.stopAfterAttempt(ATTEMPT_NUM))
                .withWaitStrategy(WaitStrategies.fixedWait(SLEEP_TIME, TimeUnit.SECONDS))    // 隔1秒重試
                //監聽器
                .withRetryListener(new SMRetryListener<>())
                .build();
        
        CMSResultDTO cmsResultDTO = null;
        try {
        //執行任務的重試,得到返回結果
            cmsResultDTO = smsRetryer.call(task);
        } catch (ExecutionException e) {
            log.error("SM ExecutionException", e);
        } catch (RetryException e) {
            log.error("SM RetryException", e);
        }
        return cmsResultDTO;
    }
    
    //自定義的監聽器
    /**
     * 重試監聽器
     * @param <CMSResultDTO>
     */
    private class SMRetryListener<CMSResultDTO> implements RetryListener {

        @Override
        public <CMSResultDTO> void onRetry(Attempt<CMSResultDTO> attempt) {
            log.info("[retry]time=" + attempt.getAttemptNumber());
            if (attempt.hasException()) {
                log.error("retry exception", attempt.getExceptionCause());
            }
            if (attempt.hasResult()) {
                if (attempt.getResult() == null) {
                    log.info("retry return data is null");
                } else {
                    log.info("retry return data is:{}", JSON.toJSONString(attempt.getResult()));
                }
            }
        }
        
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM