spring-retry简单例子

来源:互联网 发布:会计核算软件 编辑:程序博客网 时间:2024/05/20 13:04

在实际工作过程中,重试是一个经常使用的手段。比如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

原创粉丝点击