13.斷路器:Hystrix客戶端
Netflix創建了一個名爲Hystrix的庫,用於實現斷路器模式。在微服務架構中,通常有多層服務調用,如以下示例所示:
圖13.1。微服務圖
較低級別的服務中的服務故障可能導致級聯故障一直到用戶。當對特定服務的調用超過circuitBreaker.requestVolumeThreshold
(默認值:20個請求)並且故障百分比大於circuitBreaker.errorThresholdPercentage
(默認值:> 50%)在由metrics.rollingStats.timeInMilliseconds
(默認值:10秒)定義的滾動窗口中時,服務將斷開並且不會再進行調用。在出現錯誤和斷路的情況下,開發人員可以提供降級服務。
圖13.2。Hystrix回退可防止級聯故障
斷路可以阻止級聯故障,並使服務不堪重負或無法恢復。降級服務可以是另一個受Hystrix保護的調用,靜態數據或合理的空值。降級服務可以形成一個鏈,以便第一個降級服務調用其他一些業務調用,也可能返回一些靜態數據。
13.1如何包含Hystrix
要在項目中包含Hystrix,請使用具有groud ID 爲org.springframework.cloud
和artifact ID 爲spring-cloud-starter-netflix-hystrix的starter
。有關使用當前Spring Cloud Release Train設置構建系統的詳細信息,請參閱Spring Cloud Project頁面。
以下示例顯示了具有Hystrix斷路器的最小Eureka服務器:
@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
由名爲“ javanica ”的Netflix contrib庫提供。Spring Cloud在連接到Hystrix斷路器的代理中自動包裝帶有該註釋的Spring bean。斷路器計算何時打開和關閉電路以及在發生故障時應採取的措施。
要配置@HystrixCommand,
您可以將commandProperties
屬性與@HystrixProperty
註解列表一起使用。有關詳細信息,請參見 此處 有關。可用屬性的詳細信息,請參閱Hystrix wiki。
13.2 傳播安全上下文或使用Spring Scopes
如果您希望某些線程本地上下文傳播到 @HystrixCommand
,則默認聲明不起作用,因爲它在線程池中執行該命令(如果超時)。您可以通過配置或直接在註解中切換Hystrix以使用與調用者相同的線程,方法是要求它使用不同的“ 隔離策略 ”。以下示例演示如何在註解中設置線程:
@HystrixCommand(fallbackMethod = "stubMyService",
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
}
)
...
如果您正在使用@SessionScope
或@RequestScope
,則同樣適用。如果遇到運行時異常,表示無法找到作用域上下文,則需要使用相同的線程。
您還可以選擇將hystrix.shareSecurityContext
屬性設置爲true
。這樣做會自動配置Hystrix併發策略插件鉤子,以便將SecurityContext從
主線程轉換到HystrixCommand使用的線程。Hystrix不會註冊多個Hystrix併發策略,因此可以通過聲明自己的HystrixConcurrencyStrategy
爲Spring bean來實現擴展機制。Spring Cloud在Spring上下文中查找您的實現,並將其包裝在自己的插件中。
13.3健康指標
連接斷路器的狀態也暴露在調用應用程序的/health
端點中,如以下示例所示:
{
"hystrix": {
"openCircuitBreakers": [
"StoreIntegration::getStoresByLocationLink"
],
"status": "CIRCUIT_OPEN"
},
"status": "UP"
}
13.4 Hystrix Metrics流
要啓用Hystrix度量流,請包含依賴關係spring-boot-starter-actuator
和設置management.endpoints.web.exposure.include: hystrix.stream
。這樣做會將/actuator/hystrix.stream作爲
管理端點公開,如以下示例所示:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
14.斷路器:Hystrix儀表板
Hystrix的主要好處之一是它能收集每個HystrixCommand的度量指標。Hystrix儀表板以高效的方式顯示每個斷路器的運行狀況。
圖14.1。Hystrix儀表板