在调用第三方接口或者执行定时任务时,会出现网络抖动,连接超时等异常,所以需要重试,以提高程序的健壮性。
加入依赖:
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
在主类或者需要开启重试的类上加上@EnableRetry
注解,表示启用重试机制。
测试代码:
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@EnableRetry
@Component()
public class AccessCarTaskTest {
private int i = 1;
@Scheduled(cron = "0 */1 * * * ?")
//重试 最多重试15次,每2秒重试1次;maxAttempts 最大重试次数 delay 重试间隔时间 multiplier 间隔时间倍数
@Retryable(value = Exception.class, maxAttempts = 15, backoff = @Backoff(delay = 2000, multiplier = 1))
public void accessCarInfo() {
test();
}
public void test() {
System.out.println("第" + i + "次执行方法!");
System.out.println("第" + i + "次执行方法时间:" + LocalDateTime.now());
i++;
if (i < 7) {
throw new RuntimeException("抛出异常");
}
System.out.println("结束执行任务!" + LocalDateTime.now());
}
}
有需要的朋友把其中的test方法换成自己方法就行了