接口调用重试@Retryable重试机制

本文介绍了如何在Spring中使用@Retryable注解实现接口调用的重试机制,包括配置、使用示例以及注意事项。在服务中遇到异常时,会按照设定的次数和间隔进行重试,最后如果所有尝试都失败,则调用@Recover注解的方法进行后续处理。此外,还提醒了内部方法调用可能导致重试失效的问题。

@Retryable重试机制

当调用其他接口失败的时候,我们希望可以多次重试调用该接口,spring中已经有封装好的相关注解,直接拿来使用即可

1 引入相关依赖

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>

2.相关代码

入口类中添加@EnableRetry注解

@SpringBootApplication
@EnableRetry
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

Controller

@RestController
@RequestMapping(value = "/test")
public class TestController {

    @Autowired
    private Demo1Service demo1Service;

    @GetMapping(value = "/test")
    public void test () {
        try {
            demo1Service.test();
        } catch (Exception e) {
            System.out.println("this is catch," + new Date());
        }
    }
  
}

Service

@Service
public class Demo1Service {

    // 共尝试3次调用,调用间隔5s,以后每次事件间隔*2
    @Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(value = 5000, multiplier = 2))
    public void test () {
        System.out.println("this is Demo1Service.test()," + new Date());
        throw new RuntimeException("这里是自定义异常");
    }

    // 当在自定义的重试范围内均未调用成功,则进入到此方法中
    @Recover
    public void recover (Exception e) {
        System.out.println("this is recover(), " + e.getMessage() + "," + new Date());
    }

}

运行结果

this is Demo1Service.test(),Sun Apr 10 15:08:00 CST 2022
this is Demo1Service.test(),Sun Apr 10 15:08:05 CST 2022
this is Demo1Service.test(),Sun Apr 10 15:08:15 CST 2022
this is recover(), 这里是自定义异常,Sun Apr 10 15:08:15 CST 2022

温馨提示: 由于retry用到了aspect增强,所有会有aspect的坑,就是方法内部调用时,会使aspect增强失效,那么retry当然也会失效。

@Service
public class Demo1Service {

    public void test () {
        // 此时test1是本类中的一个内部方法,所以test1的重试机制会失效
        // 建议将test1放到其他service中
        test1();
    }

    // 共尝试3次调用,调用间隔5s,以后每次事件间隔*2
    @Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(value = 5000, multiplier = 2))
    public void test1 () {
        System.out.println("this is Demo1Service.test1()," + new Date());
        throw new RuntimeException("这里是自定义异常");
    }

    // 当在自定义的重试范围内均未调用成功,则进入到此方法中
    @Recover
    public void recover () {
        System.out.println("this is recover(), " + e.getMessage() + "," + new Date());
    }

}

简单案例

@Service
public class Demo1Service {

    @Autowired
    private Demo2Service demo2Service;

    public void test () {
        Integer[] arr = {6,8,10,12,14};
        for (Integer n : arr) {
            demo2Service.test1(n);
        }
    }

}
@Service
public class Demo2Service {

    // 共尝试3次调用,调用间隔5s,以后每次事件间隔*2
    @Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(value = 5000, multiplier = 2))
    public void test1 (Integer n) {
        System.out.println("this is Demo1Service.test1(),参数:" + n + " 执行时间:" + new Date());
        if (n == 10) {
            throw new RuntimeException("这里是自定义异常");
        }
    }

    // 当在自定义的重试范围内均未调用成功,则进入到此方法中
    @Recover
    public void recover (Exception e) {
        System.out.println("this is recover(), " + e.getMessage() + "," + new Date());
    }

}

运行结果

this is Demo1Service.test1(),参数:6 执行时间:Sun Apr 10 15:28:17 CST 2022
this is Demo1Service.test1(),参数:8 执行时间:Sun Apr 10 15:28:17 CST 2022
this is Demo1Service.test1(),参数:10 执行时间:Sun Apr 10 15:28:17 CST 2022
this is Demo1Service.test1(),参数:10 执行时间:Sun Apr 10 15:28:22 CST 2022
this is Demo1Service.test1(),参数:10 执行时间:Sun Apr 10 15:28:32 CST 2022
this is recover(), 这里是自定义异常,Sun Apr 10 15:28:32 CST 2022
this is Demo1Service.test1(),参数:12 执行时间:Sun Apr 10 15:28:32 CST 2022
this is Demo1Service.test1(),参数:14 执行时间:Sun Apr 10 15:28:32 CST 2022
### 使用 `@Retryable` 注解实现轮询调用 为了使用 `@Retryable` 注解来实现轮询调用,首先需要确保已经在应用程序中启用了 Spring Retry 功能。这可以通过在配置类上添加 `@EnableRetry` 来完成[^1]。 #### 启用 Spring Retry ```java @Configuration @EnableRetry public class AppConfig { } ``` 接下来定义一个带有 `@Retryable` 的方法用于模拟轮询操作。此注解允许指定重试条件以及最大尝试次数等参数: #### 定义可重试的方法 ```java @Service public class PollingService { private static final Logger logger = LoggerFactory.getLogger(PollingService.class); @Autowired RestTemplate restTemplate; @Retryable( value = {RestClientException.class}, maxAttempts = 5, backoff = @Backoff(delay = 2000, multiplier = 2)) public String pollForData(String url) throws RestClientException { try { ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { return "Success"; } throw new HttpClientErrorException(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { logger.error("Failed to get data from {}", url, e); throw e; } } @Recover public String recover(RestClientException ex, String url){ logger.warn("All retries failed for URL:{}",url); return "Failure"; } } ``` 上述代码片段展示了如何通过 `@Retryable` 和 `@Recover` 注解组合起来处理失败情况下的自动恢复机制。每当遇到 `RestClientException` 类型的异常时就会触发一次新的尝试直到达到设定的最大次数为止;而一旦所有的重试都未能成功,则会转交给由 `@Recover` 标记的方法来进行最终错误处理并返回默认的结果给调用者。 对于线程安全性方面的问题,Spring Retry 中使用的 `RetryTemplate.execute()` 方法是线程安全的设计,它利用了 `ThreadLocal` 变量来存储每次执行期间特定于当前线程的状态信息,从而保证即使在同一时间多个线程并发访问也不会互相干扰[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

难过的风景

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值