本文是精講RestTemplate第8篇,前篇的blog訪問地址以下:html
在上一節咱們爲你們介紹了,當RestTemplate發起遠程請求異常時的自定義處理方法,咱們能夠經過自定義的方式解析出HTTP Status Code狀態碼,而後根據狀態碼和業務需求決定程序下一步該如何處理。
本節爲你們介紹另一種通用的異常的處理機制:那就是自動重試。也就是說,在RestTemplate發送請求獲得非200狀態結果的時候,間隔必定的時間再次發送n次請求。n次請求都失敗以後,最後拋出HttpClientErrorException。
在開始本節代碼以前,將上一節的RestTemplate自定義異常處理的代碼註釋掉,不然自動重試機制不會生效。以下(參考上一節代碼):vue
//restTemplate.setErrorHandler(new MyRestErrorHandler());
經過maven座標引入spring-retry,spring-retry的實現依賴於面向切面編程,因此引入aspectjweaver。如下配置過程都是基於Spring Boot應用。java
<dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> <version>1.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> </dependency>
在Spring Boot 應用入口啓動類,也就是配置類的上面加上@SpringRetry註解,表示讓重試機制生效。spring
@Service public class RetryService { @Resource private RestTemplate restTemplate; private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @Retryable(value = RestClientException.class, maxAttempts = 3, backoff = @Backoff(delay = 5000L,multiplier = 2)) public HttpStatus testEntity() { System.out.println("發起遠程API請求:" + DATE_TIME_FORMATTER.format(LocalDateTime.now())); String url = "http://jsonplaceholder.typicode.com/postss/1"; ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); return responseEntity.getStatusCode(); // 獲取響應碼 } }
@Retryable
註解的方法在發生異常時會重試,參數說明:編程
@Backoff
註解爲重試等待的策略,參數說明:json
寫一個測試的RetryController 對RetryService 的testEntity方法進行調用後端
@RestController public class RetryController { @Resource private RetryService retryService; @GetMapping("/retry") public HttpStatus test() { return retryService.testEntity(); } }
向 http://localhost:8080/retry 發起請求,結果以下:springboot
從結果能夠看出:app
以爲對您有幫助的話,幫我點贊、分享!您的支持是我不竭的創做動力! 。另外,筆者最近一段時間輸出了以下的精品內容,期待您的關注。前後端分離