在分布式系統(tǒng)中,為了保證數(shù)據(jù)分布式事務(wù)的強一致性,大家在調(diào)用RPC接口或者發(fā)送MQ時,針對可能會出現(xiàn)網(wǎng)絡(luò)抖動請求超時情況采取一下重試操作。大家用的最多的重試方式就是MQ了,但是如果你的項目中沒有引入MQ,那就不方便了,本文主要介紹一下如何使用Spring Retry實現(xiàn)重試操作。
1. 添加maven依賴
2. 在啟動里添加重試配置
1
2
3
4
5
6
7
8
9
|
@SpringBootApplication @EnableRetry public class Application { public static void main(String[] args) { SpringApplication.run(Application. class , args); } } |
3. 編寫Service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@Service public class RemoteService { private static final Logger logger = LoggerFactory.getLogger(TestController. class ); @Retryable (value= {BusinessException. class },maxAttempts = 3 ,backoff = @Backoff (delay = 5000l,multiplier = 2 )) public void call() throws Exception { logger.info( "do something..." ); throw new BusinessException( "RPC調(diào)用異常" ); } @Recover public void recover(BusinessException e) { logger.info( " --------------------------- " ); logger.info(e.getMessage()); } } |
4. 編寫Controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@RestController @RequestMapping ( "/test" ) public class TestController { private static final Logger logger = LoggerFactory.getLogger(TestController. class ); @Autowired private RemoteService remoteService; @RequestMapping ( "/test" ) public String login() throws Exception { remoteService.call(); return String.valueOf( "11" ); } |
5. 訪問http://localhost:8080/test/test
6. 測試日志
2017-07-25 19:28:07 [INFO]-[http-nio-53602-exec-1]-[com.test.retry.service.RemoteService.call(RemoteService.java:19)] do something...
2017-07-25 19:28:12 [INFO]-[http-nio-53602-exec-1]-[com.test.retry.service.RemoteService.call(RemoteService.java:19)] do something...
2017-07-25 19:28:22 [INFO]-[http-nio-53602-exec-1]-[com.test.retry.service.RemoteService.call(RemoteService.java:19)] do something...
2017-07-25 19:28:22 [INFO]-[http-nio-53602-exec-1]-[com.test.retry.service.RemoteService.recover(RemoteService.java:24)] ---------------------------
2017-07-25 19:28:22 [INFO]-[http-nio-53602-exec-1]-[com.test.retry.service.RemoteService.recover(RemoteService.java:25)] RPC調(diào)用異常
7. 相關(guān)配置說明
@Retryable 標(biāo)注此注解的方法在發(fā)生異常時會進行重試
value:指定處理的異常類
include:指定處理的異常類和value一樣,默認為空,當(dāng)exclude也為空時,默認所有異常
exclude:指定異常不處理,默認空,當(dāng)include也為空時,默認所有異常
maxAttempts:最大重試次數(shù)。默認3次
backoff: 重試等待策略。默認使用@Backoff注解
@Backoff 重試等待策略
不設(shè)置參數(shù)時,默認使用FixedBackOffPolicy(指定等待時間),重試等待1000ms
設(shè)置delay,使用FixedBackOffPolicy(指定等待時間),重試等待填寫的時間
設(shè)置delay和maxDealy時,重試等待在這兩個值之間均態(tài)分布
設(shè)置delay、maxDealy、multiplier,使用 ExponentialBackOffPolicy(指數(shù)級重試間隔的實現(xiàn) ),multiplier即指定延遲倍數(shù),比如delay=5000l,multiplier=2,則第一次重試為5秒,第二次為10秒,第三次為20秒……
@Recover 用于@Retryable重試失敗后處理方法,此注解注釋的方法參數(shù)一定要是@Retryable拋出的異常,否則無法識別,可以在該方法中進行日志處理。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/a294039255/article/details/76095759