栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 方法执行异常重试

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot 方法执行异常重试

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

加入依赖:


    org.springframework.retry
    spring-retry

在主类或者需要开启重试的类上加上@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方法换成自己方法就行了

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/336788.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号