spring retry是從spring batch獨(dú)立出來(lái)的一個(gè)能功能,主要實(shí)現(xiàn)了重試和熔斷。對(duì)于重試是有場(chǎng)景限制的,不是什么場(chǎng)景都適合重試,比如參數(shù)校驗(yàn)不合法、寫操作等(要考慮寫是否冪等)都不適合重試。遠(yuǎn)程調(diào)用超時(shí)、網(wǎng)絡(luò)突然中斷可以重試。在微服務(wù)治理框架中,通常都有自己的重試與超時(shí)配置,比如dubbo可以設(shè)置retries=1,timeout=500調(diào)用失敗只重試1次,超過(guò)500ms調(diào)用仍未返回則調(diào)用失敗。在spring retry中可以指定需要重試的異常類型,并設(shè)置每次重試的間隔以及如果重試失敗是繼續(xù)重試還是熔斷(停止重試)。
設(shè)計(jì)與實(shí)現(xiàn)
retryoperations
定義重試的api,retrytemplate
是api的模板模式實(shí)現(xiàn),實(shí)現(xiàn)了重試和熔斷。提供的api如下:
1
2
3
4
|
public interface retryoperations { <t, e extends throwable>t execute(retrycallback<t, e>retrycallback) throws e; } // 其他api已省略 |
retrycallback
定義了需要執(zhí)行重試的操作,定義好操作后,就是如何重試的問題了。retrytemplate
通過(guò)制定不同的重試策略來(lái)執(zhí)行如何重試的邏輯。默認(rèn)的重試策略是simpleretryplicy
,也就是會(huì)重試3次。重試第1次如果成功后面就不會(huì)繼續(xù)重試了。那么如果3尺都重試失敗了呢?流程結(jié)束或者返回兜底結(jié)果。要返回兜底結(jié)果需要配置recoveycallback
,從名字可以看出這是一個(gè)兜底回調(diào)接口,也就是重試失敗后執(zhí)行的邏輯。除了simpleretrypolicy
還有其他重試策略,先來(lái)看下retrypolicy
接口:
1
2
3
4
5
6
|
public interface retrypolicy extends serializable { boolean canretry(retrycontext context); retrycontext open(retrycontext parent); void close(retrycontext context); void registerthrowable(retrycontext context, throwable throwable); } |
canretry
在每次重試的時(shí)候調(diào)用,是否可以繼續(xù)重試的判斷條件
open
重試開始前調(diào)用,會(huì)創(chuàng)建一個(gè)重試上下文到retrycontext
,保存重試的堆棧等信息
registerthrowable
每次重試異常時(shí)調(diào)用(有異常會(huì)繼續(xù)重試)
以simpleretrypolicy
為例,當(dāng)重試次數(shù)達(dá)到3(默認(rèn)3次)停止重試,重試次數(shù)保存在重試上下文中。
提供如下重試策略實(shí)現(xiàn):
- neverretrypolicy:只允許調(diào)用retrycallback一次,不允許重試
- alwaysretrypolicy:允許無(wú)限重試,直到成功,此方式邏輯不當(dāng)會(huì)導(dǎo)致死循環(huán)
- simpleretrypolicy:固定次數(shù)重試策略,默認(rèn)重試最大次數(shù)為3次,retrytemplate默認(rèn)使用的策略
- timeoutretrypolicy:超時(shí)時(shí)間重試策略,默認(rèn)超時(shí)時(shí)間為1秒,在指定的超時(shí)時(shí)間內(nèi)允許重試
- exceptionclassifierretrypolicy:設(shè)置不同異常的重試策略,類似組合重試策略,區(qū)別在于這里只區(qū)分不同異常的重試
- circuitbreakerretrypolicy:有熔斷功能的重試策略,需設(shè)置3個(gè)參數(shù)opentimeout、resettimeout和delegate
- compositeretrypolicy:組合重試策略,有兩種組合方式,樂觀組合重試策略是指只要有一個(gè)策略允許重試即可以,悲觀組合重試策略是指只要有一個(gè)策略不允許重試即可以,但不管哪種組合方式,組合中的每一個(gè)策略都會(huì)執(zhí)行
重試回退策略,指的是每次重試是立即重試還是等待一段時(shí)間后重試。默認(rèn)情況下是立即重試,如果需要配置等待一段時(shí)間后重試則需要指定回退策略backoffretrypolicy
。backoffretrypolicy有如下實(shí)現(xiàn):
- nobackoffpolicy:無(wú)退避算法策略,每次重試時(shí)立即重試
- fixedbackoffpolicy:固定時(shí)間的退避策略,需設(shè)置參數(shù)sleeper和backoffperiod,sleeper指定等待策略,默認(rèn)是thread.sleep,即線程休眠,backoffperiod指定休眠時(shí)間,默認(rèn)1秒
- uniformrandombackoffpolicy:隨機(jī)時(shí)間退避策略,需設(shè)置sleeper、minbackoffperiod和maxbackoffperiod,該策略在[minbackoffperiod,maxbackoffperiod之間取一個(gè)隨機(jī)休眠時(shí)間,minbackoffperiod默認(rèn)500毫秒,maxbackoffperiod默認(rèn)1500毫秒
- exponentialbackoffpolicy:指數(shù)退避策略,需設(shè)置參數(shù)sleeper、initialinterval、maxinterval和multiplier,initialinterval指定初始休眠時(shí)間,默認(rèn)100毫秒,maxinterval指定最大休眠時(shí)間,默認(rèn)30秒,multiplier指定乘數(shù),即下一次休眠時(shí)間為當(dāng)前休眠時(shí)間*multiplier
- exponentialrandombackoffpolicy:隨機(jī)指數(shù)退避策略,引入隨機(jī)乘數(shù)可以實(shí)現(xiàn)隨機(jī)乘數(shù)回退
有狀態(tài)重試 or 無(wú)狀態(tài)重試
所謂無(wú)狀態(tài)重試是指重試在一個(gè)線程上下文中完成的重試,反之不在一個(gè)線程上下文完成重試的就是有狀態(tài)重試。之前的simpleretrypolicy
就屬于無(wú)狀態(tài)重試,因?yàn)橹卦囀窃谝粋€(gè)循環(huán)中完成的。那么什么會(huì)后會(huì)出現(xiàn)或者說(shuō)需要有狀態(tài)重試呢?通常有兩種情況:事務(wù)回滾和熔斷。
數(shù)據(jù)庫(kù)操作異常dataaccessexception,不能執(zhí)行重試,而如果拋出其他異常可以重試。
熔斷的意思不在當(dāng)前循環(huán)中處理重試,而是全局重試模式(不是線程上下文)。熔斷會(huì)跳出循環(huán),那么必然會(huì)丟失線程上下文的堆棧信息。那么肯定需要一種“全局模式”保存這種信息,目前的實(shí)現(xiàn)放在一個(gè)cache(map實(shí)現(xiàn)的)中,下次從緩存中獲取就能繼續(xù)重試了。
quick start
在需要執(zhí)行重試的類上使用@enableretry
,如果設(shè)置了proxytargetclass=true
這使用cglib動(dòng)態(tài)代理:
1
2
3
4
5
6
|
@configuration @enableretry (proxytargetclass = true ) @component public class retryexamples { } |
基于最大重試次數(shù)策略的重試,如果重試了3次仍然拋出異常則停止重試,執(zhí)行兜底回調(diào),所以最后的輸出結(jié)果是integer.max_value
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
private void retryexample3() throws exception { retrytemplate retrytemplate = new retrytemplate(); simpleretrypolicy simpleretrypolicy = new simpleretrypolicy(); simpleretrypolicy.setmaxattempts( 3 ); retrytemplate.setretrypolicy(simpleretrypolicy); integer result = retrytemplate.execute( new retrycallback<integer, exception>() { int i = 0 ; // 重試操作 @override public integer dowithretry(retrycontext retrycontext) throws exception { log.info( "retry count: {}" , retrycontext.getretrycount()); return len(i++); } }, new recoverycallback<integer>() { //兜底回調(diào) @override public integer recover(retrycontext retrycontext) throws exception { log.info( "after retry: {}, recovery method called!" , retrycontext.getretrycount()); return integer.max_value; } }); log.info( "final result: {}" , result); } private int len( int i) throws exception { if (i < 10 ) throw new exception(i + " le 10" ); return i; } |
下面介紹如何使用熔斷重試策略模式(circuitbreakerretrypolicy),需要設(shè)置如下三個(gè)參數(shù):
- delegate:傳入retrypolicy(每個(gè)retrypolicy實(shí)現(xiàn)都有自己的重試策略實(shí)現(xiàn)),是真正判斷是否重試的策略,當(dāng)重試失敗時(shí),則執(zhí)行熔斷策略
- opentimeout:openwindow,配置熔斷器電路打開的超時(shí)時(shí)間,當(dāng)超過(guò)opentimeout之后熔斷器電路變成半打開狀態(tài)(只要有一次重試成功,則閉合電路)
- resettimeout:timeout,配置重置熔斷器重新閉合的超時(shí)時(shí)間
斷路器開閉實(shí)現(xiàn)判斷:
- 當(dāng)重試失敗,且在熔斷器打開時(shí)間窗口[0,openwindow) 內(nèi),立即熔斷
- 當(dāng)重試失敗,且超過(guò)timeout,熔斷器電路重新閉合
- 在熔斷器半打開狀態(tài)[openwindow, timeout] 時(shí),只要重試成功則重置上下文,斷路器閉合
測(cè)試代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
retrytemplate template = new retrytemplate(); circuitbreakerretrypolicy retrypolicy = new circuitbreakerretrypolicy( new simpleretrypolicy( 3 )); retrypolicy.setopentimeout( 5000 ); retrypolicy.setresettimeout( 20000 ); template.setretrypolicy(retrypolicy); for ( int i = 0 ; i < 10 ; i++) { //thread.sleep(100); try { object key = "circuit" ; boolean isforcerefresh = false ; retrystate state = new defaultretrystate(key, isforcerefresh); string result = template.execute( new retrycallback<string, runtimeexception>() { @override public string dowithretry(retrycontext context) throws runtimeexception { log.info( "retry count: {}" , context.getretrycount()); throw new runtimeexception( "timeout" ); } }, new recoverycallback<string>() { @override public string recover(retrycontext context) throws exception { return "default" ; } }, state); log.info( "result: {}" , result); } catch (exception e) { system.out.println(e); } } |
這里由于設(shè)置了isforcerefresh = false
,則key = "circuit"
的值(也就是retrycontext)會(huì)從緩存中獲取,所以當(dāng)重試失敗且滿足this.time < this.openwindow
發(fā)生熔斷的時(shí)候,后面仍然可以繼續(xù)已全局模式實(shí)現(xiàn)重試(拿到的retrycontext
是同一個(gè))。
注解開發(fā)
如果每次有重試需求的時(shí)候都寫一個(gè)retrytemplate
太臃腫了,使用注解可以大大簡(jiǎn)化開發(fā),減少重復(fù)代碼。下面是一個(gè)使用注解實(shí)現(xiàn)的最大重試策略的重試:
1
2
3
4
5
6
7
8
9
10
|
@retryable (value = sqldataexception. class , backoff = @backoff (value = 0l)) public string service3() throws sqldataexception { log.info( "service3 open" ); throw new sqldataexception(); } @recover public string recover(sqldataexception ne) { return "sqldataexception recover" ; } |
注解包括:
@enableretry
@retryable
@recover
@backoff
@circuitbreaker
@enableretry:能否重試,proxytargetclass屬性為true時(shí)(默認(rèn)false),使用cglib代理
@retryable:注解需要被重試的方法
- include 指定處理的異常類。默認(rèn)為空
- exclude指定不需要處理的異常。默認(rèn)為空
- vaue指定要重試的異常。默認(rèn)為空
- maxattempts 最大重試次數(shù)。默認(rèn)3次
- backoff 重試等待策略。默認(rèn)使用@backoff注解
@backoff:重試回退策略(立即重試還是等待一會(huì)再重試)
- 不設(shè)置參數(shù)時(shí),默認(rèn)使用fixedbackoffpolicy,重試等待1000ms
- 只設(shè)置delay()屬性時(shí),使用fixedbackoffpolicy,重試等待指定的毫秒數(shù)
- 當(dāng)設(shè)置delay()和maxdealy()屬性時(shí),重試等待在這兩個(gè)值之間均態(tài)分布
- 使用delay(),maxdealy()和multiplier()屬性時(shí),使用exponentialbackoffpolicy
- 當(dāng)設(shè)置multiplier()屬性不等于0時(shí),同時(shí)也設(shè)置了random()屬性時(shí),使用exponentialrandombackoffpolicy
@recover: 用于方法。用于@retryable失敗時(shí)的“兜底”處理方法。 @recover注釋的方法必須要與@retryable注解的方法“簽名”保持一致,第一入?yún)橐卦嚨漠惓#渌麉?shù)與@retryable保持一致,返回值也要一樣,否則無(wú)法執(zhí)行!
@circuitbreaker:用于方法,實(shí)現(xiàn)熔斷模式。
- include 指定處理的異常類。默認(rèn)為空
- exclude指定不需要處理的異常。默認(rèn)為空
- vaue指定要重試的異常。默認(rèn)為空
- maxattempts 最大重試次數(shù)。默認(rèn)3次
- opentimeout 配置熔斷器打開的超時(shí)時(shí)間,默認(rèn)5s,當(dāng)超過(guò)opentimeout之后熔斷器電路變成半打開狀態(tài)(只要有一次重試成功,則閉合電路)
- resettimeout 配置熔斷器重新閉合的超時(shí)時(shí)間,默認(rèn)20s,超過(guò)這個(gè)時(shí)間斷路器關(guān)閉
更多的例子歡迎到我的github(https://github.com/happyxiaofan/springboot-learning-example) star。謝謝
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/u011116672/article/details/77823867