天天看點

SpringCloud重試retry 20220927

SpringCloud重試retry是一個很贊的功能,能夠有效的處理單點故障的問題。主要功能是當請求一個服務的某個執行個體時,譬如你的User服務啟動了2個,它們都在eureka裡注冊了,那麼正常情況下當請求User服務時,ribbon預設會輪詢這兩個執行個體。此時如果其中一個執行個體故障了,發生了當機或者逾時等,如果沒有配置啟用重試retry政策,那麼調用方就會得到錯誤資訊或者逾時無響應或者是熔斷傳回的資訊。我們希望的自然是一個故障了,會自動切換到另一個去通路。

最簡單的方法就是retry。

需要先在pom.xml裡加入

  1. <dependency>
  2. <groupId>org.springframework.retry</groupId>
  3. <artifactId>spring-retry</artifactId>
  4. </dependency>

ribbon、zuul、feign都可以配置各自的retry方式。

1 ribbon配置如下

SpringCloud重試retry 20220927
  1. @Bean
  2. @LoadBalanced
  3. RestTemplate restTemplate() {
  4. HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
  5. httpRequestFactory.setReadTimeout(5000);
  6. httpRequestFactory.setConnectTimeout(5000);
  7. return new RestTemplate(httpRequestFactory);
  8. }

2 zuul配置如下

SpringCloud重試retry 20220927

zuul的重試比較簡單,不需要任何代碼,直接在yml裡配置即可。

注意,配置時,ribbon開頭的在yml裡是不給提示的,不要以為不提示就是沒效果,其實是可以用的。

SpringCloud重試retry 20220927

這個ReadTimeout和ConnectTimeout差別是很大的,ConnectTimeout是指建立連接配接的時間,如果目标服務當機或網絡故障,那麼響應的就是ConnectTimeout,無法連接配接。而ReadTimeout則是連接配接建立後,等待目标服務傳回響應的時間,譬如目标服務做了一個複雜操作導緻耗時較長,那麼會觸發ReadTimeout。

譬如zuul路由了/user路徑到user服務上,如果User1執行個體當機了,那麼配置了retry的zuul就會在重試MaxAutoRetries次數後,切換到另一個執行個體User2上。如果User2也故障了,那麼傳回404.

retryableStatusCodes裡面有幾個錯誤碼,意思就是遇到哪些錯誤碼時觸發重試。預設是404,我多配了幾個,僅供參考。

3 feign配置如下

feign預設是通過自己包下的Retryer進行重試配置,預設是5次

  1. import static java.util.concurrent.TimeUnit.SECONDS;
  2. /**
  3. * Cloned for each invocation to {@link Client#execute(Request, feign.Request.Options)}.
  4. * Implementations may keep state to determine if retry operations should continue or not.
  5. */
  6. public interface Retryer extends Cloneable {
  7. /**
  8. * if retry is permitted, return (possibly after sleeping). Otherwise propagate the exception.
  9. */
  10. void continueOrPropagate(RetryableException e);
  11. Retryer clone();
  12. public static class Default implements Retryer {
  13. private final int maxAttempts;
  14. private final long period;
  15. private final long maxPeriod;
  16. int attempt;
  17. long sleptForMillis;
  18. public Default() {
  19. this(100, SECONDS.toMillis(1), 5);
  20. }
  21. public Default(long period, long maxPeriod, int maxAttempts) {
  22. this.period = period;
  23. this.maxPeriod = maxPeriod;
  24. this.maxAttempts = maxAttempts;
  25. this.attempt = 1;
  26. }
  1. @Bean
  2. Retryer feignRetryer() {
  3. return Retryer.NEVER_RETRY;
  4. }
  1. @Bean
  2. Request.Options requestOptions(ConfigurableEnvironment env){
  3. int ribbonReadTimeout = env.getProperty("ribbon.ReadTimeout", int.class, 6000);
  4. int ribbonConnectionTimeout = env.getProperty("ribbon.ConnectTimeout", int.class, 3000);
  5. return new Request.Options(ribbonConnectionTimeout, ribbonReadTimeout);
  6. }