当前位置:网站首页>聊聊一个注解实现接口重试
聊聊一个注解实现接口重试
2022-06-11 00:59:00 【Javaesandyou】
在实际工作中,重处理是一个非常常见的场景,比如:
- 发送消息失败。
- 调用远程服务失败。
- 争抢锁失败。
这些错误可能是因为网络波动造成的,等待过后重处理就能成功。通常来说,会用try/catch,while循环之类的语法来进行重处理,但是这样的做法缺乏统一性,并且不是很方便,要多写很多代码。然而spring-retry却可以通过注解,在不入侵原有业务逻辑代码的方式下,优雅的实现重处理功能。
[email protected]是什么?
spring系列的spring-retry是另一个实用程序模块,可以帮助我们以标准方式处理任何特定操作的重试。在spring-retry中,所有配置都是基于简单注释的。
2.使用步骤
(1) POM依赖
<dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency>
(2)启用@Retryable
@EnableRetry
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}(3)在方法上添加@Retryable
import com.mail.elegant.service.TestRetryService;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import java.time.LocalTime;
@Service
public class TestRetryServiceImpl implements TestRetryService {
@Override
@Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 1.5))
public int test(int code) throws Exception{
System.out.println("test被调用,时间:"+LocalTime.now());
if (code==0){
throw new Exception("情况不对头!");
}
System.out.println("test被调用,情况对头了!");
return 200;
}
}来简单解释一下注解中几个参数的含义:
- value:抛出指定异常才会重试。
- include:和value一样,默认为空,当exclude也为空时,默认所有异常。
- exclude:指定不处理的异常。
- maxAttempts:最大重试次数,默认3次。
- backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000L;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。
当重试耗尽时还是失败,会出现什么情况呢?
当重试耗尽时,RetryOperations可以将控制传递给另一个回调,即RecoveryCallback。Spring-Retry还提供了@Recover注解,用于@Retryable重试失败后处理方法。如果不需要回调方法,可以直接不写回调方法,那么实现的效果是,重试次数完了后,如果还是没成功没符合业务判断,就抛出异常。
(4)@Recover
@Recover
public int recover(Exception e, int code){
System.out.println("回调方法执行!!!!");
//记日志到数据库 或者调用其余的方法
return 400;
}可以看到传参里面写的是 Exception e,这个是作为回调的接头暗号(重试次数用完了,还是失败,我们抛出这个Exception e通知触发这个回调方法)。对于@Recover注解的方法,需要特别注意的是:
- 方法的返回值必须与@Retryable方法一致。
- 方法的第一个参数,必须是Throwable类型的,建议是与@Retryable配置的异常一致,其他的参数,需要哪个参数,写进去就可以了(@Recover方法中有的)。
- 该回调方法与重试方法写在同一个实现类里面。
- 复java面试,获取最新面试题资料。
(5)注意事项
- 由于是基于AOP实现,所以不支持类里自调用方法。
- 如果重试失败需要给@Recover注解的方法做后续处理,那这个重试的方法不能有返回值,只能是void。
- 方法内不能使用try catch,只能往外抛异常。
- @Recover注解来开启重试失败后调用的方法(注意,需跟重处理方法在同一个类中),此注解注释的方法参数一定要是@Retryable抛出的异常,否则无法识别,可以在该方法中进行日志处理。
3.总结
本篇主要简单介绍了Springboot中的Retryable的使用,主要的适用场景和注意事项,当需要重试的时候还是很有用的。
边栏推荐
- [traitement d'image] système multifonctionnel de traitement d'image basé sur l'interface graphique MATLAB [y compris le code source MATLAB 1876]
- 【圖像處理】基於matlab GUI多功能圖像處理系統【含Matlab源碼 1876期】
- switch case使用枚举类来比较
- How to change the administrator's Avatar in win11? Win11 method of changing administrator image
- The problem of slow response of cs-3120 actuator during use
- [traffic sign recognition] Based on Matlab GUI YCbCr feature extraction +bp neural network traffic sign recognition [including Matlab source code 1869]
- 2021-07-18 ROS notes - basics and communication
- QT database learning notes (II) QT operation SQLite database
- [leetcode] different binary search trees (recursion - recursion + memory search optimization - dynamic programming)
- Alibaba cloud Tianchi online programming training camp_ Task arrangement
猜你喜欢
![[leetcode] same tree + symmetric binary tree](/img/e5/40803ce66756c03737aa8991f7ec92.jpg)
[leetcode] same tree + symmetric binary tree
![[leetcode] flat multi-level bidirectional linked list](/img/7b/1631162f11a05e9323dd544fee6045.jpg)
[leetcode] flat multi-level bidirectional linked list

面试官:介绍一下你简历中的项目,细讲一点,附项目实战

ASEMI场效应管12N65参数,12N65规格书,12N65特征

Union find

Project sorting of Online Exercise System Based on gin and Gorm
![[leetcode] restore binary search tree](/img/92/14c4d670f318f93297040241a61c41.jpg)
[leetcode] restore binary search tree

(solved) latex -- cancel the superscript display of references in the text (gbt7714-2015 will lead to the default superscript reference) (tutorial on mixed use of superscript and flush)

2021-2-26 compilation of programming language knowledge points

Start with interpreting the code automatically generated by BDC, and explain the trial version of the program components of sapgui
随机推荐
Introduction and practice of QT tcp/udp network protocol (II) UDP communication
Method of using dism command to backup driver in win11 system
Dialog alertdialog, simpledialog, showmodalbottomsheet, showtoast shutter custom dialog
Question g: candy
Linux Installation MySQL database details
Coordonnées des capitales provinciales des provinces chinoises
QT database learning notes (II) QT operation SQLite database
[untitled]
Matlab array other common operation notes
MD61计划独立需求导入BAPI【按日维度/动态模板/动态字段】
flutter_ Swiper carousel map plug-in
(solved) latex -- cancel the superscript display of references in the text (gbt7714-2015 will lead to the default superscript reference) (tutorial on mixed use of superscript and flush)
[music] playing "over fire" based on MATLAB [including Matlab source code 1875]
Sword finger offer II 095 Longest common subsequence dynamic programming
视频压缩数据集TVD
Internet of things final assignment - sleep quality detection system (refined version)
【MATLAB】MATLAB图像处理基本操作
[leetcode] breadth first search level traversal general disassembly template
【MATLAB】图像增强(幂次变换、直方图规定化处理方法、平滑、锐化滤波)
[matlab] image restoration