当前位置: 首页 > 科技观察

SpringCloudHystrix实现高并发下的请求合并

时间:2023-03-14 22:11:07 科技观察

前言在高并发场景下,前端会有大量的访问请求。如果一个请求需要打开一个数据库连接,然后在对数据库进行操作后关闭,无形中会对数据造成很大的开销。请求合并就是将多个单独的请求合并为一个请求,调用服务提供者提供的服务接口,然后遍历合并后的结果,为每个单独的请求设置合并前的返回结果。SpringCloud通过Hystrix实现请求合并,减少高并发时请求线程的消耗,降低请求响应时间的影响。今天就来说说Hystrix请求合并的实现。实现方式是高并发场景,所以准备了SpringCloud微服务框架。准备了注册中心、网关、服务提供者、服务消费者等组件。导入依赖org.springframework.cloudspring-cloud-starter-netflix-hystrix启动类添加注解@SpringBootApplication@EnableHystrixpublicclassServiceApplication{publicstaticvoidmain(String[]args){SpringApplication.run(ServiceApplication.class,args);}}实现请求合并,Service中的代码如下://请求合并的方法在5s内合并请求@HystrixCollapser(batchMethod="mergeGet",scope=com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL,collapserProperties={@HystrixProperty(name="timerDelayInMilliseconds",value="5000")})publicFutureget(Stringid){log.info("======执行了get方法========"+编号);returnnull;}//合并请求后调用的方法@HystrixCommandpublicListmergeGet(Listids){log.info("===mergestart===");列表items=ids.stream().map(x->{Itemitem=newItem();item.setId(Integer.valueOf(x));item.setName("商品:"+x);归还物品;}).collect(Collectors.toList());log.info("===mergeend,merge{}requests====",ids.size());returnitems;}描述:调用get方法。如果5s内有多次调用获取,mergeGet方法controller合并后调用代码如下:@RequestMapping(value="/find/{id}")publicItemfind(@PathVariableStringid)throwsInterruptedException,ExecutionException{HystrixRequestContextcontext=HystrixRequestContext.initializeContext();未来items=itemService.get(id);System.out.println(items.get());上下文.close();returnitems.get();}同时执行127.0.0.1:8080/find/11和127.0.0.1:8080/find/22,保证两个请求在5s内发出。返回结果说明:scope=com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL:合并所有线程中的多个服务调用scope=com.netflix.hystrix.HystrixCollapser.Scope.REQUEST:一个请求合并多个服务调用