在spring mvc3.2及以上版本增加了对请求的异步处理,是在servlet3的基础上进行封装的。

1、修改web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  5. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  6. ...
  7. </web-app>

1.1、声明version="3.0",声明web-app_3_0.xsd

1.2、为servlet或者filter设置启用异步支持:<async-supported>true</async-supported>,修改WEB应用的web.xml

  1. <!-- spring mvc -->
  2. <servlet>
  3. <servlet-name>SpringMvc</servlet-name>
  4. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  5. <init-param>
  6. <param-name>contextConfigLocation</param-name>
  7. <param-value>...</param-value>
  8. </init-param>
  9. <load-on-startup>1</load-on-startup>
  10. <async-supported>true</async-supported>
  11. </servlet>

2、使controller类支持async

2.1、返回java.util.concurrent.Callable来完成异步处理

  1. package org.springframework.samples.mvc.async;
  2.  
  3. import java.util.concurrent.Callable;
  4.  
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.ui.Model;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestParam;
  10. import org.springframework.web.bind.annotation.ResponseBody;
  11. import org.springframework.web.context.request.async.WebAsyncTask;
  12.  
  13. @Controller
  14. @RequestMapping("/async/callable")
  15. public class CallableController {
  16. @RequestMapping("/response-body")
  17. public @ResponseBody Callable<String> callable() {
  18.  
  19. return new Callable<String>() {
  20. @Override
  21. public String call() throws Exception {
  22. Thread.sleep(2000);
  23. return "Callable result";
  24. }
  25. };
  26. }
  27.  
  28. @RequestMapping("/view")
  29. public Callable<String> callableWithView(final Model model) {
  30.  
  31. return new Callable<String>() {
  32. @Override
  33. public String call() throws Exception {
  34. Thread.sleep(2000);
  35. model.addAttribute("foo", "bar");
  36. model.addAttribute("fruit", "apple");
  37. return "views/html";
  38. }
  39. };
  40. }
  41.  
  42. @RequestMapping("/exception")
  43. public @ResponseBody Callable<String> callableWithException(
  44. final @RequestParam(required=false, defaultValue="true") boolean handled) {
  45.  
  46. return new Callable<String>() {
  47. @Override
  48. public String call() throws Exception {
  49. Thread.sleep(2000);
  50. if (handled) {
  51. // see handleException method further below
  52. throw new IllegalStateException("Callable error");
  53. }
  54. else {
  55. throw new IllegalArgumentException("Callable error");
  56. }
  57. }
  58. };
  59. }
  60.  
  61. @RequestMapping("/custom-timeout-handling")
  62. public @ResponseBody WebAsyncTask<String> callableWithCustomTimeoutHandling() {
  63.  
  64. Callable<String> callable = new Callable<String>() {
  65. @Override
  66. public String call() throws Exception {
  67. Thread.sleep(2000);
  68. return "Callable result";
  69. }
  70. };
  71.  
  72. return new WebAsyncTask<String>(1000, callable);
  73. }
  74.  
  75. @ExceptionHandler
  76. @ResponseBody
  77. public String handleException(IllegalStateException ex) {
  78. return "Handled exception: " + ex.getMessage();
  79. }
  80.  
  81. }

2.2、在异步处理完成时返回org.springframework.web.context.request.async.DeferredResult其他线程,例如一个JMS或一个AMQP消息,Redis通知等等:

  1. @RequestMapping("/quotes")
  2. @ResponseBody
  3. public DeferredResult<String> quotes() {
  4. DeferredResult<String> deferredResult = new DeferredResult<String>();
  5. // Add deferredResult to a Queue or a Map...
  6. return deferredResult;
  7. }
  8.  
  9. // In some other thread...
  10. deferredResult.setResult(data);
  11. // Remove deferredResult from the Queue or Map

3、spring配置文件的修改

spring mvc的dtd的声明必须大于等于3.2

  1. <mvc:annotation-driven>
  2. <!-- 可不设置,使用默认的超时时间 -->
  3. <mvc:async-support default-timeout="3000"/>
  4. </mvc:annotation-driven>

实际使用示例:

  1. function deferred(){
  2. $.get('quotes.htm',function(data){
  3. console.log(data);
  4. deferred();//每次请求完成,再发一次请求,避免客户端定时刷新来获取数据
  5. });
  6. }

这么做的好处避免web server的连接池被长期占用而引起性能问题,调用后生成一个非web的服务线程来处理,增加web服务器的吞吐量~~

可以看下这个blog,还不错:http://wiselyman.iteye.com/blog/2215852

spring mvc对异步请求的处理的更多相关文章

  1. 高性能的关键:Spring MVC的异步模式

    我承认有些标题党了,不过话说这样其实也没错,关于“异步”处理的文章已经不少,代码例子也能找到很多,但我还是打算发表这篇我写了好长一段时间,却一直没发表的文章,以一个更简单的视角,把异步模式讲清楚. 什 ...

  2. Spring MVC的异步模式

    高性能的关键:Spring MVC的异步模式   我承认有些标题党了,不过话说这样其实也没错,关于“异步”处理的文章已经不少,代码例子也能找到很多,但我还是打算发表这篇我写了好长一段时间,却一直没发表 ...

  3. Spring MVC的异步模式DefferedResult

    原文:http://www.importnew.com/21051.html 什么是异步模式 要知道什么是异步模式,就先要知道什么是同步模式,先看最典型的同步模式: (图1) 浏览器发起请求,Web服 ...

  4. Spring MVC中forward请求转发2种方式(带参数)

    Spring MVC中forward请求转发2种方式(带参数) http://www.51gjie.com/javaweb/956.html  

  5. spring mvc 文件下载 get请求解决中文乱码问题

    方案简写,自己或有些基础的可以看懂,因为没时间写的那么详细 方案1 spring mvc解决get请求中文乱码问题, 在tamcat中server.xml文件 URIEncoding="UT ...

  6. Spring MVC的映射请求

    一.SpringMVC常用注解 @Controller 声明Action组件 @Service    声明Service组件    @Service("myMovieLister" ...

  7. Spring mvc 启动 和 请求分发

    Spring mvc 启动 和 请求分发 启动加载: abstract class HttpServletBean extends HttpServlet void init() initServle ...

  8. Spring MVC 处理一个请求的流程分析

    Spring MVC是Spring系列框架中使用频率最高的部分.不管是Spring Boot还是传统的Spring项目,只要是Web项目都会使用到Spring MVC部分.因此程序员一定要熟练掌握MV ...

  9. spring mvc ajax异步文件的上传和普通文件上传

    表单提交方式文件上传和ajax异步文件上传 一:首先是我在spring mvc下的表单提交方式上传 ssm的包配置我就不一一详细列出来了,但是上传的包我还是列出来 这一段我也不知道怎么给大家讲解就是直 ...

随机推荐

  1. Rete算法

    RETE算法介绍一. rete概述Rete算法是一种前向规则快速匹配算法,其匹配速度与规则数目无关.Rete是拉丁文,对应英文是net,也就是网络.Rete算法通过形成一个rete网络进行模式匹配,利 ...

  2. Unity3d-Particle System 5.x系统的学习(四)

    Unity3d-Particle System 5.x系统的学习(四) 今天,我们来聊聊unity5.x的粒子系统和unity4.x粒子系统的区别. 我大致看了下,区别还是蛮多的,但是总体的粒子制作思 ...

  3. 文件操作篇 close creat dup dup2 fcntl flock fsync lseek mkstemp open read sync write

    文件操作篇 close creat dup dup2 fcntl flock fsync lseek mkstemp open read sync write close(关闭文件) 相关函数 ope ...

  4. 【BZOJ】【2946】【POI2000】公共串

    后缀数组 好感动,复习了下后缀数组居然写出来了……(感谢ykz大神) 求最长公共子串……WA了一发是因为:[不同字符串之间要用不同的特殊字符隔开]否则就会匹配到相同→_→比如都是aaa结尾,如果用相同 ...

  5. An easier way to debug windows services

    Have you got tired of attaching the Visual Studio debugger to the service application? I got the sol ...

  6. ILMerge-GUI的使用

    去这里下载: 这里下载ILMerge,http://www.microsoft.com/en-us/download/details.aspx?id=17630 这里下载ILMerge-GUI,htt ...

  7. jQuery实现新浪微博自动底部加载的方法

    jQuery ScrollPagination plugin 是一个jQuery 实现的支持无限滚动加载数据的插件. 地址:http://andersonferminiano.com/jquerysc ...

  8. SQL基础(四):SQL命令

    1.CREATE INDEX 语句 CREATE INDEX 语句用于在表中创建索引.在不读取整个表的情况下,索引使数据库应用程序可以更快地查找数据. 索引:在表中创建索引,以便更加快速高效地查询数据 ...

  9. android 下的网络图片加载

    Android图片的异步加载,主要原理: 加载图片时先查看缓存中时候存在该图片,如果存在则返回该图片,否则先加载载一个默认的占位图片,同时创建一个通过网络获取图片的任务并添加,任务完成后放松消息给主线 ...

  10. Splunk的安装与使用

    一.简单介绍         Splunk 是机器数据的引擎.使用 Splunk 可收集.索引和利用全部应用程序.server和设备(物理.虚拟和云中)生成的高速移动型计算机数据 .从一个位置搜索并分 ...