看頭圖說話

前言:當我們調用第三方接口或者在同一個注冊中心的其他服務的時候,由于一些原因沒有返回成功的標識,需要嘗試多次獲取響應。
加入依賴
<dependency><groupId>org.springframework.retrygroupId><artifactId>spring-retryartifactId>dependency>
手寫代碼實現(xiàn)
public?class?TestJob?{????private?static?Logger?logger?=?LoggerFactory.getLogger(TestJob.class);private int cnt = 0;public void retry(String params){RetryTemplate oRetryTemplate = new RetryTemplate();//????????SimpleRetryPolicy?oRetryPolicy?=?new?SimpleRetryPolicy(5);//簡單重試策略,重試5次????????AlwaysRetryPolicy?oRetryPolicy?=?new?AlwaysRetryPolicy();//重試策略,一直重試直到成功????????oRetryTemplate.setRetryPolicy(oRetryPolicy);//指定重試策略,也可以用其他的try {// obj為doWithRetry的返回結果,可以為任意類型Object obj = oRetryTemplate.execute(new RetryCallback@Overridepublic Object doWithRetry(RetryContext context) throws Exception {// 開始重試System.out.println(params + "----retry----" + context.getRetryCount());doTask(params);return "success";}}, new RecoveryCallback@Overridepublic Object recover(RetryContext context) throws Exception { // 重試多次后都失敗了System.out.println("重試多次失敗");return "error";}});} catch (Exception e) {e.printStackTrace();}????}public void doTask(String data) throws Exception {try{System.out.println("exec---" + data);if(cnt==10){System.out.println("exec success");return;}int code = 400;if(code!=200){cnt++;throw new Exception("error"); // 拋出異常,執(zhí)行重試}}catch (Exception e){System.out.println(e.getMessage());throw e;????????}}public static void main(String[] args) {TestJob t = new TestJob();System.out.println("start exec");String data = UUID.randomUUID().toString();try{t.doTask(data);}catch (Exception e){//重試datat.retry(data);}}}
基于注解實現(xiàn)
value//開啟重試注解,必須public class CallServiceImpl {MyService myService;RedisService redisService;private static Logger logger= LoggerFactory.getLogger(CallServiceImpl.class);????//重試注解,必須(value = {Exception.class}, maxAttempts = 2, backoff = (delay = 2000L))public Result invoke(MyParamForm param) throws Exception {Result,Object>> result = new Result<>();try{result=myService.invoke(param);}catch (Exception e){logger.error("invoke err:{}, param:{}",e.getMessage(),JSON.toJSONString(esgParamForm));throw e;}if (result.getCode() != ResultCodeEnum.SUCCESS.getCode()){logger.error("invoke fail:{}, param:{}",JSON.toJSONString(result),JSON.toJSONString(esgParamForm));throw new Exception("invoke callfail");}return result;????}}
拋出指定異常才會重試
maxAttempts最大重試次數(shù),默認3次
backoff重試等待策略,默認使用@Backoff,@Backoff的value默認為1000L;multiplier(指定延遲倍數(shù))
最后,關于重試還有@Recover注解,注解在方法上,重試失敗后會執(zhí)行該方法,@Retryable注解也還有其他一些值沒有說到,朋友需自行探究,歡迎留言相告。

評論
圖片
表情
