秒杀项目里的队列泄洪

我在学习一个秒杀项目,课程提到队列泄洪的技术。我的理解是为了避免请求数过大而冲垮系统,通过一个线程池来减缓过大的流量。

    //封装下单请求
    @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);
    }

但是按照我对多线程的理解,tomcat为每一个web请求产生一个线程,这个线程执行web程序,那么为什么要在一个请求里通过线程池来新建线程,处理一个请求的后续步骤?这样能达到限制请求数的效果吗?

阅读 3.2k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题