?? 本節(jié)目標(biāo):了解傳統(tǒng)重試的寫法以及 Spring-Retry 快速入門。
下面使用一個(gè)例子來講述:調(diào)用第三方接口獲取數(shù)據(jù),支持重試 3 次,每次重試間隔 5 秒。
傳統(tǒng)寫法
傳統(tǒng)寫法:while 循環(huán),判斷是否有異常,有異常則重試,并使用 Thread 延遲,直到重試次數(shù)用完或重試成功為止。
調(diào)用第三方接口的代碼:?? 普通的 RestTemplate 調(diào)用文章來源:http://www.zghlxwxcb.cn/news/detail-846320.html
var responseEntity = restTemplate.exchange(new RequestEntity<>(HttpMethod.GET, URI.create(drugUrl)),
new ParameterizedTypeReference<R<List<Drug>>>() {
});
Assert.isTrue(responseEntity.getStatusCode().is2xxSuccessful(), "請(qǐng)求狀態(tài)碼不是200!");
Assert.notNull(responseEntity.getBody(), "response body 不可為空!");
return responseEntity.getBody().getData();
加入重試邏輯:?? RestTemplate 代碼被重試代碼包裹,代碼可讀性不高,可復(fù)用性差文章來源地址http://www.zghlxwxcb.cn/news/detail-846320.html
- 設(shè)定最大重試次數(shù)為 4。
- while 循環(huán)實(shí)現(xiàn)重試,出現(xiàn)異常則線程睡眠 3 秒,然后進(jìn)行下一次重試。
- 如果超過最大重試次數(shù),則停止重試,返回空集合;如果重試成功,則直接返回。
public List<Drug> getDrugWithWhileRetry(String drugUrl) {
// 最大重試次數(shù)
int maxAttempt = 4;
int current = 1;
while (current <= maxAttempt) {
log.info("正在進(jìn)行第{}次調(diào)用", current);
try {
var responseEntity = restTemplate.exchange(new RequestEntity<>(HttpMethod.GET, URI.create(drugUrl
到了這里,關(guān)于Java 重試框架 Spring-Retry | 快速入門的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!