Hystrix異常處理及執行緒池劃分

2021-09-13 11:09:44 字數 1771 閱讀 3545

在hystrixcommand實現的run()方法中丟擲異常時,除了hystrixbadrequestexception之外,其他異常均會被hystrix認為命令執行失敗並觸發服務降級的處理邏輯,所以當需要在命令執行中丟擲不觸發服務降級的異常時來選擇它。

在使用註解配置實現hystrix命令時,可以忽略指定的異常型別,只需要通過設定@hystrixcommand註解的ignoreexceptions引數,如下:

@hystrixcommand(fallbackmethod = "getdefaultuser", ignoreexceptions = nullpointerexception.class)

public user finduserbyid(long id) ", user.class, id);

}

當上述方法丟擲nullpointerexception的異常時,不會觸發後續的fallback邏輯。

在傳統的繼承實現hystrix命令時,可以在getfallback()方法中通過getexecutionexception()方法來獲取具體的異常,然後通過判斷來進入不同的處理邏輯。

在註解配置方式中,只需要在fallback實現方法的引數中增加throwable e物件的定義,這樣在方法內部就可以獲取觸發服務降級的具體異常內容。

public usercommand(resttemplate resttemplate, long id)
從上面的**中可以看出,我們並沒有直接設定命令名稱,而是先呼叫了withgroupkey來設定命令組名,然後才通過呼叫andcommandkey來設定命令名。

在setter中只有withgroupkey靜態函式可以建立setter的例項,因此groupkey是每個setter必須的引數,而commandkey則是乙個可選引數。

通過設定命令組,hystrix會根據組來組織和統計命令的告警、儀錶盤等資訊。除了上述可以統計資訊之外,hystrix命令預設的執行緒劃分也是根據命令分組來實現的。預設情況下,hystrix會讓相同組名的命令使用同乙個執行緒池,所以我們需要在建立hystrix命令時為其指定命令組名來實現預設的執行緒池劃分。

hystrix還提供hystrixthreadpoolkey來對執行緒池進行設定,通過它可以實現更細粒度的執行緒池劃分。

public usercommand(resttemplate resttemplate, long id)
在沒有指定hystrixthreadpoolkey的情況下,會使用命令組的方式來劃分執行緒池。通常情況下,我們盡量使用hystrixthreadpoolkey來指定執行緒池的劃分。因為多個不同的命令可能從業務邏輯上來看屬於同乙個組,但是往往從實現本身上需要跟其他命令來進行隔離。

使用註解時只需要設定註解的commandkey、groupkey以及threadpoolkey屬性即可,他分別表示了命令名稱、分組以及執行緒池劃分。

@hystrixcommand(fallbackmethod = "getdefaultuser", ignoreexceptions = nullpointerexception.class,

commandkey = "finduserbyid", groupkey = "usergroup", threadpoolkey = "finduserbyidthread")

public user finduserbyid(long id) ", user.class, id);

}

spring-cloud-example

Java執行緒池異常處理原理

executorservice exec executors.newfixedthreadpool 8 以上述 為例,得到executorservice例項後,我們可以通過兩種方式提交任務 runnable exec.execute runnable 和 exec.submit runnable e...

python執行緒池異常處理方案

from multiprocessing.pool import threadpool 建立乙個執行緒池 pool size 4 thread pool threadpool pool size 呼叫map方法,將會對迭代物件拆包並各自開啟執行緒交由目標函式處理 pool output thread...

Hystrix執行緒池 訊號量

5.執行緒池 請求佇列 訊號量是否佔滿 如果與命令相關的執行緒池和請求佇列或者訊號量已經被佔滿,那麼hystrix也不會執行命令,而是轉接到fallback處理邏輯。命令名稱 分組以及執行緒池劃分 super setter.withgroupkey hystrixcommandgroupkey.fa...