注意点:
- http调用类需要交spring管理
- http调用类与其调用类不能同类即demoserver与demo不能同类
- 实际是通过aop切面完成,因此http调用类中不能出现try-catch,没有异常不会重试
- @Retryable与@Recover所贴的两个方法需要同类,异常类型必须要一致
- maxAttempts 包括第一次请求的总次数
- @Backoff :
delay 在上一次基础上*multiplier
maxDelay 最大重试间隔,默认30s,但注解中值为0
实际重试间隔取 delay,maxDelay之间的最小值
@Retryable(value = Exception.class, maxAttempts = 6, backoff = @Backoff(delay = 10000L,maxDelay = 60*60*1000L, multiplier = 2))
依赖
<!-- 需要依赖aspectjweaver-->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
- 启动类需要 @EnableRetry
- 编写http调用类,需要交给spring管理 @Service
package com.example.kafkademo.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class DemoService {
@Autowired
private RestTemplate restTemplate ;
@Retryable(value = Exception.class,maxAttempts = 5,backoff = @Backoff(delay = 1000L,multiplier=1))
public String test(){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity httpEntity = new HttpEntity("{'data':'消息'}",headers);
restTemplate.postForEntity("http://www.baidu.com",httpEntity,Object.class);
return "失败";
}
}
- 重试超限调用 -- Exception类型必须与@Retryable的value类型一致
@Recover
public String test(Exception e) {
System.out.println("调用失败打印日志");
return "调用失败";
}
- demo类
@RestController
@RequestMapping
public class Demo {
@Autowired
private DemoService service;
@RequestMapping("/demo")
public String send(){
service.test();
return null;
}
}
文献: https://www.jianshu.com/p/cc7abf831900
https://www.cnblogs.com/zimug/p/13507850.html