spring-retry简单例子

在实际工作过程中,重试是一个经常使用的手段。比如MQ发送消息失败,会采取重试手段,比如工程中使用RPC请求外部服务,可能因为网络波动出现超时而采取重试手段......可以看见重试操作是非常常见的一种处理问题,系统设计的手段。

spring-retry概念介绍

java简单的重试代码

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class retry {

    public static void main(String[] args) throws InterruptedException {
        int tryTimes = 4;     //重试次数
        int intervalTime = 10;//时间间隔
        int redo = 0;
        while (redo < tryTimes + 1) {   //MAXTRY为最大重试次数
            try {
                doSomething(redo);  	//可能发生特殊情况的方法
                break;              	//执行成功后直接退出此循环
            } catch (Exception e) {
                redo++;					//异常时,重试次数增加
//               优先使用TimeUnit类中的sleep() 而不是Thread.sleep(4*60*1000);
                TimeUnit.SECONDS.sleep(intervalTime);
//                TimeUnit.MINUTES.sleep(4);
//                TimeUnit.HOURS.sleep(1);
//                TimeUnit.DAYS.sleep(1);

                continue;             //结束本次循环
            }
        }
    }

    /***
     * 业务方法
     * @param redo
     * @throws Exception
     */
    private static void doSomething(int redo) throws Exception {
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (redo == 0 || redo == 1) {
            System.err.println("第" + redo + "次执行dosomething()" + "开始执行时间:" + s.format(new Date()));
            throw new RuntimeException();
        }
        System.err.println("第" + redo + "次执行dosomething()" + "开始执行时间:" + s.format(new Date()));
    }
}
Spring-Retry却能够以一种很优雅的方式解决这种问题。

Spring-retry提供了RetryOperations接口的实现类RetryTemplate。通过RetryTemplate来完成重试,下面是使用RetryTemplate重试的一个简单例子。

public class Main {

    public static void main(String[] args) throws Exception {
        RetryTemplate template = new RetryTemplate();
        TimeoutRetryPolicy policy = new TimeoutRetryPolicy();

        template.setRetryPolicy(policy);

        String result = template.execute(
                new RetryCallback<String, Exception>() {
                    public String doWithRetry(RetryContext arg0) throws Exception {
                        return "Retry";
                    }
                }
        );
        System.out.println(result);
    }
}
代码定义了TimeoutRetryPolicy策略,TimeoutRetryPolicy超时时间默认是1秒。TimeoutRetryPolicy超时是指在execute方法内部,从open操作开始到调用TimeoutRetryPolicy的canRetry方法这之间所经过的时间。这段时间未超过TimeoutRetryPolicy定义的超时时间,那么执行操作,否则抛出异常。

在RetryOperations接口中还会看到RecoveryCallback这个参数。当重试执行完闭,操作还未成为,那么可以通过RecoveryCallback完成一些失败事后处理。

public class Main {

    public static void main(String[] args) throws Exception {
        RetryTemplate template = new RetryTemplate();

        SimpleRetryPolicy policy = new SimpleRetryPolicy();
        policy.setMaxAttempts(2);

        template.setRetryPolicy(policy);

        String result = template.execute(
                new RetryCallback<String, Exception>() {
                    public String doWithRetry(RetryContext arg0) throws Exception {
                        throw new NullPointerException("nullPointerException");
                    }
                }
                ,
                new RecoveryCallback<String>() {
                    public String recover(RetryContext    context) throws Exception {
                        return "recovery callback";
                    }
                }
        );
        System.out.println(result);
    }
}
上面的代码重试两次后,仍然失败,RecoveryCallback被调用,返回”recovery callback”。如果没有定义RecoveryCallback,那么重试2次后,将会抛出异常。

参考文章:http://blog.csdn.net/Revivedsun/article/details/53401335

参考文章:https://docs.spring.io/spring-batch/reference/html/retry.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值