[Spring Cloud] 4.3 Circuit Breaker : Hystrix Clients

4.3 Circuit Breaker: Hystrix Clients

斷路器:Hystrix客戶端

Netflix實現了一個斷路器模式的類庫叫作Hystrix。 在一個微服務架構中一般來講會有一個多層服務的調用。java

image Figure 1. Microservice Graphgit

對於用戶來講,一個底層服務失敗,就會引起一系列的連鎖反應。當調用一個服務達到一個閾值(Hystrix默認是5秒內20次失敗),斷路器打開,並拒絕調用。開發者能夠指定一些特定錯誤,來觸發降級操做。github

image Figure 2. Hystrix fallback prevents cascading failuresweb

斷路器打開後,阻止了連鎖反應而且容許丟棄或者等待服務從新響應。降級調用是Hystrix提供的另外一種策略,好比提供一個靜態數據或者一個合理的空值。 降級也能夠鏈式觸發,好比,一個服務降級可能引發另一些業務調用獲得一個降級的靜態數據。spring

4.3.1 How to Include Hystrix 如何引入Hystrix

在工程中引入Hystrix只須要使用特定的starter就能夠了。如:group:org.springframework.cloud,artifact id : spring-cloud-starter-hystrix。如何使用Spring Cloud構建系統能夠參見 Spring Cloud Project page安全

例如:架構

@SpringBootApplication
@EnableCircuitBreaker
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

@Component
public class StoreIntegration {

    @HystrixCommand(fallbackMethod = "defaultStores")
    public Object getStores(Map<String, Object> parameters) {
        //do stuff that might fail
    }

    public Object defaultStores(Map<String, Object> parameters) {
        return /* something useful */;
    }
}

@HystrixCommand是由Netfix開源的javanica提供的。併發

Spring Cloud 經過這個註解自動包裝了一個代理去關聯Hystrix斷路器。 斷路器提供對調用鏈路的斷開和閉合控制,主要用於調用失敗處理。spring-boot

能夠經過配置@HystrixCommandcommandProperties屬性來列出一些列的@HystrixProperty,來對Hystrix斷路器進行配置。詳情見此處。詳細的屬性配置項說明能夠參見Hystrix的Wiki微服務

4.3.2 Propagating the Security Context or using Spring Scopes 安全上下文的傳播機制或者Spring做用域配置

若是你想要讓一些本地線程上下文傳播到@HystrixCommand中,那麼默認狀況下是不行的,由於Hystrix是在一個普通的線程池中執行的。

你能夠二選一來達到傳播上下文的目的,要麼配置Hystrix,讓其使用同一個線程去處理調用;要麼,乾脆直接在註解中使用一個不一樣的隔離策略。例如:

@HystrixCommand(fallbackMethod = "stubMyService",
    commandProperties = {
      @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
    }
)
...

一樣的,若是你使用過@SessionScope或者@RequestScope。你就會知道你這樣作是由於,運行時異常會找不到做用域的上下文。

你還能夠配置hystrix.shareSecurityContexttrue。這樣作,將會讓Hystris自動配置一個併發策略插件,當使用Hystris命令從主線程遷移SecurityContext時自動同步。Hystris不容許多個併發策略同時存在,因此須要本身擴展一個HystrixConcurrencyStrategy註冊到Spring中。Spring Cloud會自動在Spring上下文中發現你的實現類,並自動包裝成一個自定義Hystrix插件。

4.3.3 Health Indicator 健康指示器

斷路器的狀態也能夠經過/health接口被應用查看到。

{
    "hystrix": {
        "openCircuitBreakers": [
            "StoreIntegration::getStoresByLocationLink"
        ],
        "status": "CIRCUIT_OPEN"
    },
    "status": "UP"
}

4.3.4 Hystrix Metrics Stream Hystrix實時數據監控(這個說法可能不靠譜^_^)

開啓流量測量須要引入依賴:spring-boot-starter-actuator。將會提供一個/hystrix.stream管理接口。

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
相關文章
相關標籤/搜索