微服務架構 | 5.1 使用 Netflix Hystrix 斷路器
- 2022 年 1 月 29 日
- 筆記
- Hystrix, Spring Cloud, Spring Cloud Alibaba, Spring 微服務實踐學習筆記, 分佈式, 學習筆記, 微服務架構, 服務容災
前言
參考資料:
《Spring Microservices in Action》
《Spring Cloud Alibaba 微服務原理與實戰》
《B站 尚硅谷 SpringCloud 框架開發教程 周陽》
Hystrix 是一個延遲和容災庫,旨在隔離遠程系統、服務和第三方庫的訪問點,停止級聯故障,並在故障不可避免的複雜分佈式系統中實現彈性;
1. Hystrix 基礎知識
1.1 Hystrix 斷路器強調調用
- Hystrix 斷路器沒有提供者與消費者的區別,它強調的是服務與資源之間的中間人,如:服務請求數據庫與服務內部調用;
- 因此在服務消費者與服務提供者里,凡是涉及數據庫訪問與服務間調用都可以使用 Hystrix 斷路器;
- 構建斷路器模式、後備模式和艙壁模式的實現需要對線程和線程管理有深入的理解;
- Netflix 的 Hystrix 庫里封裝了線程操作,開發人員可以只需要關注業務開發與 Spring Cloud;
1.2 兩大類別的 Hystrix 實現
- 使用 Hystrix 斷路器包裝所有服務中所有對數據庫的調用;
- 使用 Hystrix 斷路器包裝所有服務之間的內部服務調用;
1.3 艙壁策略
1.4 Hystrix 在遠程資源調用失敗時的決策過程
- 快照時間窗:查看在 10 s 內發生的調用次數:
- 請求總數閥值:如果調用次數少於在這個窗口內設置的最小調用次數,那麼即使有幾個調用失敗,Hystrix 也不會採取行動;
- 反之,進行下一步;
- 查看整體故障的百分比:
- 錯誤百分比閥值:如果故障的總體百分比超過閾值, Hystrix 將觸發斷路器,使將來幾乎所有的調用都失敗;
- 當 Hystrix 斷路器被觸發時,它將嘗試啟動一個新的活動窗口:
- 每隔 5s(可配置的), Hystrix 會通過一個遠程調用。 如果調用成功, Hystrix將重置斷路器並重新開始讓調用通過。 如果調用失敗, Hystrix將保持斷路器斷開;
1.5 當 Hystrix 斷路器打開後
- 再有請求調用的時候,將不會調用主邏輯,而是直接調用降級fallback。通過斷路器,實現了自動地發現錯誤並將降級邏輯切換為主邏輯,減少響應延遲的效果;
- hystrix 會啟動一個休眠時間窗,在這個時間窗內,降級邏輯是臨時的成為主邏輯;
- 當休眠時間窗到期,斷路器將進入半開狀態,釋放一次請求到原來的主邏輯上;
- 如果此次請求正常返回,那麼斷路器將繼續閉合,主邏輯恢復;
- 反之,斷路器繼續進入打開狀態,休眠時間窗重新計時;
1.6 Hystrix 的所有配置
@HystrixCommand(fallbackMethod = "str_fallbackMethod",
groupKey = "strGroupCommand",
commandKey = "strCommand",
threadPoolKey = "strThreadPool",
commandProperties = {
// 設置隔離策略,THREAD 表示線程池 SEMAPHORE:信號池隔離
@HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
// 當隔離策略選擇信號池隔離的時候,用來設置信號池的大小(最大並發數)
@HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests", value = "10"),
// 配置命令執行的超時時間
@HystrixProperty(name = "execution.isolation.thread.timeoutinMilliseconds", value = "10"),
// 是否啟用超時時間
@HystrixProperty(name = "execution.timeout.enabled", value = "true"),
// 執行超時的時候是否中斷
@HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout", value = "true"),
// 執行被取消的時候是否中斷
@HystrixProperty(name = "execution.isolation.thread.interruptOnCancel", value = "true"),
// 允許回調方法執行的最大並發數
@HystrixProperty(name = "fallback.isolation.semaphore.maxConcurrentRequests", value = "10"),
// 服務降級是否啟用,是否執行回調函數
@HystrixProperty(name = "fallback.enabled", value = "true"),
// 是否啟用斷路器
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
// 該屬性用來設置在滾動時間窗中,斷路器熔斷的最小請求數。例如,默認該值為 20 的時候,
// 如果滾動時間窗(默認10秒)內僅收到了19個請求, 即使這19個請求都失敗了,斷路器也不會打開。
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
// 該屬性用來設置在滾動時間窗中,表示在滾動時間窗中,在請求數量超過
// circuitBreaker.requestVolumeThreshold 的情況下,如果錯誤請求數的百分比超過50,
// 就把斷路器設置為 "打開" 狀態,否則就設置為 "關閉" 狀態。
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
// 該屬性用來設置當斷路器打開之後的休眠時間窗。 休眠時間窗結束之後,
// 會將斷路器置為 "半開" 狀態,嘗試熔斷的請求命令,如果依然失敗就將斷路器繼續設置為 "打開" 狀態,
// 如果成功就設置為 "關閉" 狀態。
@HystrixProperty(name = "circuitBreaker.sleepWindowinMilliseconds", value = "5000"),
// 斷路器強制打開
@HystrixProperty(name = "circuitBreaker.forceOpen", value = "false"),
// 斷路器強制關閉
@HystrixProperty(name = "circuitBreaker.forceClosed", value = "false"),
// 滾動時間窗設置,該時間用於斷路器判斷健康度時需要收集信息的持續時間
@HystrixProperty(name = "metrics.rollingStats.timeinMilliseconds", value = "10000"),
// 該屬性用來設置滾動時間窗統計指標信息時劃分"桶"的數量,斷路器在收集指標信息的時候會根據
// 設置的時間窗長度拆分成多個 "桶" 來累計各度量值,每個"桶"記錄了一段時間內的採集指標。
// 比如 10 秒內拆分成 10 個"桶"收集這樣,所以 timeinMilliseconds 必須能被 numBuckets 整除。否則會拋異常
@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
// 該屬性用來設置對命令執行的延遲是否使用百分位數來跟蹤和計算。如果設置為 false, 那麼所有的概要統計都將返回 -1。
@HystrixProperty(name = "metrics.rollingPercentile.enabled", value = "false"),
// 該屬性用來設置百分位統計的滾動窗口的持續時間,單位為毫秒。
@HystrixProperty(name = "metrics.rollingPercentile.timeInMilliseconds", value = "60000"),
// 該屬性用來設置百分位統計滾動窗口中使用 「 桶 」的數量。
@HystrixProperty(name = "metrics.rollingPercentile.numBuckets", value = "60000"),
// 該屬性用來設置在執行過程中每個 「桶」 中保留的最大執行次數。如果在滾動時間窗內發生超過該設定值的執行次數,
// 就從最初的位置開始重寫。例如,將該值設置為100, 滾動窗口為10秒,若在10秒內一個 「桶 」中發生了500次執行,
// 那麼該 「桶」 中只保留 最後的100次執行的統計。另外,增加該值的大小將會增加內存量的消耗,並增加排序百分位數所需的計算時間。
@HystrixProperty(name = "metrics.rollingPercentile.bucketSize", value = "100"),
// 該屬性用來設置採集影響斷路器狀態的健康快照(請求的成功、 錯誤百分比)的間隔等待時間。
@HystrixProperty(name = "metrics.healthSnapshot.intervalinMilliseconds", value = "500"),
// 是否開啟請求緩存
@HystrixProperty(name = "requestCache.enabled", value = "true"),
// HystrixCommand的執行和事件是否打印日誌到 HystrixRequestLog 中
@HystrixProperty(name = "requestLog.enabled", value = "true"),
},
threadPoolProperties = {
// 該參數用來設置執行命令線程池的核心線程數,該值也就是命令執行的最大並發量
@HystrixProperty(name = "coreSize", value = "10"),
// 該參數用來設置線程池的最大隊列大小。當設置為 -1 時,線程池將使用 SynchronousQueue 實現的隊列,
// 否則將使用 LinkedBlockingQueue 實現的隊列。
@HystrixProperty(name = "maxQueueSize", value = "-1"),
// 該參數用來為隊列設置拒絕閾值。 通過該參數, 即使隊列沒有達到最大值也能拒絕請求。
// 該參數主要是對 LinkedBlockingQueue 隊列的補充,因為 LinkedBlockingQueue
// 隊列不能動態修改它的對象大小,而通過該屬性就可以調整拒絕請求的隊列大小了。
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "5"),
}
)
2. 對服務使用 Hystrix 斷路器
2.1 引入 pom.xml 依賴
<!--拉取 Spring Cloud Hystrix 依賴項-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
- 以下依賴是核心 Netflix Hystrix 庫,一般情況下不需要我們引入;
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-javanica</artifactId>
<version>1.5.9</version>
</dependency>
2.2 修改 bootstrap.yml 配置文件
- 如果需要用到 Feign 調用才需要進行配置;
feign:
hystrix:
#開啟feign的hystrix支持,默認是false
enabled: true
2.3 在主程序類上標註註解
-
@EnableCircuitBreaker:表示激活使用服務降級相關策略;
-
@EnableHystrix:繼承了@EnableCircuitBreaker,並對其進行了在封裝;
-
如果忘記將該註解添加到主程序類中,那麼 Hystrix 斷路器不會處於活動狀態。在服務啟動時,也不會收到任何警告或錯誤消息;
2.4 在業務類上使用 @HystrixCommand 註解(斷路器模式)
在 service 包下的業務類里;方法級註解;
@HystrixCommand
private Xxx getXxx(String xxxId) {
return xxxService.getXxx(xxxId);
}
@HystrixCommand
註解將動態生成一個代理,該代理將包裝該方法,並通過專門用於處理遠程調用的線程池來管理對該方法的所有調用;- 當調用時間超過 1000 ms 時,斷路器將中斷對 getXxx()。並拋出r如下異常:
- com.nextflix.hystrix.exception.HystrixRuntimeException;
2.5 定製斷路器(後備策略、艙壁策略)
- 默認情況下,不帶屬性配置的
@HystrixCommand
註解,會將所有遠程服務調用都放在同一線程池下。可能會導致應用程序中出現問題;
@HystrixCommand(
fallbackMethod="getYyy", //【可選】艙壁策略,定義線程池的唯一名稱後備策略,如果 getXxx 調用失敗,那麼就會調用該方法。注意兩個方法參數需保持一致
threadPoolKey="xxxThreadPool", //【可選】艙壁策略,定義線程池的唯一名稱艙壁策略,定義線程池的唯一名稱
threadPoolProperties={
@HystrixProperty(name="coreSize",value="30"), //線程池中線程的最大數量
@HystrixProperty(name="maxQueueSize", value="10") //定義一個位於線程池前的隊列,對傳入的請求進行排隊
},
//通過 commandProperties 屬性來定製斷路器的行為
commandProperties={
@HystrixProperty(name="circuitBreaker.requestVolumeThreshold", value="10"), //斷路器觸發前 10s 內需要發生的連續調用數量
@HystrixProperty(name="circuitBreaker.errorThresholdPercentage", value="75"), //在斷路器跳閘之前必須達到的調用失敗百分比
@HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds", value="7000"), //斷路器跳閘之後, Hystrix 允許一個調用通過以便查看服務是否恢復健康之前 Hystrix 的休眠時間
@HystrixProperty(name="metrics.rollingStats.timeInMilliseconds", value="15000"), //Hystr ix 用來監視服務調用問題的窗口大小,其默認值為 10 000ms
@HystrixProperty(name="metrics.rollingStats.numBuckets", value="5"), //定義的滾動窗口中收集統計信息的次數
//@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="5000"), //設置斷路器超時時間
@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE"), //修改命令池的隔離設置
}
)
private Xxx getXxx(String xxxId) {
return xxxService.getXxx(xxxId);
}
private Yyy getYyy(String yyyId) {
return yyyService.getYyy(yyyId);
}
屬性詳解:
-
threadPoolProperties:
maxQueueSize
:如果將其值設置為 -1,則將使用 Java SynchronousQueue 來保存所有傳人的請求。同步隊列本質上會強制要求正在處理中的請求數量永遠不能超過線程池中可用線程的數量;maxQueueSize
:設置為大於 1 的值將使用 Java LinkedBlockingQueue;LinkedBlockingQueue 的使用允許開發人員即使所有線程都在忙於處理請求,也能對請求進行排隊;maxQueueSize
屬性只能在線程池首次初始化時設置(例如,在應用程序啟動時)。Hystrix 允許通過使用 queueSizeRejectionThreshold 屬性來動態更改隊列的大小,但只有在 maxQueueSize 屬性的值大於 0 時,才能設置此屬性;
-
commandProperties:
execution.isolation.thread.timeoutInMilliseconds
:設置斷路器超時時間。在實際開發中應該把問題放在解決性能問題而不是增加默認超時。如果確實遇到一些比其他服務調用需要更長時間的服務調用,務必將這些服務調用隔離到單獨的線程池中;metrics.rollingStats.numBuckets
:其值需要被metrics.rollingStats.timeInMilliseconds
整除。上例 Hystrix 使用 15s 的窗口,並將統計數據收集到長度為 3 s 的 5 個桶中。查的統計窗口越小且在窗口中保留的桶的數量越多,就越會加劇高請求服務的 CPU 利用率和內存使用率;execution.isolation.strategy
:斷路器執行時,有兩種不同的隔離策略;- THREAD(線程):默認,保護調用的每個 Hystrix命令都在一個單獨的線程池中運行;
- SEMAPHORE(信號量):輕量級隔離,適用於服務量很大且正在使用異步 l/O 編程模型(假設使用的是像 Netty 這樣的異步 IO 容器)運行的情況;
-
其他配置屬性詳情請見本篇《1.6 Hystrix 的所有配置》;
2.6 使用類級註解統一 Hystrix 配置
- @DefaultProperties:相當於修改該類下 Hystrix 配置的默認值;
@DefaultProperties(
commandProperties={
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="10000")}
class MyService{
...
}
3. 使用 HystrixConcurrencyStrategy 聯繫線程上下文
3.1 Hystrix 的上下文隔離
- 默認情況下, Hystrix 以 THREAD 隔離策略運行;
- 這使每個 Hystrix 命令都在一個單獨的線程池中運行,該線程池不與父錢程共享它的上下文;
- 因此默認情況下,對被父線程調用並由 @HystrixComman 保護的方法而言,在父線程中設置為 ThreadLocal 值的值都是不可用的;
- 解決方法:定義一種並發策略,能將附加的父線程上下文注入由 由 Hystrix 命令管理的線程中;
3.2 自定義 Hystrix 井發策略類
//擴展基本的 Hystrix ConcurrencyStrategy 類
public class ThreadLocalAwareStrategy extends HystrixConcurrencyStrategy{
private HystrixConcurrencyStrategy existingConcurrencyStrategy;
//將已存在的並發策略傳入到構造器中
public ThreadLocalAwareStrategy(HystrixConcurrencyStrategy existingConcurrencyStrategy) {
this.existingConcurrencyStrategy = existingConcurrencyStrategy;
}
@Override
public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) {
return existingConcurrencyStrategy != null
? existingConcurrencyStrategy.getBlockingQueue(maxQueueSize)
: super.getBlockingQueue(maxQueueSize);
}
@Override
public <T> HystrixRequestVariable<T> getRequestVariable(
HystrixRequestVariableLifecycle<T> rv) {
return existingConcurrencyStrategy != null
? existingConcurrencyStrategy.getRequestVariable(rv)
: super.getRequestVariable(rv);
}
@Override
public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
HystrixProperty<Integer> corePoolSize,
HystrixProperty<Integer> maximumPoolSize,
HystrixProperty<Integer> keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
return existingConcurrencyStrategy != null
? existingConcurrencyStrategy.getThreadPool(threadPoolKey, corePoolSize,
maximumPoolSize, keepAliveTime, unit, workQueue)
: super.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize,
keepAliveTime, unit, workQueue);
}
@Override
public <T> Callable<T> wrapCallable(Callable<T> callable) {
//注入 Callable 實現,用來設置 UserContext
return existingConcurrencyStrategy != null
? existingConcurrencyStrategy
.wrapCallable(new DelegatingUserContextCallable<T>(callable, UserContextHolder.getContext()))
: super.wrapCallable(new DelegatingUserContextCallable<T>(callable, UserContextHolder.getContext()));
}
}
3.3 定義一個 Java Callable 類,將 UserContext 注入 Hystrix 命令中
public final class DelegatingUserContextCallable<V> implements Callable<V> {
private final Callable<V> delegate;
private UserContext originalUserContext;
//傳遞原始 Callable 類,自定義 Callable 將調用 Hystrix 保護的代碼與來自父線程的 UserContext
public DelegatingUserContextCallable(Callable<V> delegate,
UserContext userContext) {
this.delegate = delegate;
this.originalUserContext = userContext;
}
//call() 方法在被 @HystrixCommand 註解保護的方法之前調用
public V call() throws Exception {
//已設置 UserContext,存儲 UserContext 的 ThreadLocal 變量與運行受 Hystrix 保護的方法的線程相關聯
UserContextHolder.setContext( originalUserContext );
try {
//在 Hystrix 保護的方法上調用 call() 方法
return delegate.call();
}
finally {
this.originalUserContext = null;
}
}
public static <V> Callable<V> create(Callable<V> delegate,
UserContext userContext) {
return new DelegatingUserContextCallable<V>(delegate, userContext);
}
}
3.4 配置 Spring Cloud 以使用自定義 Hystrix 井發策略
@Configuration
public class ThreadLocalConfiguration {
//當構造配置對象時,它將自動裝配在現有的 HystrixConcurrencyStrategy 中
@Autowired(required = false)
private HystrixConcurrencyStrategy existingConcurrencyStrategy;
@PostConstruct
public void init() {
// 保留現有的 Hystrix 插件的引用
//因為要註冊一個新的並發策略,所以要獲取所有其他的 Hystrix 組件,然後重新設置 Hystrix 組件
HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance()
.getEventNotifier();
HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance()
.getMetricsPublisher();
HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance()
.getPropertiesStrategy();
HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins.getInstance()
.getCommandExecutionHook();
HystrixPlugins.reset();
//使用 Hystrix 插件註冊自定義的 Hystrix 並發策略(ThreadConcurrency Strategy)
HystrixPlugins.getInstance().registerConcurrencyStrategy(new ThreadLocalAwareStrategy(existingConcurrencyStrategy));
//重新註冊 Hystrix 插件使用的所有組件
HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);
HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
}
}
4. 使用 hystrixDashboard 實現服務監控
- Hystrix 提供了准實時的調用監控(Hystrix Dashboard),其會持續地記錄所有通過Hystrix發起的請求的執行信息,並以統計報表和圖形的形式展示給用戶,包括每秒執行多少請求多少成功,多少失敗等;
- Netflix通過 hystrix-metrics-event-stream 項目實現了對以上指標的監控;
- Spring Cloud 也提供了 Hystrix Dashboard 的整合,對監控內容轉化成可視化界面;
4.1 引入 pom.xml 依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
4.2 修改 application.yml 配置文件
主要是修改端口號;
server:
port: 9001
4.3 在主程序類上標註註解
@EnableHystrixDashboard:表名啟用 Hystrix Dashboard 對調用進行監控;
4.4 配置被監控的服務
1. 添加 pom.xml 依賴文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2. 在主啟動類中指定監控路徑
@SpringBootApplication
@EnableEurekaClient //本服務啟動後會自動註冊進eureka服務中
@EnableCircuitBreaker//對hystrixR熔斷機制的支持
public class Application{
public static void main(String[] args){
SpringApplication.run(Application.class,args);
}
/**
*此配置是為了服務監控而配置,與服務容錯本身無關,springcloud升級後的坑
*ServletRegistrationBean因為springboot的默認路徑不是"/hystrix.stream",
*只要在自己的項目里配置上下面的servlet就可以了
*/
@Bean
public ServletRegistrationBean getServlet() {
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
4.5 訪問圖形化界面
4.6 查看監控圖
- 監控圖示例:
- 監控圖圖例解釋:
- 實心圈:有兩種含義:
- 通過顏色的變化代表了實例的健康程度,它的健康度從:綠色 < 黃色 < 橙色 < 紅色 遞減;
- 其大小也會根據實例的請求流量發生變化,流量越大該實心圓就越大;
- 所以通過該實心圓的展示,就可以在大量的實例中快速的發現故障實例和高壓力實例;
- 曲線:
- 用來記錄2分鐘內流量的相對變化,可以通過它來觀察到流量的上升和下降趨勢;
最後
