今天需要通过http接口推送数据,根据协议接口失败情况下,需要重试3次。
springboot 版本1.5,
1.maven依赖
-
<dependency>
-
<groupId>org.springframework.retry</groupId>
-
<artifactId>spring-retry</artifactI
-
</dependency>
-
<dependency>
-
<groupId>org.aspectj</groupId>
-
<artifactId>aspectjweaver</artifactId>
-
</dependency>
2.springboot启动类 启动重试 ,添加 @EnableRetry 注解
3.在需要重试的方法上添加注解 @Retryable
-
@Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000L, multiplier = 1))
-
public boolean httpPushRetry(String url, String body) throws Exception {
-
String result = HttpUtils.goddHttpPost(url, body);
-
logger.warn("**传输内容:{},返回结果:{}", body, result);
-
AntResponseDto dto = JSONObject.parseObject(result, AntResponseDto.class);
-
if (dto == null) {
-
throw new Exception("");
-
}
-
Boolean success = dto.getSuccess();
-
Integer status = dto.getStatus();
-
if (success && status == 0) {
-
return true;
-
}
-
throw new Exception("返回值为失败:" + dto);
-
}
4、重试次数超过规定次数,调用回调方法 @Recover
-
/**
-
* 达到最大重试次数,或抛出了一个没有指定进行重试的异常
-
* recover 机制
-
*
-
* @param e 异常
-
*/
-
@Recover
-
public boolean recover(Exception e, String param) {
-
logger.error("达到最大重试次数,或抛出了一个没有指定进行重试的异常:", e);
-
return false;
-
}
@Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000L, multiplier = 1))
value :需要重试的异常种类
maxAttempts :重试次数
delay :重试间隔时间 delay = 1000L 为1秒
multiplier = 1:间隔时间倍数