Spring Boot集成Spring Retry快速入门Demo

1.Retry介绍

Spring Retry

提供了自动重新调用失败的操作的功能。这在错误可能是暂时的(例如瞬时网络故障)的情况下很有用。从2.2.0版本开始,重试功能已从Spring Batch中撤出,成为一个独立的新库:Spring Retry

使用场景

在日常开发过程中,难免会与第三方接口发生交互,例如:短信发送、远程服务调用、争抢锁等场景,当正常调用发生异常时,例如:网络抖动,这些间歇性的异常在一段时候之后会自行恢复,程序为了更加健壮并且更不容易出现故障,需要重新触发业务操作,以防止间歇性的异常对程序照成的影响。

tips:幂等性

非幂等的情况下要小心使用重试。HTTP/1.1中对幂等性的定义是:一次和多次请求某一个资源对于资源本身应该具有同样的结果(网络超时等问题除外)。也就是说,其任意多次执行对资源本身所产生的影响均与一次执行的影响相同。

2.代码工程

实验目标:模拟三方接口异常,触发重试

pom.xml

xml 复制代码
<?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">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>


    <artifactId>SpringRetry</artifactId>


    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--retry-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>


    </dependencies>
</project>

application.yaml

properties 复制代码
server:
  port: 8088

RemoteApiService.java

  • @Retryable注解,value值表示当哪些异常的时候触发重试,maxAttempts表示最大重试次数默认为3,delay表示重试的延迟时间,multiplier表示上一次延时时间是这一次的倍数。

  • @Recover注解,当重试次数达到设置的次数的时候,还是失败抛出异常,执行的回调函数。

java 复制代码
package com.et.retry.service;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.time.LocalTime;


@Service
public class RemoteApiService {


    private Logger logger = LoggerFactory.getLogger(getClass());


    @Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 1.5))
    public boolean pay(int num) throws Exception{
        logger.info("invoke third method");
        logger.info("do something... {}", LocalDateTime.now());
        //mock exception
        if(num==0) {
            throw new Exception("error,need retry");
        }
        return true;


    }
    @Recover
    public boolean recover(int num) throws Exception {
        logger.info("recover ... {},{}", num, LocalDateTime.now());
        return false;
    }


}

DemoApplication.java

在主类上加上@EnableRetry注解,表示启用重试机制。

java 复制代码
package com.et.retry;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.retry.annotation.EnableRetry;


@SpringBootApplication
@EnableRetry
public class DemoApplication {


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

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

3.测试

编写测试类

java 复制代码
package com.et.retry;


import com.et.retry.service.RemoteApiService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;




@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoTests {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    RemoteApiService remoteApiService;


    @Before
    public void before()  {
        log.info("init some data");
    }
    @After
    public void after(){
        log.info("clean some data");
    }
    @Test
    public void execute() throws Exception {
        log.info("pay result:"+remoteApiService.pay(0));
    }


}

运行测试方法,结果如下

css 复制代码
2024-04-03 10:35:54.738 INFO 13096 --- [ main] com.et.retry.DemoTests : init some data
2024-04-03 10:35:54.756 INFO 13096 --- [ main] com.et.retry.service.RemoteApiService : invoke third method
2024-04-03 10:35:54.759 INFO 13096 --- [ main] com.et.retry.service.RemoteApiService : do something... 2024-04-03T10:35:54.758
2024-04-03 10:35:56.766 INFO 13096 --- [ main] com.et.retry.service.RemoteApiService : invoke third method
2024-04-03 10:35:56.766 INFO 13096 --- [ main] com.et.retry.service.RemoteApiService : do something... 2024-04-03T10:35:56.766
2024-04-03 10:35:59.776 INFO 13096 --- [ main] com.et.retry.service.RemoteApiService : invoke third method
2024-04-03 10:35:59.776 INFO 13096 --- [ main] com.et.retry.service.RemoteApiService : do something... 2024-04-03T10:35:59.776
2024-04-03 10:35:59.776 INFO 13096 --- [ main] com.et.retry.service.RemoteApiService : recover ... 0,2024-04-03T10:35:59.776
2024-04-03 10:35:59.776 INFO 13096 --- [ main] com.et.retry.DemoTests : pay result:false
2024-04-03 10:35:59.778 INFO 13096 --- [ main] com.et.retry.DemoTests : clean some data

4.引用

相关推荐
IT_陈寒2 小时前
Java中equals方法比了个寂寞?原来这才是正确的重写姿势
前端·人工智能·后端
Thneonl2 小时前
Celery 生产踩坑:1000 任务积压与 acks_late 双重执行
后端·python
卷福同学2 小时前
第一次当面试官有感
后端·面试
苏三说技术2 小时前
为什么越来越多人用 OnlyOffice?
后端
IT枫斗者枫哥2 小时前
MyBatis一对多分页:LIMIT 20,为什么凑不齐20个订单?
java·数据库
知守观2 小时前
@Transactional 事务失效排查,try-catch 吞异常导致回滚失败(附源码分析)
后端·spring
羑悻2 小时前
Codex + Seed-2.1-pro 实测:多模态理解 + Coding Agent 能扛住真实仓库吗?
后端
代码方舟2 小时前
Java数据工程:利用天远全网运营商三要素优化线上实名认证合规体验
java·人工智能
颜进强2 小时前
14 · NestJS ExecutionContext 执行上下文:守卫、拦截器、过滤器拿到的"同一个 context",为什么能力不一样?
前端·后端·ai编程
小小张说故事2 小时前
Python 多线程为什么跑不快?asyncio 入门指南:异步并发从零上手
后端·python