中断重试机制

原文:https://my.oschina.net/u/566591/blog/1526551

还是用spring-retry吧………………

中断重试代码

/**
 * 中断重试机制
 */
public abstract class RetryTemplate {

	private static final Logger log = LoggerFactory.getLogger(QuarantineSynchronizationJob.class);
	//这里读取的配置文件,和原文有一点差别
	//重试次数
	@NacosValue("retry.retryTime")
	private Integer retryTime;
	//重试时间
	@NacosValue("retry.sleepTime")
	private Integer sleepTime;

	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;
	}

	/**
	 * 重试的业务执行代码
	 * 失败时请抛出一个异常
	 *
	 * 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) {
				log.error("业务执行出现异常,第"+ i +"次重试 e: {}", e);
				Thread.sleep(sleepTime);
			}
		}
		return null;
	}

	public Object submit(ExecutorService executorService) {
		if (executorService == null) {
			throw new IllegalArgumentException("please choose executorService!");
		}
		Future<Object> submit = executorService.submit((Callable) () -> execute());
		return submit;
	}

调用

/**
		 * 异常重试
		 */
		Object ans = new RetryTemplate() {
			@Override
			protected Object doBiz() throws Exception {
				try{
				
					//执行逻辑处理
					
				}catch (Exception e){
					logger.error("执行bacterinClassJob-----------定时Exception 异常:" + ExceptionUtil.getExceptionInfo(e));
					e.printStackTrace();
				}
				return ReturnT.SUCCESS;
			}
		}.setRetryTime(retryConfig.getRetryTime()).setSleepTime(retryConfig.getSleepTime()).execute();

		//setRetryTime : 重试次数
		//setSleepTime :重试时间
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值