spring-retry demo

注意點(diǎn):

  1. http調(diào)用類需要交spring管理
  2. http調(diào)用類與其調(diào)用類不能同類即demoserver與demo不能同類
  3. 實(shí)際是通過aop切面完成,因此http調(diào)用類中不能出現(xiàn)try-catch,沒有異常不會(huì)重試
  4. @Retryable與@Recover所貼的兩個(gè)方法需要同類,異常類型必須要一致
  5. maxAttempts 包括第一次請(qǐng)求的總次數(shù)
  6. @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>
  1. 啟動(dòng)類需要 @EnableRetry
  2. 編寫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 "失敗";
    }
}

  1. 重試超限調(diào)用 -- Exception類型必須與@Retryable的value類型一致
@Recover
    public String test(Exception e) {
        System.out.println("調(diào)用失敗打印日志");
        return "調(diào)用失敗";
    }
  1. demo類
@RestController
@RequestMapping
public class Demo {
@Autowired
private DemoService service;

    @RequestMapping("/demo")
    public  String send(){
        service.test();
        return null;
    }

}

文獻(xiàn): http://www.itdecent.cn/p/cc7abf831900
https://www.cnblogs.com/zimug/p/13507850.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容