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 合并做用域的区别
相关文章
相关标签/搜索