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

Java實(shí)現(xiàn)自定義重試工具類

 更新時(shí)間:2024年11月29日 11:29:08   作者:花開(kāi)不識(shí)君  
這篇文章主要為大家詳細(xì)介紹了如何基于Java實(shí)現(xiàn)自定義重試工具類,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

Spring-retry、guava的Retry都提供有重試工具,但二者均存在一個(gè)確缺點(diǎn),即如果重試等待過(guò)程中會(huì)一直阻塞工作線程,這對(duì)于在生產(chǎn)環(huán)境使用是存在風(fēng)險(xiǎn)的,如果存在大量長(zhǎng)時(shí)間等待的重試任務(wù)將會(huì)耗盡系統(tǒng)線程資源,下文基于線程池來(lái)完成一個(gè)簡(jiǎn)易的重試工具類。

核心思想

將任務(wù)封裝為一個(gè)task,將任務(wù)的重試放入可調(diào)度的線程池中完成執(zhí)行,避免在重試間隔中,線程陷入無(wú)意義的等待,同時(shí)將重試機(jī)制抽象為重試策略。

代碼實(shí)現(xiàn)

重試工具類

package com.huakai.springenv.retry.v2;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;

@Slf4j
public class RetryUtil {

    public static ExecutorService EXECUTOR = Executors.newFixedThreadPool(1);
    private static final ScheduledExecutorService SCHEDULER_EXECUTOR = Executors.newScheduledThreadPool(20);


    /**
     * 任務(wù)重試
     * @param actualTaskFunction 執(zhí)行的任務(wù)函數(shù)
     * @param resultHandler 任務(wù)結(jié)果處理器
     * @param maxRetry 最大重試次數(shù)
     * @param retryStrategy 重試策略
     */
    public static void retryTask(
            Function<Integer, String> actualTaskFunction,
            Function<String, Boolean> resultHandler,
            int maxRetry,
            RetryStrategy retryStrategy // 使用策略模式
    ) {
        Runnable runnable = new Runnable() {
            final AtomicInteger retryCount = new AtomicInteger(); // 當(dāng)前重試次數(shù)
            final AtomicInteger maxRetryCount = new AtomicInteger(maxRetry); // 最大重試次數(shù)

            @Override
            public void run() {
                String taskResult = actualTaskFunction.apply(retryCount.get()); // 執(zhí)行任務(wù)
                Boolean taskSuccess = resultHandler.apply(taskResult); // 處理任務(wù)結(jié)果
                if (taskSuccess) {
                    if (retryCount.get() > 1) {
                        log.info("任務(wù)重試成功,重試次數(shù):{}", retryCount.get());
                    }
                    return; // 任務(wù)成功,不需要再重試
                }

                if (retryCount.incrementAndGet() == maxRetryCount.get()) {
                    log.warn("任務(wù)重試失敗,重試次數(shù):{}", retryCount.get());
                    return; // 達(dá)到最大重試次數(shù),停止重試
                }

                // 獲取重試間隔
                long delay = retryStrategy.getDelay(retryCount.get());
                TimeUnit timeUnit = retryStrategy.getTimeUnit(retryCount.get());

                // 安排下次重試
                SCHEDULER_EXECUTOR.schedule(this, delay, timeUnit);
                log.info("任務(wù)重試失敗,等待 {} {} 后再次嘗試,當(dāng)前重試次數(shù):{}", delay, timeUnit, retryCount.get());
            }
        };
        EXECUTOR.execute(runnable); // 執(zhí)行任務(wù)
    }

    public static void main(String[] args) {
        // 使用指數(shù)退避重試策略
        RetryStrategy retryStrategy = new ExponentialBackoffRetryStrategy(1, TimeUnit.SECONDS);

        retryTask(
                retryCount -> "task result",
                taskResult -> Math.random() < 0.1,
                5,
                retryStrategy
        );
    }
}

重試策略

指數(shù)退避

package com.huakai.springenv.retry.v2;

import java.util.concurrent.TimeUnit;

/**
 * 指數(shù)退避重試策略
 */
public class ExponentialBackoffRetryStrategy implements RetryStrategy {
    private final long initialDelay;
    private final TimeUnit timeUnit;

    public ExponentialBackoffRetryStrategy(long initialDelay, TimeUnit timeUnit) {
        this.initialDelay = initialDelay;
        this.timeUnit = timeUnit;
    }

    @Override
    public long getDelay(int retryCount) {
        return (long) (initialDelay * Math.pow(2, retryCount - 1)); // 指數(shù)退避
    }

    @Override
    public TimeUnit getTimeUnit(int retryCount) {
        return timeUnit;
    }
}

自定義重試間隔時(shí)間

package com.huakai.springenv.retry.v2;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 自定義重試間隔時(shí)間的重試策略
 */
public class CustomerIntervalRetryStrategy implements RetryStrategy {
    // 配置重試間隔和時(shí)間單位
    List<RetryInterval> retryIntervals;


    public CustomerIntervalRetryStrategy(List<RetryInterval> retryIntervals) {
        this.retryIntervals = retryIntervals;
    }

    @Override
    public long getDelay(int retryCount) {
        return retryIntervals.get(retryCount).getDelay();
    }

    @Override
    public TimeUnit getTimeUnit(int retryCount){
        return retryIntervals.get(retryCount).getTimeUnit();
    }
}

固定間隔

package com.huakai.springenv.retry.v2;

import java.util.concurrent.TimeUnit;

/**
 * 固定間隔重試策略
 */
public class FixedIntervalRetryStrategy implements RetryStrategy {
    private final long interval;
    private final TimeUnit timeUnit;

    public FixedIntervalRetryStrategy(long interval, TimeUnit timeUnit) {
        this.interval = interval;
        this.timeUnit = timeUnit;
    }

    @Override
    public long getDelay(int retryCount) {
        return interval;
    }

    @Override
    public TimeUnit getTimeUnit(int retryCount) {
        return timeUnit;
    }
}

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

相關(guān)文章

最新評(píng)論

阳西县| 阳曲县| 静安区| 宁都县| 常熟市| 九龙县| 昌吉市| 东源县| 望江县| 亚东县| 南投市| 黄大仙区| 勐海县| 车险| 介休市| 松原市| 友谊县| 兴城市| 绥滨县| 旬阳县| 温宿县| 嵩明县| 临城县| 孟津县| 小金县| 襄城县| 鹤岗市| 潮州市| 西丰县| 海原县| 衡南县| 长海县| 富锦市| 西乌| 色达县| 永嘉县| 藁城市| 潼关县| 安丘市| 临洮县| 长汀县|