SpringBoot 方法执行异常重试

在调用第三方接口或者执行定时任务时,会出现网络抖动,连接超时等异常,所以需要重试,以提高程序的健壮性。

加入依赖:

<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方法换成自己方法就行了

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值