java重试两种实现方式

本文介绍了两种在Java中实现重试机制的方法:一是使用模板方法设计模式,通过定义RetryTemplate类及测试类进行实现;二是借助Spring AOP,包括引入依赖、定义注解ExceptionRetry、切面ExceptionRetryAspect以及测试类的编写和启动测试。通过启动APP并访问特定URL,可以观察到重试效果。
摘要由CSDN通过智能技术生成

1、java重试两种实现方式

1.1 模板方法

定义模板类

RetryTemplate

package com.mine.template;

public abstract class RetryTemplate {
   
	// 重试次数
	private int retryTime = 5;

	// 重试的睡眠时间
	private int sleepTime = 3000;

	public void setSleepTime(int sleepTime) {
   
		this.sleepTime = sleepTime;
	}

	public void setRetryTime(int retryTime) {
   
		this.retryTime = retryTime;
	}

	protected abstract void doAction() throws Exception;

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

测试类

TestRetryTemplate

package com.mine.template;

public class TestRetryTemplate extends RetryTemplate {
   
	private int i = 1;

	@Override
	protected void doAction() throws Exception {
   
		System.out.println("----------------");
		System.out.println(System.currentTimeMillis());
		if (i++ >= 3) {
   
			System.out.println("sucess");
		} else {
   
			System.out.println("failure");
			throw new Exception();
		}
	}

	public static void main
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值