mirror of
https://gitee.com/wangkang/udf.git
synced 2026-10-23 09:16:46 +00:00
92 lines
2.3 KiB
Markdown
92 lines
2.3 KiB
Markdown
# spring boot / cloud (七) 使用@Retryable来进行重处理
|
|
|
|
##前言
|
|
|
|
|
|
###什么时候需要重处理?
|
|
|
|
|
|
>在实际工作中,重处理是一个非常常见的场景,比如:发送消息失败,调用远程服务失败,争抢锁失败,等等,这些错误可能是因为网络波动造成的,等待过后重处理就能成功.通常来说,会用try/catch,while循环之类的语法来进行重处理,但是这样的做法缺乏统一性,并且不是很方便,要多写很多代码.然而`spring-retry`却可以通过注解,在不入侵原有业务逻辑代码的方式下,优雅的实现重处理功能.
|
|
|
|
|
|
##思路
|
|
|
|
|
|
使用@Retryable和@Recover实现重处理,以及重处理失后的回调
|
|
|
|
|
|
##实现
|
|
|
|
|
|
###1.pom引用
|
|
|
|
|
|
``` xml
|
|
<dependency>
|
|
<groupId>org.springframework.retry</groupId>
|
|
<artifactId>spring-retry</artifactId>
|
|
</dependency>
|
|
```
|
|
|
|
###2.应用启动类开启retry
|
|
|
|
|
|
``` java
|
|
....其他注解
|
|
@EnableRetry
|
|
public class BaseApplication {
|
|
.......
|
|
}
|
|
```
|
|
|
|
###3.在指定方法上标记@Retryable来开启重试
|
|
|
|
|
|
``` java
|
|
@Retryable(value={A异常.class,B异常.class},
|
|
maxAttempts=重试次数,
|
|
backoff = @Backoff(value = 每次重试延迟毫秒数))
|
|
public Integer retry() {
|
|
final int a = 5;
|
|
int num = new SecureRandom().nextInt();
|
|
if (num % a == 0) {
|
|
return num;
|
|
}
|
|
throw new RetryException("重试失败");
|
|
}
|
|
```
|
|
|
|
|
|
###4.在指定方法上标记@Recover来开启重试失败后调用的方法(注意,需跟重处理方法在同一个类中)
|
|
|
|
|
|
``` java
|
|
@Recover
|
|
public void recover(A异常 e) {
|
|
// ... do something
|
|
}
|
|
|
|
@Recover
|
|
public void recover(B异常 e) {
|
|
// ... do something
|
|
}
|
|
|
|
```
|
|
|
|
## **代码仓库** (博客配套代码)
|
|
|
|
- [udf-starter : 基础项目,脚手架,框架](https://gitee.com/wangkang/udf)
|
|
|
|
- [udf-sample : 集成样例](https://gitee.com/wangkang/udf-sample)
|
|
|
|
##结束
|
|
|
|
演示了单spring boot的应用的,在后续的cloud场景中,如:zuul,等组件,都会涉及到重处理,会在后续的章节中讲解
|
|
|
|
---------
|
|
|
|
想获得最快更新,请关注公众号
|
|
|
|

|
|
|