因为依赖服务的线程池有限,将出现排队等待与响应延迟的情况,为了优化这些问题,Hystrix提供了HystrixCollapser来实现请求的合并,以减少 通信消耗和线程数的占用。
HystrixCollapser实现了在HystrixCommand之前放置一个合并处理器,将处于一个很短的时间窗(默认10毫秒)内对同一依赖服务的多个请求进行整合并以批量方式发起请求的功能(服务提供方也需要提供相应的批量实现接口)。
这里我们只讲解使用注解实现请求合并器。
首先服务提供者,需要包含一个批量处理的服务。
@RequestMapping("/getbook6")
public List<String> book6(String ids) {
System.out.println("ids>>>>>>>>>>>>>>>>>>>>>" + ids);
ArrayList<String> books = new ArrayList<>();
books.add("哈哈2");
books.add("哈哈3");
books.add("哈哈4");
books.add("哈哈5");
books.add("哈哈6");
return books;
}
@RequestMapping("/getbook6/{id}")
public String book61(@PathVariable Integer id) {
return "哈哈1";
}
服务消费者service:
@Service
public class HelloService2 {
@Autowired
private RestTemplate restTemplate;
@HystrixCollapser(batchMethod = "test11",collapserProperties = {@HystrixProperty(name ="timerDelayInMilliseconds",value = "1000")})
public Future<String> test10(Long id) {
return null;
}
@HystrixCommand
public List<String> test11(List<Long> ids) {
System.out.println("test9---------"+ids+"Thread.currentThread().getName():" + Thread.currentThread().getName());
String[] books = restTemplate.getForObject("http://HELLOSERVICE-1/getbook6?ids={1}", String[].class, StringUtils.join(ids, ","));
return Arrays.asList(books);
}
}
服务消费者controller:
@RequestMapping("/test8")
@ResponseBody
public void test8() throws ExecutionException, InterruptedException {
// HystrixRequestContext context = HystrixRequestContext.initializeContext();
Future<String> f1 = helloService2.test10(1l);
Future<String> f2 = helloService2.test10(2l);
Future<String> f3 = helloService2.test10(3l);
String b1 = f1.get();
String b2 = f2.get();
String b3 = f3.get();
Thread.sleep(3000);
Future<String> f4 = helloService2.test10(4l);
String b4 = f4.get();
System.out.println("b1>>>"+b1);
System.out.println("b2>>>"+b2);
System.out.println("b3>>>"+b3);
System.out.println("b4>>>"+b4);
// context.close();
}
结果:
前三个请求和合并,因为时间窗的时间是1秒,睡眠3秒后,最后一个请求单独执行,ok。
请求合并的优点小伙伴们已经看到了,多个请求被合并为一个请求进行一次性处理,可以有效节省网络带宽和线程池资源,但是,有优点必然也有缺点,设置请求合并之后,本来一个请求可能5ms就搞定了,但是现在必须再等10ms看看还有没有其他的请求一起的,这样一个请求的耗时就从5ms增加到15ms了,不过,如果我们要发起的命令本身就是一个高延迟的命令,那么这个时候就可以使用请求合并了,因为这个时候时间窗的时间消耗就显得微不足道了,另外高并发也是请求合并的一个非常重要的场景。
请求合并的时间窗会带来额外开销,所以时候使用请求合并器需要根据依赖服务调用的实际情况,主要参考以下两个方面:
1.请求本身的延迟
2、延迟时间窗内的并发量