Spring MVC 的异步模式

Elim 2016-11-18

浏览器发起请求,Web服务器会开一个线程处理,该线程会等待处理结果,自身处于阻塞状态,处理完把处理结果返回浏览器。但是,因为请求处理线程的总数是有限的,如果类似的请求多了,所有的处理线程处于阻塞的状态,那新的请求也就无法处理了,也就所谓影响了服务器的吞吐能力。要更加好地发挥服务器的全部性能,就要使用异步。

异步请求最大的不同在于请求处理线程调用了之后直接返回,而不等待,这样请求处理线程就“自由”了,它可以接着去处理别的请求,当后端处理完成后,会钩起一个回调处理线程来处理调用的结果,这个回调处理线程跟请求处理线程也许都是线程池中的某个线程,相互间可以完全没有关系,由这个回调处理线程向浏览器返回内容。这就是异步的过程。

Spring MVC的使用 -- DefferedResult

要使用Spring MVC的异步功能,你得先确保你用的是Servlet 3.0或以上的版本

<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
</dependency>
<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.3.RELEASE</version>
</dependency>

传统的同步模式的Controller是返回ModelAndView,而异步模式则是返回DeferredResult<ModelAndView>。

@RequestMapping(value="/asynctask", method = RequestMethod.GET)
public DeferredResult<ModelAndView> asyncTask(){
    DeferredResult<ModelAndView> deferredResult = new DeferredResult<ModelAndView>();
    System.out.println("/asynctask 调用!thread id is : " + Thread.currentThread().getId());
    longTimeAsyncCallService.makeRemoteCallAndUnknownWhenFinish(
        new LongTermTaskCallback() {
            @Override
            public void callback(Object result) {
                System.out.println("异步调用执行完成, thread id is : " + 
                    Thread.currentThread().getId());
                ModelAndView mav = new ModelAndView("remotecalltask");
                mav.addObject("result", result);
                deferredResult.setResult(mav);
            }
        });
}

longTimeAsyncCallService是自定义的一个模拟长时间异步调用的服务类,调用之,立即返回,当它处理完成时,就钩起一个线程调用我们提供的回调函数。

public interface LongTermTaskCallback {
    void callback(Object result);
}

public class LongTimeAsyncCallService {
    private final int CorePoolSize = 4;
    private final int NeedSeconds = 3;
    private Random random = new Random();
    private ScheduledExecutorService scheduler = 
        Executors.newScheduledThreadPool(CorePoolSize);
    public void makeRemoteCallAndUnknownWhenFinish(LongTermTaskCallback callback){
        System.out.println("完成此任务需要 : " + NeedSeconds + " 秒");
        scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                callback.callback("长时间异步调用完成.");
            }
        }, "这是处理结果:)", TimeUnit.SECONDS);
    }
}

输出的结果是:

/asynctask 调用!thread id is : 46
完成此任务需要 : 3 秒
异步调用执行完成, thread id is : 47

由此可见返回结果的线程和请求处理线程不是同一线程。

返回DefferedResult<ModelAndView>并非唯一做法,还可以返回WebAsyncTask来实现“异步”,但略有不同,不同之处在于返回WebAsyncTask的话是不需要我们主动去调用Callback的

@RequestMapping(value="/longtimetask", method = RequestMethod.GET)
public WebAsyncTask longTimeTask(){
    System.out.println("/longtimetask被调用 thread id is : " + Thread.currentThread().getId());
    Callable<ModelAndView> callable = new Callable<ModelAndView>() {
        public ModelAndView call() throws Exception {
            Thread.sleep(3000); //假设是一些长时间任务
            ModelAndView mav = new ModelAndView("longtimetask");
            mav.addObject("result", "执行成功");
            System.out.println("执行成功 thread id is : " + Thread.currentThread().getId());
            return mav;
        }
    };
    return new WebAsyncTask(callable);
}

其核心是一个Callable<ModelAndView>,事实上,直接返回Callable<ModelAndView>都是可以的。

和前一个方案的差别在于这个Callable的call方法并不是我们直接调用的,而是在longTimeTask返回后,由Spring MVC用一个工作线程来调用,执行。

打印出来的结果:

/longtimetask被调用 thread id is : 56
执行成功 thread id is : 57

处理超时

WebAsyncTask方式

@RequestMapping(value="/longtimetask", method = RequestMethod.GET)
public WebAsyncTask longTimeTask(){
    System.out.println("/longtimetask被调用 thread id is : " + Thread.currentThread().getId());
    Callable<ModelAndView> callable = new Callable<ModelAndView>() {
        public ModelAndView call() throws Exception {
            Thread.sleep(3000); //假设是一些长时间任务
            ModelAndView mav = new ModelAndView("longtimetask");
            mav.addObject("result", "执行成功");
            System.out.println("执行成功 thread id is : " + Thread.currentThread().getId());
            return mav;
        }
    };
    
    
    WebAsyncTask asyncTask = new WebAsyncTask(2000, callable);
    asyncTask.onTimeout(
            new Callable<ModelAndView>() {
                public ModelAndView call() throws Exception {
                    ModelAndView mav = new ModelAndView("longtimetask");
                    mav.addObject("result", "执行超时");
                    System.out.println("执行超时 thread id is :" + 
                        Thread.currentThread().getId());
                    return mav;
                }
            }
    );
    return new WebAsyncTask(3000, callable);
}

DefferedResult方式

@RequestMapping(value = "/asynctask", method = RequestMethod.GET)
    public DeferredResult<ModelAndView> asyncTask() {
        DeferredResult<ModelAndView> deferredResult = 
            new DeferredResult<ModelAndView>(2000L);
        System.out.println("/asynctask 调用!thread id is : " + 
            Thread.currentThread().getId());
        longTimeAsyncCallService.makeRemoteCallAndUnknownWhenFinish(
            new LongTermTaskCallback() {
                @Override
                public void callback(Object result) {
                    System.out.println("异步调用执行完成, thread id is : " + 
                        Thread.currentThread().getId());
                    ModelAndView mav = new ModelAndView("remotecalltask");
                    mav.addObject("result", result);
                    deferredResult.setResult(mav);
                }
            });

        deferredResult.onTimeout(new Runnable() {
            @Override
            public void run() {
                System.out.println("异步调用执行超时!thread id is : " + 
                    Thread.currentThread().getId());
                ModelAndView mav = new ModelAndView("remotecalltask");
                mav.addObject("result", "异步调用执行超时");
                deferredResult.setResult(mav);
            }
        });

        return deferredResult;
    }

http://www.cnblogs.com/guogangj/p/5457959.html#3555455

相关推荐