springboot项目整合Retry机制
1.引入pom.xml
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId >
<artifactId>aspectjweaver</artifactId >
</dependency>
(本人使用springboot项目2.4.5版本,自动引入该版本的相关jar包)
2.代码实现
1》在目标方法中添加 @Retryable注解
@Retryable(value = {NullPointerException.class}, maxAttempts = 5)
public void sendMsg(SgipSubmitRequestMessage sgipSubmitRequestMessage) throws Exception {
List<Promise<BaseMessage>> futures = ChannelUtil.syncWriteLongMsgToEntity("***",sgipSubmitRequestMessage);
if (futures == null) {
throw new NullPointerException(String.format("调用 ChannelUtil.syncWriteLongMsgToEntity()方法,参数:%s,返回结果futures为空", JSON.toJSONString(sgipSubmitRequestMessage)));
}
}
2》重试次数执行完成后添加回调方法
(注意:实现回调时,目标重试方法和回调方法都不要有返回值,否则无法实现)
@Recover
public void recover(NullPointerException e) {
log.info("重试5次后仍然报错:{}", e.getMessage());
}
3》在项目启动类中添加注解@EnableRetry
