简单实现一个Java的Retry方法

15 篇文章 1 订阅

前言

最近有一个需求,要调用外部API满足业务逻辑,然后就用到了重试机制,又联想到不止API,其实很多中间件,比如Reids、各类MQ、Kafka,这些涉及到连接失败的读取写入需求都应该有重试机制。虽然最终需求使用了Spring自带的Retry机制,但是这一套还是太重了,思考了下就写了一个简易Retry功能分享出来。主要是利用Java的lambda表达式和线程接口实现有返回值和无返回值的重试。更多线程知识内容请点击【Java 多线程和锁知识笔记系列】

代码

public class Retry {

    public static <T> T retry(Callable<T> callable, int num) {
        Retry.check(num >= 1, "次数需要大于0");
        Exception exception = null;
        for (int i = 0; i < num; i++) {
            try {
                return callable.call();
            } catch (Exception e) {
                exception = e;
            }
        }
        throw Retry.runtimeException(exception);
    }

    public static void retry(Runnable runnable, int num) {
        Retry.check(num >= 1, "次数需要大于0");
        Exception exception = null;
        for (int i = 0; i < num; i++) {
            try {
                runnable.run();
                return;
            } catch (Exception e) {
                exception = e;
            }
        }
        throw Retry.runtimeException(exception);
    }

    public static void check(boolean check, String message) {
        if (!check) {
            if (Objects.isNull(message)) {
                throw new IllegalArgumentException("Check Requirement Error.");
            } else {
                throw new IllegalArgumentException("Check Requirement Error:" + message);
            }
        }
    }

    public static RuntimeException runtimeException(Exception exception) {
        Retry.check(Objects.nonNull(exception), "传入参数为null");
        if (exception instanceof RuntimeException) {
            throw new RuntimeException(exception);
        }
        throw new RuntimeException();
    }
}

使用样例

public class RetryTest implements Runnable{

    public static void main(String[] args) {
        RetryTest test=new RetryTest();
        //直接用Runnable做参数,可以换成Callable的实例
        Retry.retry(test, 3);
        //使用方法做参数
        Retry.retry(()->supplierTestNoReturn("a"), 3);
        //使用方法做参数接受返回值
        String back = Retry.retry(()->supplierTest("a"), 3);
        System.out.println(back);
        //直接写有返回值
        Retry.retry(()->{
            //TODO 业务逻辑调用外部API等等
            System.out.println("返回值");
            return "返回值";
        }, 3);
 		//直接写无返回值
        Retry.retry(()->{
            //TODO 业务逻辑调用外部API等等
            System.out.println("无返回值");
        }, 3);
    }

    //非静态直接使用
    public void test(){
        Retry.retry(()->normal("aa"), 3);
    }

    @Override
    public void run() {
        //TODO 业务逻辑、调用外部API等等
        System.out.println("Runnable Test");
    }

    public static String supplierTest(String str){
        //TODO 业务逻辑、调用外部API等等
        return "Test "+ str;
    }

    public static void supplierTestNoReturn(String str){
        //TODO 业务逻辑、调用外部API等等
        System.out.println("No Return "+str);
    }

    public String normal(String a){
        //TODO 业务逻辑、调用外部API等等
        return "Test";
    }
}

另一个版本

例子写出来以后,觉得也可以用Supplier去替代Callable也是可以的,只需要一些小改动,如下一样可以使用。

    public static <T> T retry(Supplier<T> supplier, int num) {
        Retry.check(num >= 1, "次数需要大于0");
        Exception exception = null;
        for (int i = 0; i < num; i++) {
            try {
                return supplier.get();
            } catch (Exception e) {
                exception = e;
            }
        }
        throw Retry.runtimeException(exception);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值