当前位置:网站首页>Talk about an annotation implementation interface retry
Talk about an annotation implementation interface retry
2022-06-11 02:11:00 【Javaesandyou】
In practice , Reprocessing is a very common scenario , such as :
- Failed to send message .
- Call to remote service failed .
- Lock contention failed .
These errors may be caused by network fluctuations , After waiting, reprocessing can succeed . Generally speaking , Will use try/catch,while Loop and so on , But such an approach lacks uniformity , And it's not very convenient , Write a lot more code . However spring-retry But through annotation , Without invading the original business logic code , Elegant implementation of reprocessing function .
[email protected] What is it? ?
spring Series of spring-retry Is another utility module , It can help us deal with the retry of any specific operation in a standard way . stay spring-retry in , All configurations are based on simple comments .
2. Use steps
(1) POM rely on
<dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency>
(2) Enable @Retryable
@EnableRetry
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}(3) Add... To the method @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 Called , Time :"+LocalTime.now());
if (code==0){
throw new Exception(" Something's wrong !");
}
System.out.println("test Called , The situation is right !");
return 200;
}
}Let's briefly explain the meaning of several parameters in the annotation :
- value: Throw the specified exception to retry .
- include: and value equally , The default is empty. , When exclude Also empty , Default to all exceptions .
- exclude: Specifies the exception not to be handled .
- maxAttempts: max retries , Default 3 Time .
- backoff: Retry the wait policy , By default @Backoff,@Backoff Of value The default is 1000L, We set it to 2000L;multiplier( Specify the delay times ) The default is 0, Indicates a fixed pause 1 Try again in seconds , If you put multiplier Set to 1.5, The first try is 2 second , The second time is 3 second , The third time is 4.5 second .
When the retry runs out, it still fails , What will happen ?
When the retry runs out ,RetryOperations You can pass control to another callback , namely RecoveryCallback.Spring-Retry It also provides @Recover annotation , be used for @Retryable Processing method after retry failure . If callback method is not required , You can not write callback methods directly , So what is the effect , After the number of retries is completed , If it still fails, it does not meet the business judgment , Throw an exception .
(4)@Recover
@Recover
public int recover(Exception e, int code){
System.out.println(" Callback method execution !!!!");
// Log to database Or call the rest of the methods
return 400;
}You can see that it says Exception e, This is the connector code as a callback ( The number of retries has run out , Or failure , We throw this Exception e The notification triggers this callback method ). about @Recover Method of annotation , Here's the thing to watch out for :
- The return value of the method must be the same as @Retryable The method is consistent .
- The first parameter of the method , Must be Throwable Type of , The suggestion is to go with @Retryable Abnormally consistent configuration , Other parameters , Which parameter is required , Just write it in (@Recover Some methods ).
- The callback method and the retry method are written in the same implementation class .
- complex java interview , Get the latest interview questions .
(5) matters needing attention
- Because it's based on AOP Realization , Therefore, self calling methods in classes are not supported .
- If the retry fails, you need to give @Recover The annotation method is used for subsequent processing , The retry method cannot have a return value , Can only be void.
- Cannot be used inside method try catch, You can only throw exceptions out .
- @Recover Annotation to open the method of calling after retry failure. ( Be careful , It needs to be in the same class as the reprocessing method ), The method parameter of this annotation must be @Retryable Exception thrown , Otherwise, I can't recognize , Log processing can be done in this method .
3. summary
This article mainly introduces Springboot Medium Retryable Use , Main applicable scenarios and precautions , It's useful when you need to try again .
边栏推荐
- 中国各省份省会的坐标
- Project sorting of Online Exercise System Based on gin and Gorm
- [traffic sign recognition] Based on Matlab GUI YCbCr feature extraction +bp neural network traffic sign recognition [including Matlab source code 1869]
- 20n10-asemi medium and small power MOS transistor 20n10
- [leetcode] balanced binary tree
- Task04: String
- Win11画图工具没了怎么重新安装
- Secret
- Video compression data set TVD
- Basic underlying principles of concurrent programming (4)
猜你喜欢

ABAP CDS实现多行字段内容拼接

Interviewer: let me introduce the items in your resume. Tell me more about them, and attach the actual project

Win11画图工具没了怎么重新安装

Win11系统使用DISM命令备份驱动程序的方法

QT widget's simple serial port assistant (qserialport)

Oracle collects statistics

(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 blue and white porcelain based on MATLAB [including Matlab source code 1873]](/img/cf/63b04080867e93ab2e00e2e21b37df.jpg)
[music] playing blue and white porcelain based on MATLAB [including Matlab source code 1873]

(已解决)Latex--取消正文中参考文献引用的上标显示(gbt7714-2015会导致默认上角标引用)(上角标&平齐标混合使用教程)

---Arrange numbers---
随机推荐
SAP smartforms text content manual wrap output
CRS-4544 & ORA-09925
[leetcode] balanced binary tree
Introduction and practice of QT tcp/udp network protocol (II) UDP communication
中国各省份省会的坐标
软测人都该知道的七大原则
Wrong question (character array)
[BSP video tutorial] BSP video tutorial issue 17: single chip microcomputer bootloader topic, startup, jump configuration and various usage of debugging and downloading (2022-06-10)
Oracle收集统计信息
【Qt】error: QApplication: No such file or directory 解决方案
MD61计划独立需求导入BAPI【按日维度/动态模板/动态字段】
Initialize the one-dimensional array a correctly
flutter_ Swiper carousel map plug-in
Contest2902 - following Tang Kelian's programming: sequence structure question d: area 201502 question f: persistence of supporting college students in Ludian earthquake
(已解决)Latex--取消正文中参考文献引用的上标显示(gbt7714-2015会导致默认上角标引用)(上角标&平齐标混合使用教程)
[Haas hands on] creative case of new video program launch we started the first phase together E01: Internet of things engineers started the remote control manipulator with you
接口自动化核心知识点浓缩,为面试加分
Treatment of small fish
基于Gin、Gorm实现的在线练习系统之项目梳理
我们对于产业互联网的认识,或许更多的要跳出现有的逻辑之外