HystrixCommand 動態(tài)配置

需求: @HystrixCommand 的commandProperties 屬性需要動態(tài)的配置,比如根據(jù)傳遞的參數(shù),動態(tài)的配置每個url 請求的?execution.isolation.thread.timeoutInMilliseconds屬性。(本文沒有使用Hystrix Rx 響應式模式)

實現(xiàn):

需求其實很簡單,記錄下自己探索過程。? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

首先:先補充下基本的知識, 我們得知道熔斷器circuitBreaker 的基本狀態(tài),下面是圖來自于vertx 狀態(tài)轉換之間的關系(作者是vertx 官網其中一本書,具體的忘記了),很具體的分析,請查閱詳細的資料。這里就只介紹一個半開啟的狀態(tài)(half-open state). 在半開啟的狀態(tài)下,允許下一次熔斷器的調用實際調用如果成功,熔斷器將復位并返回到關閉狀態(tài)(closed staus),回歸正常的模式;但是如果這次調用失敗,則熔斷器返回到熔斷狀態(tài)(open status),直到下次半開狀態(tài).? 我們可以通過設(setResetTimeout設置)來設置多久之后,進入half-open 的狀態(tài)。因為不了解狀態(tài)轉換的小伙伴們,會吃驚的遇到一種情況:請求的服務好了之后,code仍然執(zhí)行到fallback method里面去。原因是此時的狀態(tài)仍是closed state。需要等待一段時間(setResetTimeout)的時間,狀態(tài)變成half-open state時候,才allow you 重新嘗試訪問服務。這種狀態(tài)管理是為了保護當前的service,特別是遇到很大的流量的時候。好了下面看看,我是怎么解決這么簡單的問題的。

其次:需要補充的是,HystrixCommand 這個東西呢是從過攔截器來做的,也就是spring 的AOP,一開始我不知道,這個就是解決動態(tài)配置的關鍵所在: HystrixCommandAspect


第一步:最容易讓我想到的就是extend模式,這種方式得mysimpleObject extend HystrixCommand。通過 super(Setter.withGroupKey(HystrixCommandKey.Factory.asKey("ExampleGroup")).andcommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutMilliSeconds(500))), 這是不是很酷?

然后重寫 run 和fallback方法,執(zhí)行restTemplate調用服務。 調用的時候就簡簡單單的new?mysimpleObject(參數(shù)傳遞).execute 一下,就會執(zhí)行 run里面的方法,當出現(xiàn)熔斷的情況下,會執(zhí)行fallback里面的邏輯。可問題來了,這個東西不適用,因為首先 run() 函數(shù)不能傳遞參數(shù),其次是要為每種情況下都得extend?HystrixCommand, 沒有通用性。所以寫寫就放棄了,雖然可以使用范型等。

第二步:還記得HystrixCommand的本質是什么東西嗎? AOP! 好了,那就簡單了,那我大展一下AOP的本事,所以我刷刷下了差不多下面的代碼(不是全部,只是關鍵的步驟):

/**

* point cut

*/

@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")

public void hystrixCommandAnnotationPointcut() {

}

/**

* reset the hystrix command properties : request timeout

* @param joinPoint

* @throws Throwable

*/

@Before("hystrixCommandAnnotationPointcut()")

public void customizeHystrixCommandProperties(final JoinPoint joinPoint)throws Throwable {

Method method = AopUtils.getMethodFromTarget(joinPoint);

HystrixCommand hystrixCommand = method.getAnnotation(HystrixCommand.class);

HystrixProperty[] hystrixProperties = hystrixCommand.commandProperties();

for (HystrixProperty hystrixProperty : hystrixProperties){

if("execution.isolation.thread.timeoutInMilliseconds".equals(hystrixProperty.name())){

InvocationHandler invocationHandler = Proxy.getInvocationHandler(hystrixProperty);

? ? ? ? Field field = invocationHandler.getClass().getDeclaredField("memberValues");

? ? ? ? field.setAccessible(true);

? ? ? ? Map memberValues = (Map) field.get(invocationHandler);

? ? ? ? memberValues.put("value", “6000”);

? ? }

}

看見了吧,@HystrixCommand里面的屬性和字段都可以這樣的攔截然后重寫,好了,很興奮。動態(tài)的值從哪里傳呢?那當然是函數(shù)的參數(shù)了Object[] args = joinPoint.getArgs(); 這樣就可以把參數(shù)都搞到手了,我就可以隨心的動態(tài)的改變參數(shù)。

第三步:好了,我第二步寫完了,開始測試,奇怪的事情來了:

(1)@HystrixCommand 這個熔斷器根本就沒有執(zhí)行,一點反應都沒有

(2)更不用說 fallbackMethod了,fallback 當然也不會執(zhí)行。

解決(1)很簡單,你不知道的話就是一個坑,知道就很簡單,小伙伴們想一想,攔截器? 嗯! 本質是攔截器,那好,把 @HystrixCommand 放到了私有方法上,能起到作用嗎? 我看看了自己的idea, 不對啊,我已經標志是public method了,為什么呢? 因為@HystrixCommand加到了共有方法里面調用的方法上面(其實就是私有方法,攔截器是攔截不到的)。 所以解決辦法就是將?@HystrixCommand 放到公有方法上面

那么當run的時候,立刻出現(xiàn)了(2)的問題。為什么? exception: fallbackMethod 找不到。解決辦法是:在fallbackMethod加上參數(shù)和@HystrixCommand 注解的那個方法參數(shù)必須一致?。?/p>

好了,我問題都解決了,需求也實現(xiàn)了,可以順利的run一把了。但是當我訪問https的時候,毫無疑問,證書出現(xiàn)問題了, exception類型都是ssl。那順便說一下ssl是如何解決的, 我使用的是restTemplate,所以配置一下restTemplate 就沒有問題了,具體的代碼如下:

public static HttpClientinitSsl(){

/**defualt http client without ssl **/

? ? CloseableHttpClient httpclient = HttpClients.custom().build();

? ? Properties prop =new Properties();

? ? try {

/**load the properties **/

? ? ? ? prop.load(HttpSslUtil.class.getClassLoader().getResourceAsStream(HTTPS_SSL_PATH));

? ? ? ? KeyStore keyStore? = KeyStore.getInstance(KeyStore.getDefaultType());

? ? ? ? KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

? ? ? ? File KeyFile? =new? File(HttpSslUtil.class.getClassLoader().getResource(prop.getProperty(KEY_CERT_PATH)).getFile());

? ? ? ? keyStore.load(new FileInputStream(KeyFile), prop.getProperty(KEY_STORE_PASS).toCharArray());

? ? ? ? File trustFile =new File(HttpSslUtil.class.getClassLoader().getResource(prop.getProperty(trust_CERT_PATH)).getFile());

? ? ? ? trustStore.load(new FileInputStream(trustFile), prop.getProperty(TRUST_STORE_PASS).toCharArray());

? ? ? ? SSLConnectionSocketFactory socketFactory =new SSLConnectionSocketFactory(

new SSLContextBuilder()

.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())

.loadKeyMaterial(keyStore, prop.getProperty(KEY_STORE_PASS).toCharArray())

.build(),

? ? ? ? ? ? ? ? NoopHostnameVerifier.INSTANCE);

? ? ? ? httpclient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

? ? }catch (Exception ex) {

log.error("ssl init failed, https does not support", ex);

? ? }

return httpclient;

}

好了,問題了解決了,下次介紹一下 springboot 的@Conditional On Properties, 如何根據(jù)@Conditional 自動裝載不同的beans

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容