Java——Retry重试机制详解

【博文目录>>>】


【项目源码>>>】

第一步、引入maven依赖

你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>wjc.spring.boot</groupId>
    <artifactId>017-spring-boot-retry</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>wjc.spring</groupId>
        <artifactId>boot</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
    </dependencies>
</project>

第二步、添加@Retryable和@Recover注解

@Service
public class RemoteService {
    @Retryable(
            value = {RemoteAccessException.class},
            maxAttempts = 3,
            backoff = @Backoff(delay = 5000L, multiplier = 1))
    public void call() {

        int i = 1 + (int) (Math.random() * 5);

        if (i % 3 != 0) {
            System.out.println("RPC调用异常");
            throw new RemoteAccessException("RPC调用异常");
        }

        System.out.println("方法成功调用");
    }

    @Recover
    public void recover(RemoteAccessException e) {
        System.out.println("重试都没有成功,在这里做数据还原");
        e.printStackTrace();
    }
}

@Retryable注解

被注解的方法发生异常时会重试
value:指定发生的异常进行重试
include:和value一样,默认空,当exclude也为空时,所有异常都重试
exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试
maxAttemps:重试次数,默认3
backoff:重试补偿机制,默认没有

@Backoff注解

delay:指定延迟后重试
multiplier:指定延迟的倍数,比如delay=5000l,multiplier=2时,第一次重试为5秒后,第二次为10秒,第三次为20秒

@Recover

当重试到达指定次数时,被注解的方法将被回调,可以在该方法中进行日志处理。需要注意的是发生的异常和入参类型一致时才会回调

第三步、SpringBoot方式启动容器、测试

添加@EnableRetry注解,启用重试功能

@EnableRetry
@SpringBootApplication
public class RetryApplication {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(RetryApplication.class, args);
        RemoteService remoteService = SpringContextUtils.getBean(RemoteService.class);
        remoteService.call();
    }
}

运行结果

在这里插入图片描述

参考

https://github.com/spring-projects/spring-retry

发布了535 篇原创文章 · 获赞 1139 · 访问量 164万+

猜你喜欢

转载自blog.csdn.net/DERRANTCM/article/details/90377679