Java retry

简单的用Java实现重试

package com.spring.demo_hello.service;

import org.springframework.stereotype.Service;

@Service
public class RetryService {
    public String testRetry() {
        System.out.println("start...");
        try {
            Object ans = new RetryTemplate() {
                @Override
                protected Object doBiz() throws Exception {
                    int temp = (int) (Math.random() * 10) + 5;
                    System.out.println(temp);
                    if (temp > 3) {
                        throw new Exception("generate value bigger then 3! need retry");
                    }
                    return temp;
                }
            }.setRetryTime(6).setSleepTime(1000).execute();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end...");
        return "dddd";
    }
}

实现类如下:

package com.spring.demo_hello.service;

public abstract class RetryTemplate {

    private static final int DEFAULT_RETRY_TIME = 1;
    private int retryTime = DEFAULT_RETRY_TIME;
    private int sleepTime = 0;// 重试的睡眠时间

    public int getSleepTime() {
        return sleepTime;
    }

    public RetryTemplate setSleepTime(int sleepTime) {
        if (sleepTime < 0) {
            throw new IllegalArgumentException("sleepTime should equal or bigger than 0");
        }
        this.sleepTime = sleepTime;
        return this;
    }

    public int getRetryTime() {
        return retryTime;
    }

    public RetryTemplate setRetryTime(int retryTime) {
        if (retryTime <= 0) {
            throw new IllegalArgumentException("retryTime should bigger than 0");
        }
        this.retryTime = retryTime;
        return this;
    }

    /**
     * 重试的业务执行代码
     * 失败时请抛出一个异常
     * <p>
     * todo 确定返回的封装类,根据返回结果的状态来判定是否需要重试
     *
     * @return
     */
    protected abstract Object doBiz() throws Exception; //预留一个doBiz方法由业务方来实现,在其中书写需要重试的业务代码,然后执行即可

    public Object execute() throws InterruptedException {
        for (int i = 0; i < retryTime; i++) {
            try {
                return doBiz();
            } catch (Exception e) {
                Thread.sleep(sleepTime);
            }
        }
        return null;
    }
}

 

posted @ 2020-08-07 00:39  6xiong  阅读(315)  评论(0编辑  收藏  举报