Spring的异常重试框架Spring Retry简单配置操作
相关api见:点击进入
/* *Copyright2014theoriginalauthororauthors. * *LicensedundertheApacheLicense,Version2.0(the"License"); *youmaynotusethisfileexceptincompliancewiththeLicense. *YoumayobtainacopyoftheLicenseat * *http://www.apache.org/licenses/LICENSE-2.0 * *Unlessrequiredbyapplicablelaworagreedtoinwriting,software *distributedundertheLicenseisdistributedonan"ASIS"BASIS, *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied. *SeetheLicenseforthespecificlanguagegoverningpermissionsand *limitationsundertheLicense. */ packageorg.springframework.retry.annotation; importjava.lang.annotation.Documented; importjava.lang.annotation.ElementType; importjava.lang.annotation.Retention; importjava.lang.annotation.RetentionPolicy; importjava.lang.annotation.Target; /** *Annotationforamethodinvocationthatisretryable. * *@authorDaveSyer *@authorArtemBilan *@authorGaryRussell *@since1.1 * */ @Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public@interfaceRetryable{ /** *Retryinterceptorbeannametobeappliedforretryablemethod.Ismutually *exclusivewithotherattributes. *@returntheretryinterceptorbeanname */ Stringinterceptor()default""; /** *Exceptiontypesthatareretryable.Synonymforincludes().Defaultstoempty(and *ifexcludesisalsoemptyallexceptionsareretried). *@returnexceptiontypestoretry */ Class[]value()default{}; /** *Exceptiontypesthatareretryable.Defaultstoempty(andifexcludesisalso *emptyallexceptionsareretried). *@returnexceptiontypestoretry */ Class[]include()default{}; /** *Exceptiontypesthatarenotretryable.Defaultstoempty(andifincludesisalso *emptyallexceptionsareretried). *@returnexceptiontypestoretry */ Class[]exclude()default{}; /** *Auniquelabelforstatisticsreporting.Ifnotprovidedthecallermaychooseto *ignoreit,orprovideadefault. * *@returnthelabelforthestatistics */ Stringlabel()default""; /** *Flagtosaythattheretryisstateful:i.e.exceptionsarere-thrown,butthe *retrypolicyisappliedwiththesamepolicytosubsequentinvocationswiththe *samearguments.Iffalsethenretryableexceptionsarenotre-thrown. *@returntrueifretryisstateful,defaultfalse */ booleanstateful()defaultfalse; /** *@returnthemaximumnumberofattempts(includingthefirstfailure),defaultsto3 */ intmaxAttempts()default3; /** *@returnanexpressionevaluatedtothemaximumnumberofattempts(includingthefirstfailure),defaultsto3 *Overrides{@link#maxAttempts()}. *@since1.2 */ StringmaxAttemptsExpression()default""; /** *Specifythebackoffpropertiesforretryingthisoperation.Thedefaultisa *simple{@linkBackoff}specificationwithnoproperties-seeit'sdocumentation *fordefaults. *@returnabackoffspecification */ Backoffbackoff()default@Backoff(); /** *Specifyanexpressiontobeevaluatedafterthe{@codeSimpleRetryPolicy.canRetry()} *returnstrue-canbeusedtoconditionallysuppresstheretry.Onlyinvokedafter *anexceptionisthrown.Therootobjectfortheevaluationisthelast{@codeThrowable}. *Otherbeansinthecontextcanbereferenced. *Forexample: **and **{@code"message.contains('youcanretrythis')"}. *
下面就Retryable的简单配置做一个讲解:
首先引入maven依赖:
org.springframework.retry spring-retry RELEASE
然后在方法上配置注解@Retryable
@Override @SuppressWarnings("Duplicates") @Retryable(value={RemoteAccessException.class},maxAttempts=3,backoff=@Backoff(delay=3000l,multiplier=0)) publicbooleancustomSendText(Stringopenid,Stringcontent)throwsRemoteAccessException{ StringreplyString="{\n"+ "\"touser\":"+openid+",\n"+ "\"msgtype\":\"text\",\n"+ "\"text\":\n"+ "{\n"+ "\"content\":"+content+"\n"+ "}\n"+ "}"; try{ logger.info("wx:customSend=request:{}",replyString.toString()); HttpsClienthttpClient=HttpsClient.getAsyncHttpClient(); Stringurl=Constant.WX_CUSTOM_SEND; Stringtoken=wxAccessokenService.getAccessToken(); url=url.replace("ACCESS_TOKEN",token); logger.info("wx:customSend=url:{}",url); Stringstring=httpClient.doPost(url,replyString); logger.info("wx:customSend=response:{}",string); if(StringUtils.isEmpty(string))thrownewRemoteAccessException("发送消息异常"); JSONObjectjsonTexts=(JSONObject)JSON.parse(string); if(jsonTexts.get("errcode")!=null){ Stringerrcode=jsonTexts.get("errcode").toString(); if(errcode==null){ thrownewRemoteAccessException("发送消息异常"); } if(Integer.parseInt(errcode)==0){ returntrue; }else{ thrownewRemoteAccessException("发送消息异常"); } }else{ thrownewRemoteAccessException("发送消息异常"); } }catch(Exceptione){ logger.error("wz:customSend:{}",ExceptionUtils.getStackTrace(e)); thrownewRemoteAccessException("发送消息异常"); } }
注解内容介绍:
@Retryable注解
被注解的方法发生异常时会重试
value:指定发生的异常进行重试
include:和value一样,默认空,当exclude也为空时,所有异常都重试
exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试
maxAttemps:重试次数,默认3
backoff:重试补偿机制,默认没有
@Backoff注解
delay:指定延迟后重试
multiplier:指定延迟的倍数,比如delay=5000l,multiplier=2时,第一次重试为5秒后,第二次为10秒,第三次为20秒
注意:
1、使用了@Retryable的方法不能在本类被调用,不然重试机制不会生效。也就是要标记为@Service,然后在其它类使用@Autowired注入或者@Bean去实例才能生效。
2、使用了@Retryable的方法里面不能使用try...catch包裹,要在发放上抛出异常,不然不会触发。
3、在重试期间这个方法是同步的,如果使用类似SpringCloud这种框架的熔断机制时,可以结合重试机制来重试后返回结果。
4、SpringRetry不仅能注入方式去实现,还可以通过API的方式实现,类似熔断处理的机制就基于API方式实现会比较宽松。
以上这篇Spring的异常重试框架SpringRetry简单配置操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。