我在学习网上的一个秒杀项目,其中课程提到了"队列泄洪"的技术,我的理解是为了避免下单请求数过大而冲垮系统,可以通过一个线程池来减缓过大的流量。
它在处理下单请求的Controller方法里,创建了一个newFixedThreadPool,然后提交"减库存和发送事务消息"的任务给线程池。如下代码所示。
我不太理解这样做的用途,因为我觉得tomcat对每一个下单请求都封装成一个线程来执行此处的方法,也就是说,该方法是在一个请求里开启一个线程池来分配工作线程执行该请求的后续步骤,那么为什么可以达到限制请求数的目的?
//封装下单请求
@RequestMapping(value = "/createorder",method = {RequestMethod.POST},consumes={CONTENT_TYPE_FORMED})
@ResponseBody
public CommonReturnType createOrder(@RequestParam(name="itemId")Integer itemId,
@RequestParam(name="amount")Integer amount,
@RequestParam(name="promoId",required = false)Integer promoId,
@RequestParam(name="promoToken",required = false)String promoToken) throws BusinessException {
//交由线程池创建的线程来初始化库存流水并发送减库存事务消息
//在一台服务器上,同一时间内只有20个用户请求来下单,其他请求需要排队
Future<Object> future = executorService.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
//初始化库存流水,并获取其状态
String stockLogId = itemService.initStockLog(itemId, amount);
//完成下单事务消息机制
if(!mqProducer.transactionAsyncReduceStock(userModel.getId(), promoId, itemId, amount, stockLogId)) {
throw new BusinessException(EmBusinessError.UNKNOWN_ERROR, "下单失败");
}
return null;
}
});
try {
future.get();
} catch (InterruptedException e) {
throw new BusinessException(EmBusinessError.UNKNOWN_ERROR);
} catch (ExecutionException e) {
throw new BusinessException(EmBusinessError.UNKNOWN_ERROR);
}
return CommonReturnType.create(null);
}