最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java編寫自定義重試工具類的示例代碼

 更新時(shí)間:2026年01月13日 08:57:40   作者:焰火1999  
這篇文章主要為大家詳細(xì)介紹了如何基于Java實(shí)現(xiàn)自定義重試工具類,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

Java重試工具類,零依賴。可配置項(xiàng):接受的異常類型、返回值校驗(yàn)、最大重試次數(shù)、重試間隔時(shí)間。

1 重試工具類 RetryUtils源碼

RetryUtils:

使用了lombok的@Slf4j注解用于打印日志,不用可移除。

import com.example.exception.RetryException;

import lombok.extern.slf4j.Slf4j;

import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * <h2>重試工具類</h2>
 *
 * @author GFire
 * @since 2025/4/22 17:58
 */
@Slf4j
public abstract class RetryUtils {
    /**
     * 失敗重試
     *
     * @param task            執(zhí)行的任務(wù),無(wú)返回值
     * @param acceptException 可接受的異常類型,執(zhí)行的任務(wù)拋出此異常(及其子類)則失敗重試。null表示不接受任何異常
     * @param maxRetryCount   最大重試次數(shù)
     * @param waitTime        重試間隔等待時(shí)間, 單位毫秒, <=0則不等待
     * @throws RetryException 如果任務(wù)重試超過(guò)最大次數(shù)、或拋出不可接受的異常,則統(tǒng)一包裝拋出RetryException
     */
    public static void doWithRetry(Runnable task, Class<? extends Throwable> acceptException, int maxRetryCount, int waitTime) {
        if (task == null) {
            throw new IllegalArgumentException("task can not be null");
        }

        doWithRetry(() -> {
            task.run();
            return 1;
        }, i -> i == 1, acceptException, maxRetryCount, waitTime);
    }

    /**
     * 失敗重試
     *
     * @param task            執(zhí)行的任務(wù),有返回值
     * @param isValid         判斷任務(wù)返回值是否合法,不合法則失敗重試
     * @param acceptException 可接受的異常類型,執(zhí)行的任務(wù)拋出此異常(及其子類)則失敗重試。null表示不接受任何異常
     * @param maxRetryCount   最大重試次數(shù)
     * @param waitTime        重試間隔等待時(shí)間, 單位毫秒, <=0則不等待
     * @return supplier執(zhí)行結(jié)果
     * @throws RetryException 如果任務(wù)重試超過(guò)最大次數(shù)、或拋出不可接受的異常,則統(tǒng)一包裝拋出RetryException
     */
    public static <T> T doWithRetry(Supplier<T> task, Predicate<T> isValid, Class<? extends Throwable> acceptException, int maxRetryCount, int waitTime) {
        if (task == null) {
            throw new IllegalArgumentException("task can not be null");
        }
        if (isValid == null) {
            throw new IllegalArgumentException("isValid can not be null");
        }
        if (maxRetryCount <= 0) {
            throw new IllegalArgumentException("maxRetryCount must be > 0");
        }

        T result = null;
        for (int tryCount = 1; tryCount <= maxRetryCount; tryCount++) {
            try {
                result = task.get();
                if (isValid.test(result)) {
                    return result;
                } else {
                    log.error("result invalid, tryCount: {}, result: {}", tryCount, result);
                }
            } catch (Throwable e) {
                handleException(e, acceptException, maxRetryCount, tryCount);
            }

            if (waitTime > 0 && tryCount < maxRetryCount) {
                sleep(waitTime); // 等待一段時(shí)間后重試
            }
        }
        throw new RetryException("result: " + result);
    }

    private static void handleException(Throwable e, Class<? extends Throwable> acceptException, int maxRetryCount, int tryCount) {
        log.error("error, tryCount: {}, Exception: ", tryCount, e);
        if (acceptException != null && acceptException.isInstance(e)) {
            if (tryCount == maxRetryCount) { // 最后一次重試仍失敗,則拋出
                throw new RetryException(e);
            }
        } else { // 不可接受的異常,直接拋出
            throw new RetryException(e);
        }
    }

    private static void sleep(int waitTime) {
        try {
            Thread.sleep(waitTime);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RetryException(e);
        }
    }
}

RetryException:

/**
 * <h2>重試異常</h2>
 *
 * @author GFire
 * @since 2025/4/23 11:20
 */
public class RetryException extends RuntimeException {
    public RetryException(String message) {
        super(message);
    }

    public RetryException(Throwable cause) {
        super(cause);
    }
}

2 使用方式

示例1:任務(wù)無(wú)返回值

 // 模擬調(diào)用API接口,失敗重試
RetryUtils.doWithRetry(() -> apiService.query(), Exception.class, 3, 2000);

解釋:任務(wù)apiService.query()無(wú)返回值、接受Exception異常、最大重試次數(shù)為3、重試間隔2秒

示例2:任務(wù)有返回值、需校驗(yàn)返回值

/**
 * 模擬發(fā)送通知
 */
public boolean send(String content) {
    try {
        RetryUtils.doWithRetry(() -> noticeService.send(content), this::isValid, Exception.class, 3, 2000);
        return true;
    } catch (RetryException e) {
        log.error("send error: {}", e.toString());
    }
    return false;
}

private boolean isValid(String res) {
    if (StringUtils.isNotEmpty(res)) {
        JSONObject response = JSON.parseObject(res);
        return "ok".equals(response.getString("status"));
    }
    return false;
}

解釋:任務(wù)noticeService.send(content)有String類型的返回值、isValid方法判斷返回值是否合法、接受Exception異常、最大重試次數(shù)為3、重試間隔2秒

示例3:任務(wù)有返回值、無(wú)需校驗(yàn)返回值

RetryUtils.doWithRetry(() -> noticeService.send(), (res) -> true, Exception.class, 3, 2000);

解釋:任務(wù)noticeService.send()有String類型的返回值、(res) -> true認(rèn)為任意返回值都合法(即無(wú)校驗(yàn))、接受Exception異常、最大重試次數(shù)為3、重試間隔2秒

到此這篇關(guān)于Java編寫自定義重試工具類的示例代碼的文章就介紹到這了,更多相關(guān)Java自定義重試內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

越西县| 建宁县| 古交市| 漳平市| 黔西县| 东兴市| 太康县| 周口市| 阿克陶县| 丹巴县| 信丰县| 石家庄市| 女性| 庄河市| 吴川市| 喀什市| 常熟市| 梁山县| 洪泽县| 云浮市| 南康市| 龙井市| 天气| 江津市| 普洱| 康马县| 秀山| 莱西市| 乐陵市| 高阳县| 正镶白旗| 盐池县| 万盛区| 阿克苏市| 南城县| 博兴县| 玉环县| 南皮县| 嘉定区| 新化县| 呼图壁县|