注意點(diǎn):
- http調(diào)用類需要交spring管理
- http調(diào)用類與其調(diào)用類不能同類即demoserver與demo不能同類
- 實(shí)際是通過aop切面完成阻肿,因此http調(diào)用類中不能出現(xiàn)try-catch,沒有異常不會重試
- @Retryable與@Recover所貼的兩個方法需要同類沮尿,異常類型必須要一致
- maxAttempts 包括第一次請求的總次數(shù)
- @Backoff :
delay 在上一次基礎(chǔ)上*multiplier
maxDelay 最大重試間隔,默認(rèn)30s,但注解中值為0
實(shí)際重試間隔取 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調(diào)用類丛塌,需要交給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 "失敗";
}
}
- 重試超限調(diào)用 -- Exception類型必須與@Retryable的value類型一致
@Recover
public String test(Exception e) {
System.out.println("調(diào)用失敗打印日志");
return "調(diào)用失敗";
}
- demo類
@RestController
@RequestMapping
public class Demo {
@Autowired
private DemoService service;
@RequestMapping("/demo")
public String send(){
service.test();
return null;
}
}
文獻(xiàn): http://www.reibang.com/p/cc7abf831900
https://www.cnblogs.com/zimug/p/13507850.html