当前位置:网站首页>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 .
边栏推荐
- [matlab] image restoration
- (已解决)Latex--取消正文中参考文献引用的上标显示(gbt7714-2015会导致默认上角标引用)(上角标&平齐标混合使用教程)
- Within one month, the broadcasting volume has increased by 9million, and station B has three traffic growth passwords!
- npm ERR Fix the upstream dependency conflict, or retry
- Fallible point--
- Task01: be familiar with the basic process of news recommendation system
- Asemi FET 12n65 parameters, 12n65 specifications, 12n65 features
- Day code 300 lines learning notes day 22
- 接口自动化核心知识点浓缩,为面试加分
- switch case使用枚举类来比较
猜你喜欢

How to reinstall win11 drawing tool when it is missing

CRS-5017

Fb02 edit coding block field

Record the actual record of my question brushing
![[leetcode] path sum II (first glimpse recursion + backtracking)](/img/a8/54920e54a026ebef3eb0a1336e5b62.jpg)
[leetcode] path sum II (first glimpse recursion + backtracking)

Fallible point--

Understand the role of before and after Clearfixafter clear floating

CRS-4544 & ORA-09925

Go develop web

flutter_ Swiper carousel map plug-in
随机推荐
[matlab] basic operation of MATLAB image processing
CRS-4544 & ORA-09925
Alibaba cloud Tianchi online programming training camp_ Task arrangement
Go develop web
Introduction and practice of QT tcp/udp network protocol (supplementary)
[music] playing blue and white porcelain based on MATLAB [including Matlab source code 1873]
Switch case uses enumeration classes to compare
爱思唯尔---Elseviewer---预印本在线发表通知
QT database learning notes (II) QT operation SQLite database
JS basic part hand exercises
[matlab] image enhancement (power transformation, histogram specification processing method, smoothing and sharpening filtering)
Dialog alertdialog, simpledialog, showmodalbottomsheet, showtoast shutter custom dialog
【圖像處理】基於matlab GUI多功能圖像處理系統【含Matlab源碼 1876期】
Secret
Virtual joystick of QT quick QML instance
Me11/me12 purchase information record and condition record creation and update bapi:me_ INFORECORD_ MAINTAIN_ MULTI
QT widget's simple serial port assistant (qserialport)
Win11触摸键盘主题如何更换?Win11更换触摸键盘主题的方法
Task04: String
Project sorting of Online Exercise System Based on gin and Gorm