天天看點

SpringCloud中Hystrix的使用方式及注意事項

SpringCloud中Hystrix的使用方式及注意事項

  • ​​寫在前面​​
  • ​​一、springCloud 內建 HystrixCommand​​
  • ​​1.1、內建方式​​
  • ​​1.2、建立Maven工程​​
  • ​​1.3、配置 Hystrix(服務的降級回調)​​
  • ​​1.4、模拟請求測試​​
  • ​​二、springCloud + RestTemplate + HystrixCommand 實作​​
  • ​​三、springCloud + feignClient + Hystrix 實作​​
  • ​​三、[Demo代碼,可以參照這裡](https://github.com/tonels/Microservices/tree/ls-eurekaCloud)​​
  • ​​四、注意事項​​
  • ​​4.1、版本依賴(檢查)​​
  • ​​4.2、常見問題​​

寫在前面

版本依賴問題,基于Spring Cloud的微服務架構,必須考慮和慎重的問題,就是檢查版本依賴的問題,我們很多時候,百度或者谷歌别人的代碼實作的時候,面臨最多的問題也是,我們和參照的示例環境其實是不一樣的…這個在解決問題時,也是要考慮的問題。

一、springCloud 內建 HystrixCommand

1.1、內建方式

搜尋Maven中央倉庫,發現兩個類似的東西

SpringCloud中Hystrix的使用方式及注意事項

通過查找,發現

SpringCloud中Hystrix的使用方式及注意事項

還有這個starter的起始依賴,包括以下幾個包的實作封裝

SpringCloud中Hystrix的使用方式及注意事項

1.2、建立Maven工程

SpringCloud中Hystrix的使用方式及注意事項

添加依賴 jar

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>      

1.3、配置 Hystrix(服務的降級回調)

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableHystrix
@RestController
public class Hystrix {
    public static void main(String[] args) {
        SpringApplication.run(Hystrix.class, args);
    }

    @RequestMapping(value = "/")
    @HystrixCommand(fallbackMethod = "fallback_hello",
            commandProperties = {
                @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
            }
    )
    public String hello() throws InterruptedException {
        Thread.sleep(2000);
        return "Welcome Hystrix";
    }
    private String fallback_hello() {
        return "請求失敗,響應逾時...";
    }
}      

1.4、模拟請求測試

這裡可以試着去修改過時時間限制,也就是請求在多少時間内,不響應,即觸發降級回調方法

可以發現,當正常響應式,頁面傳回

SpringCloud中Hystrix的使用方式及注意事項

二、springCloud + RestTemplate + HystrixCommand 實作

這裡代碼不友善貼了,可以在Github看到      

三、springCloud + feignClient + Hystrix 實作

這裡代碼不友善貼了,可以在Github看到      

三、​​Demo代碼,可以參照這裡​​

四、注意事項

4.1、版本依賴(檢查)

4.2、常見問題

  • feignClient的請求 URL和參數映射
  • 盡量使用@RequestMapping()注解
  • 自定義fallback時,加上@Compoent注解
  • 使用feignClient時,要把 feign.hystrix.enabled=true 設定打開