一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第26天,点击查看活动详情
HystrixCollapser
| 属性 | 含义 |
|---|---|
| collapserKey | 唯一标识 |
| batchMethod | 请求合并处理方法。即合并后需要调用的方法 |
| scope | 作用域;两种方式[REQUEST, GLOBAL] ; REQUEST : 在同一个用户请求中达到条件将会合并 GLOBAL : 任何线程的请求都会加入到这个全局统计中 |
| HystrixProperty[] | 配置相关参数 |
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HystrixCollapser {
String collapserKey() default "";
String batchMethod();
Scope scope() default Scope.REQUEST;
HystrixProperty[] collapserProperties() default {};
}
@HystrixCollapser(
scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL,
batchMethod = "getIds",
collapserProperties = {
@HystrixProperty(name = HystrixPropertiesManager.MAX_REQUESTS_IN_BATCH, value = "3"),
@HystrixProperty(name =HystrixPropertiesManager.TIMER_DELAY_IN_MILLISECONDS, value = "10")
}
)
@RequestMapping(value = "/getId", method = RequestMethod.GET)
public ResultInfo getId(@RequestParam Long id) {
if (id < 0) {
int i = 1 / 0;
}
log.info(Thread.currentThread().getName());
return null;
}
@HystrixCommand
public List<ResultInfo> getIds(List<Long> ids) {
System.out.println(ids.size()+"@@@@@@@@@");
return orderPaymentService.getIds(ids);
}
-
上面我们配置了getId会走getIds请求,最多是10S三个请求会合并在一起。然后getIds有payment服务在分别去查询最终返回多个ResultInfo。
-
在Hystrix中所有的properties配置都会在HystrixPropertiesManager.java中。我们在里面可以找到Collapser只有两个相关的配置。分别表示最大请求数和统计时间单元。
请求合并
- 除了熔断、降级、限流意外hystrix还为我们提供了请求合并。顾名思义就是将多个请求合并成一个请求已达到降低并发的问题。
- 比如说我们order有个接个是查询当个订单信息
order/getId?id=1突然有一万个请求过来。为了缓解压力我们集中一下请求每100个请求调用一次order/getIds?ids=xxxxx。这样我们最终到payment模块则是10000/100=100个请求。下面我们通过代码配置实现下请求合并。
- 我们通过jemeter进行getId接口压测,日志中ids的长度最大是3 。 验证了我们上面getId接口的配置。这样就能保证在出现高并发的时候会进行接口合并降低TPS。
- 上面我们是通过请求方法注解进行接口合并处理。实际上内部hystrix是通过HystrixCommand