0
点赞
收藏
分享

微信扫一扫

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

mjjackey 2022-04-28 阅读 28
java
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();
}
举报

相关推荐

0 条评论