如何使用Spring RetryTemplate

在雲計算場景中,網絡是其中的一個重要部分。實際情況下的網絡環境沒有開發環境的網絡那麼穩定,所以在雲計算中,網絡是不可靠的已經成爲了一條默認的潛規則。在系統研發的過程中,滿足正常的業務需求的必要前提下,系統的魯棒性,容錯性也成爲了一個重要的技術需求。
在網絡不可靠的環境中,要保證業務流程,就需要在網絡異常時對流程異常環節進行重試處理。

Spring框架爲我們提供了重試機制,接下來我們來試驗下Spring的重試。



Maven Dependency

假設項目是Maven管理的,需要在家pom中增加spring-retry包的依賴。

<dependency>
   <groupId>org.springframework.retry</groupId>
   <artifactId>spring-retry</artifactId>
</dependency>




創建Spring Retry Template


創建一個Bean配置類來管理bean,使用@EnableRetry來啓用Spring重試,通過@Bean註解創建一個RetryTemplate加入Spring Container。配置最大重試次數爲4。

@Configuration
@EnableRetry
public class BeanSeederServices {

   @Bean
   public RetryTemplate retryTemplate() {
       SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
       retryPolicy.setMaxAttempts(4);
       FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
       backOffPolicy.setBackOffPeriod(3000);
       RetryTemplate template = new RetryTemplate();
       template.setRetryPolicy(retryPolicy);
       template.setBackOffPolicy(backOffPolicy);
       return template;
   }
}

















構建重試邏輯

創建一個Service,在裏面使用我們構建的RetryTemplate,將需要重試的業務邏輯交給RetryTemplate。


@Service
public class ConfigureNetworkService
{

 @Autowired
 private RetryTemplate retryTemplate;
 int counter =0;
 private void configureNetworkSystem(){
  retryTemplate.execute(
      context -> {
                  verifyNwConfiguration();
                   return true;
               });  
 }
 
 private void verifyNwConfiguration(){
   counter++;
   LOGGER.info("N/W configuration Service Failed "+ counter);
   throw new RuntimeException();
 }
}





















創建一個Controller,用來提供執行入口,通過url來觸發我們的重試功能。


@RestController
@RequestMapping(value="/networksrv")
public class NetworkClientService {
   @Autowired
   private ConfigureNetworkService configureNetworkService;
   @GetMapping
   public String callRetryService() throws SQLException {
       return configureNetworkService.configureNetworkSystem();
   }
}











在控制檯我們會看到Spring輸出的重試日誌

2020-06-16 09:59:51.399  INFO 17288 --- [nio-8080-exec-1] c.e.springretrydemo.NetworkClientService       : N/W configuration Service Failed  1
2020-06-16 09:59:52.401  INFO 17288 --- [nio-8080-exec-1] c.e.springretrydemo.NetworkClientService       : N/W configuration Service Failed  2
2020-06-16 09:59:53.401  INFO 17288 --- [nio-8080-exec-1] c.e.springretrydemo.NetworkClientService       : N/W configuration Service Failed  3
2020-06-16 09:59:53.402  INFO 17288 --- [nio-8080-exec-1] c.e.springretrydemo.NetworkClientService       : N/W configuration Service Failed  4
Exception in thread "NetworkClientService" java.lang.RuntimeException





總結

通過使用Spring RetryTemplate,我們只需要關心具體的業務邏輯,不在用開發重試處理邏輯了。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章