Hystrix:HystrixCollapser請求合併

偶爾在spring4all,看到DiDi關於hystrix請求合併的一篇文章 Spring Cloud Hystrix的請求合併,查閱資料又整理了一下。spring

具體業務概念,什麼是請求合併?請求合併優缺點?能夠參考DiDi的文章,而後我把我使用過程當中的問題及解決方法寫出來bash

代碼

合併請求服務實現

@HystrixCollapser(batchMethod = "testAll", collapserProperties = {
        @HystrixProperty(name = "timerDelayInMilliseconds", value = "3000")
})
public Future<Demo> test(String param) {
    return null;
}

@HystrixCommand
public List<Demo> testAll(List<String> params) {
    logger.info("合併操做線程 --> {} --> params --> {}", Thread.currentThread().getName(), params);
    return return restTemplate.getForObject("http://DEMO-SERVICE/demo?params={1}", List.class, StringUtils.join(params, ","));;
}
複製代碼

對外請求接口定義:

@RequestMapping("/test")
public SysDict test() throws ExecutionException, InterruptedException {
    //開啓上下文TheardLocal
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    Future<Demo> demo1 = testService.test(RandomUtil.randomNumbers(5));
    Future<Demo> demo2 = testService.test(RandomUtil.randomNumbers(5));
    System.out.println(demo1.get());
    System.out.println(demo2.get());
    context.close();
    return null;
}
複製代碼

效果以下:

image

  • 如圖兩次調用Service.test()被合併成一次服務調用。

若是我請求兩次接口也就是會調用四次Service.test(),那麼會合併成幾回服務調用呢?

image

  • 如圖,兩次請求仍是被合併成了兩次服務調用。

怎麼實現兩次請求,合併成一次服務調用?

@HystrixCollapser scope屬性
//全部線程的請求中的屢次服務請求進行合併。
Scope.GLOBAL;
//默認,對一次請求的屢次服務調用合併
Scope.REQUEST; 
複製代碼

改造後代碼:

@HystrixCollapser(batchMethod = "testAll", scope = Scope.GLOBAL, collapserProperties = {
    @HystrixProperty(name = "timerDelayInMilliseconds", value = "3000")
})
public Future<Demo> test(String param) {
    return null;
}
複製代碼

改造後效果:

image

總結

  1. 這裏單個請求的service 返回的 Future 包裝的對象,若是使用原對象,則是同步請求,不會合並。
  2. HystrixRequestContext 接口訪問須要開啓上下文對象,其實就是使用TheardLoacl 初始化一個上下文對象。
  3. 暫時還不支持 feign 整合
  4. @HystrixCollapser Scope.REQUEST Scope.GLOBAL 合併做用域的區別
相關文章
相關標籤/搜索