
前言
在高并發的場景下,前端會有大量的訪問請求。如果一個請求就需要打開一個數據庫連接,操作完數據庫后再進行關閉,無形中對數據造成很大的開銷。請求合并是將多個單個請求合并成一個請求,去調用服務提供者提供的服務接口,再遍歷合并的結果為每個合并前的單個請求設置返回結果。Spring Cloud通過Hystrix實現請求合并,減輕高并發時的請求線程消耗、降低請求響應時間的效果。今天就來聊一聊Hystrix請求合并的實現方式。
實現方式
由于是高并發場景,因此準備了SpringCloud微服務框架。準備了注冊中心、網關、服務提供者、服務消費者等組件。
導入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
啟動類上增加注解
@SpringBootApplication
@EnableHystrix
public class ServiceApplication {
public static void main(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")})
public Future<Item> get(String id) {
log.info("======執行了get方法========" + id);
return null;
}
//合并請求之后調用的方法
@HystrixCommand
public List<Item> mergeGet(List<String> ids) {
log.info("===合并開始===");
List<Item> items = ids.stream().map(
x -> {
Item item = new Item();
item.setId(Integer.valueOf(x));
item.setName("商品 :" + x);
return item;
}
).collect(Collectors.toList());
log.info("===合并結束,合并 {} 條 請求====", ids.size());
return items;
}
?說明:調用get方法,如果5s內get有多次調用,則合并后mergeGet方法。
controller調用代碼如下:
@RequestMapping(value = "/find/{id}")
public Item find(@PathVariable String id) throws InterruptedException, ExecutionException {
HystrixRequestContext context = HystrixRequestContext.initializeContext();
Future<Item> items = itemService.get(id);
System.out.println(items.get());
context.close();
return items.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:對一次請求的多次服務調用進行合并