SpringCloud 2020.0.4 系列之服務降級


1. 概述

老話說的好:做人要正直,做事要正派,胸懷坦盪、光明磊落,才會贏得他人的信賴與尊敬。

 

言歸正傳,之前聊了服務間通信的組件 Feign,今天我們來聊聊服務降級。

服務降級簡單的理解就是給一個備選方案,當服務調用報錯或者超時時,能終止遠程調用,並很快的返回備選的結果,避免引發服務雪崩。

 

今天我們用兩個例子,模擬一下 接口報錯 和 接口超時 的服務降級實現。

我們使用 hystrix 實現服務降級,雖然從 Spring Cloud 2020.0 版本開始,移除了 hystrix 組件,但並不影響我們對他的使用。

閑話不多說,直接上代碼。

 

2. 接口報錯的服務降級

2.1 被調用服務

2.1.1 接口代碼

    @GetMapping("/exception")
    String exception() throws Exception;

 

2.1.2 實現類代碼

    @Override
    public String exception() throws Exception {
        if(1==1) {
            throw new Exception("模擬異常");
        }
        return null;
    }

 

2.2 調用服務

2.2.1 主要依賴

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 健康檢查 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            <version>2.2.9.RELEASE</version>
        </dependency>

這里 hystrix 使用目前的最新版本 2.2.9.RELEASE。

 

2.2.2 主要配置

feign:
  circuitbreaker:
    enabled: true   # 開啟 feign 的斷路器

hystrix:
  command:
    default:
      fallback:
        enabled: true     # 開啟服務降級

 

2.2.3 降級工廠類的開發

@Component
public class MyEurekaClientServiceFactory implements FallbackFactory<EurekaClientService> {
    @Override
    public EurekaClientService create(Throwable cause) {

        return new EurekaClientService() {
            
            @Override
            public String exception() throws Exception {
                System.out.println("exception方法 降級");
                return "exception方法 降級";
            }
        };
    }
}

 

2.2.4 在 Feign 接口配置降級工廠類

@FeignClient(name = "my-eureka-client", fallbackFactory = MyEurekaClientServiceFactory.class)  // name為 調用服務的名稱
@RequestMapping("/api")
public interface EurekaClientService {

    @GetMapping("/exception")
    String exception() throws Exception;

}

 

2.2.5 啟動類增加 @EnableHystrix 注解

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableHystrix
public class MyFeignApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyFeignApplication.class, args);
    }
}

 

2.2.6 啟動服務測試

可以正常進入降級方法。

 

3. 接口超時的服務降級

3.1 被調用服務

3.1.1 接口代碼

    @GetMapping("/timeout")
    String timeout(@RequestParam Integer timeoutSecond);

 

3.1.2 實現類代碼

    @Override
    public String timeout(Integer timeoutSecond) {
        System.out.println("調用timeout方法");
        try {
            Thread.sleep(timeoutSecond * 1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "success:" + port;
    }

 

3.2 調用服務

3.2.1 主要配置

feign:
  client:
    config:
      # 全局配置
      default:
        connectTimeout: 1000   # 連接超時時間,單位ms
        readTimeout: 3000         # 獲取Response響應超時時間,單位ms

      # 針對 my-eureka-client 的 feign 配置,優先級高於全局配置
      my-eureka-client:
        connectTimeout: 300   # 連接超時時間,單位ms
        readTimeout: 5000         # 獲取Response響應超時時間,單位ms
  circuitbreaker:
    enabled: true   # 開啟 feign 的斷路器


hystrix:
  command:
    default:
      fallback:
        enabled: true     # 開啟服務降級
      execution:
        timeout:
          enabled: true   # 全局超時配置
        isolation:
          thread:
            timeoutInMilliseconds: 3000    # 超時時間配置
            interruptOnTimeout: true       # 超時后是否終止線程
            interruptOnFutureCancel: true  # 取消后是否終止線程

注意:feign 的 readTimeout 屬性和 hystrix 的 timeoutInMilliseconds 屬性會同時生效,以超時時間最短的為准。

 

3.2.2 降級工廠類的開發

@Component
public class MyEurekaClientServiceFactory implements FallbackFactory<EurekaClientService> {
    @Override
    public EurekaClientService create(Throwable cause) {

        return new EurekaClientService() {
            
            @Override
            public String exception() throws Exception {
                System.out.println("exception方法 降級");
                return "exception方法 降級";
            }

            @Override
            public String timeout(Integer timeoutSecond) {
                return "timeout方法 降級";
            }
        };
    }
}

 

3.2.3 啟動服務測試

可以正常進入降級方法。

 

4. 綜述

今天聊了一下 服務降級 的相關知識,希望可以對大家的工作有所幫助。

歡迎幫忙點贊、評論、轉發、加關注 :)

關注追風人聊Java,每天更新Java干貨。

 

5. 個人公眾號

追風人聊Java,歡迎大家關注

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM