重试某个方法 | Java | 使用泛型
646 ·
1 ·
2022-11-07 14:46:46
最新编辑时间: 2022-11-09 19:58:05
最新编辑原因:

定义需要重试的方法函数

public interface Function<T> {
    T func();
}

定义重试的基本逻辑

public interface Retry<T> {
    Logger log = LoggerFactory.getLogger(Retry.class);


    /**
     * 默认重试方法
     *
     * @param retry
     * @return
     */
    default T retry(Function<T> retry) {
        int seconds = 30;
        int retryTimes = 3; // 重试次数
        for (int i = 1; i <= retryTimes; i++) {
            try {
                return retry.func();
            } catch (Exception e) {
                int sleepSeconds = seconds * i;
                log.error("异常[次数:" + i + "/" + retryTimes + "],休眠" + sleepSeconds + "秒:", e);
                CommonUtils.sleep(sleepSeconds);
                if (i == retryTimes) {
                    throw new RuntimeException("已重试" + i + "次,仍异常,抛出异常", e);
                }
            }
        }
        throw new RuntimeException("Retry未知异常");
    }

}

使用示例


public class Demo implements Retry<DemoResp> {
    public void demo() {
	  // 这里会重试,成功后返回对应泛型的类变量
     DemoResp resp =  retry(() -> 您要重试的方法());   
    }
}

 


本作品系原创,采用《署名-非商业性使用-禁止演绎4.0 国际》许可协议.转载请说明出处
本文链接:https://www.upupor.com/u/22110706409919307776 复制
评论1
upupor
upupor 楼主 管理员
2023-02-06 09:02:59 ·  回复 · 1#
推荐阅读