0

当我的请求到达我的控制器时,executorService 创建一个线程池并创建一些线程来执行一些逻辑,我的请求返回到浏览器。我的问题从这里开始,在服务器端运行的线程需要会话对象,线程获取会话为空。响应返回客户端后我使用什么方法设置会话值。下面是代码,请给出一些合适的解决方案,以便我可以在请求完成后获取会话值。

@RequestMapping(value = "/expandAllController", method = RequestMethod.POST) public @ResponseBody void expandAllController(@RequestParam final String[] controllerList,final HttpServletRequest request) {

     int listSize=controllerList.length;
     BlockingQueue controllerDataQueue=cacheUtility.initBlockingQueue(listSize);
     ExecutorService executor=Executors.newCachedThreadPool();
     for(String controllerID:controllerList){
     executor.submit(new producer(controllerID,request,controllerDataQueue));
     }
     executor.shutdown();
     try {
        executor.awaitTermination(10, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

     // data fetching Thread 


}

private class producer implements Runnable{

    Object responseObj=null;
    String controllerID;
    HttpServletRequest request;
    BlockingQueue controllerDataQueue;
          producer(String controllerID ,HttpServletRequest request, BlockingQueue controllerDataQueue ){
              this.controllerDataQueue=controllerDataQueue;
              this.controllerID=controllerID;
              this.request=request;
          }
         @Override
            public void run() {
                int ThreadCount=0;
                final HttpSession session = request.getSession();
    final CommonSettings commonSettings = CommonSettings
            .getInstance(session);
                    // for(String controllerID:controllerList){
                         controllerData.setControllerId(controllerID);

                         responseObj=expandController(controllerData,session);
                         if(responseObj!=null){
                             try {
                                controllerDataQueue.put(responseObj);

                                ThreadCount++;
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                         }

                     }
                }
4

1 回答 1

0

直接从控制器方法在会话中存储一个空容器(例如同步集或列表),然后将此容器传递给每个任务,并使任务将其响应添加到容器中。

此外,请考虑始终重用相同的线程池。总是开始一个新的资源是浪费资源。如果有太多的请求进来,你就会有太多的线程并行运行,这正是线程池用来避免的。

于 2013-07-18T11:21:23.920 回答