1. 程式人生 > >《Spring Cloud Netflix官方文件》3.熔斷器:Hystrix Clients

《Spring Cloud Netflix官方文件》3.熔斷器:Hystrix Clients

原文連結

Netfilix建立了一個名為Hystrix的庫,實現了熔斷器模式。在微服務架構中,它通常有多個服務呼叫層。

圖3.1 微服務圖

一個底層服務的故障會引發直至使用者互動層的連鎖故障。在一個設定時長為“metrics.rollingStats.timeInMilliseconds”(預設為十秒)的滾動視窗內,對一個特定服務的請求數大於“circuitBreaker.requestVolumeThreshold”(預設為20個),並且故障率大於“circuitBreaker.errorThresholdPercentage”(預設大於百分之五十)的時候,啟用熔斷機制以使請求失效。在熔斷和報錯的情況下,開發者可以啟用回退機制。

圖3.2 Hystrix回退以防止連鎖故障

啟用熔斷機制能防止連鎖故障的情況,給故障服務提供時間以恢復正常。回退操作可以是另一個Hystrix受保護的呼叫、靜態資料或是一個恰當的空值。回退操作可能是成串的,所以第一個回退操作會做一些其他的業務請求,讓故障回退到預設的值。

3.1 如何引入Hystrix

使用group為“org.springframework.cloud”, artifact id為“spring-cloud-starter-hystrix”的啟動器引入Hystrix。請參閱Spring Cloud Project頁面,以獲取有關使用當前Spring Cloud Release Train設定構建系統的詳細資訊。

Boot app 樣例:

@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由Netflix contrib library提供,被稱作“javanica”。Spring Cloud會自動將包含該註釋的Spring bean封裝在連線到Hystrix熔斷器的代理中。熔斷器會計算何時啟用或關閉熔斷機制,並決定在故障時該做什麼。

可以使用帶有@HystrixProperty註解列表的commandProperties屬性配置@HystrixCommand。點選這裡獲取更多詳情。另外,有關可用屬性的詳細資訊,請參閱Hystrix wiki。

3.2傳播Security Context或使用Spring Scope

如果想要一些執行緒本地上下文傳播到@HystrixCommand,預設的宣告將不起作用,因為它執行的是執行緒池中的命令(在超時的情況下)。可以使用某種配置將Hystrix切換為使用與呼叫方相同的執行緒,或直接在註解中請求使用不同的“隔離策略”。如下所示:

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

以上操作,同樣適用於使用@SessionScope或@RequestScope的時候。當丟擲“無法找到範圍內的上下文”的執行時異常,就需要執行這些操作。

同樣可以設定屬性“hystrix.shareSecurityContext”為true。這樣做會自動配置一個Hystrix併發策略外掛鉤子,它將從主執行緒傳輸SecurityContext到Hystrix命令使用的鉤子。Hystrix不允許註冊多個hystrix併發策略。因此會通過將自己的HystrixConcurrencyStrategy宣告為Spring bean的方法,使用擴充套件機制。Spring Cloud會在上下文中查詢你的實現,並封裝進它自己的外掛中。

3.3健康監控

連線熔斷器的狀態也可以在請求應用程式的/health埠檢視。

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

3.4 Hystrix 資料流

配置spring-boot-starter-actuator的依賴以啟用Hystrix 資料流。這將啟用埠/hystrix.stream作為一個管理終端。

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