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

Springboot接口重试

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

Springboot接口重试

1:在与外部接口通信的时候,如对接第三方系统,一般情况不知道http协议是否成功,最好加上重试。

spring-retry提供了相关代码。

新增pom


            org.springframework.retry
            spring-retry
        

新增service

@Service
public class TestService {
    private int code = 0;

    @Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 1000,multiplier = 1.5))
    public int test() throws Exception{
//        code++;
//        if (code % 3 != 0){
//            throw new Exception("错错错错错错错");
//        }
        int i = new Random().nextInt(2);
        System.out.println("随机数为====================" + i);
        System.out.println(2/i);
        return 200;
    }
}

记得在启动类新增注解

@SpringBootApplication
@EnableRetry
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application .class, args);
    }

}

在没有用spring-retry之前写过基于函数式接口的重试

@FunctionalInterface
public interface Retry {
    
    boolean action();

    
    public static final int MAX_RETRY_COUNT_5 = 5;

    
    public static final int INTERVAL_SECONDS_3 = 3;

    
    public static void retry(int maxRetryCount, Retry workFunction,
                             Retry intervalFunctin) {
        // 如果最大重试次数小于1,或重试工作函数为空,直接返回
        if (maxRetryCount < 1 || null == workFunction) {
            return;
        }

        // 执行最大重试次数次重试操作
        for (int i = 0; i < maxRetryCount; i++) {
            // 如果本次的执行结果为成功,则不再继续重试
            if (workFunction.action()) {
                return;
            }

            // 如果本次的执行结果为失败,则执行重试间隔函数之后继续重试执行工作函数
            intervalFunctin.action();
        }

        System.out.println("have tried maxRetryCount!");
    }

    
    public static boolean doSleep(int seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
            return true;
        } catch (InterruptedException e) {
            System.out.println("exception occurs when doSleep, e = " + e);
            return false;
        }
    }
}





public class Test {
    public static void main(String[] args) {
        // 工作函数入参
        boolean param = true;
        Retry.retry(Retry.MAX_RETRY_COUNT_5, () -> doWork(param), () -> Retry.doSleep(Retry.INTERVAL_SECONDS_3));
    }

    
    public static boolean doWork(boolean param) {
        System.out.println("start to do some work...");

        // 为简单期间,将入参param的值取反,模拟工作函数的执行结果
        boolean result = !param;
        if (result) {
            System.out.println("doWork success!");
        } else {
            System.out.println("doWork failed!");
        }

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

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

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