utils009_非幂等性操作的重试机制

package com.jingsong.test;

import cn.hutool.core.util.RandomUtil;

/**
 * @author jingsong
 * @date 2022/4/27 23:25
 * @desc 进行某些非幂等性操作时(例如查询数据库),少数情况可能需要多次重试才能成功
 */
public class RetryTest {

    public static void main(String[] args) {

        String result = RetryUtil.retry(() -> {
            // 模拟出来一个异常
            if (RandomUtil.randomBoolean()) {
                int i = 1 / 0;
            }
            return "方法执行成功啦~";
        }, 3, 1000L);
        System.out.println("result = " + result);
    }
}

@SuppressWarnings("all")
class RetryUtil {

    public static int DEFAULT_RETRY_TIMES = 3;
    public static long DEFAULT_WAIT_TIME = 1000L;

    public static <T> T retry(Function<T> func) {
        return retry(func, DEFAULT_RETRY_TIMES, DEFAULT_WAIT_TIME);
    }


    public static <T> T retry(Function<T> func, int retryTimes, long waitTime) {

        for (int i = 1; i <= retryTimes; i++) {
            try {
                return func.apply();
            } catch (Exception e) {
                // log function error
                System.out.println("第" + i + "次出现异常啦~" + e);
                // 不要多等一次
                if (i == retryTimes) break;
                try {
                    Thread.sleep(waitTime);
                } catch (InterruptedException e1) {
                    // log sleep error
                }
            }
        }
        throw new RuntimeException("retry too many times:" + retryTimes);
    }

}

interface Function<T> {
    T apply();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值