SpringMVC配置使用servlet3.0异步请求AsyncContext示例

小郝不负流年
小郝不负流年   + 关注
2021-02-10 12:55:30   阅读941   评论0

介绍

  • 为了支持异步处理,在Servlet 3.0中,在ServletRequest上提供了startAsync()方法

配置

SpringMVC支持异步配置


  1. springmvc-servlet.xml:    
  2. <mvc:annotation-driven>    
  3.     <mvc:async-support default-timeout="5000"/>    
  4. mvc:annotation-driven>    
  5.     
  6. web.xml的所有servlet和filter    
  7. <async-supported>trueasync-supported>   


示例


  1. @Controller  
  2. @RequestMapping("/test")  
  3. public class AsyncTestController extends BaseController {  
  4.   
  5.     @RequestMapping(value = "/async", method = RequestMethod.GET)  
  6.     public void testAsync(HttpServletRequest request, HttpServletResponse response) throws IOException {  
  7.         LOGGER.info("=== 开始");  
  8.         PrintWriter out = response.getWriter();  
  9.         AsyncContext asyncContext = request.startAsync();  
  10.         asyncContext.setTimeout(5000L); // 设置0表示永不超时  
  11.         asyncContext.addListener(new TestAsyncListener());  
  12.         new Thread(new WorkThread(asyncContext)).start();  
  13.         LOGGER.info("=== 异步进行中");  
  14.         out.println("async exce...");  
  15.     }  
  16.   
  17. }  
  18.   
  19.   
  20.   
  21. public class WorkThread implements Runnable {  
  22.   
  23.     private AsyncContext asyncContext;  
  24.   
  25.     public WorkThread(AsyncContext asyncContext) {  
  26.         this.asyncContext = asyncContext;  
  27.     }  
  28.   
  29.     @Override  
  30.     public void run() {  
  31.         try {  
  32.             Thread.sleep(6000);  
  33.             try {  
  34.                 ServletResponse response = asyncContext.getResponse();  
  35.                 PrintWriter out = response.getWriter();  
  36.                 out.println("work thread excute is finished!");  
  37. //                    out.close(); // 可以放到listener.onComplete里面关闭  
  38.             } catch (IOException e) {  
  39.                 e.printStackTrace();  
  40.             }  
  41.             asyncContext.complete();  
  42.         } catch (InterruptedException e) {  
  43.             e.printStackTrace();  
  44.         }  
  45.     }  
  46.   
  47. }  
  48.   
  49.   
  50.   
  51. public class TestAsyncListener implements AsyncListener {  
  52.     @Override  
  53.     public void onComplete(AsyncEvent asyncEvent) throws IOException {  
  54.         try {  
  55.             AsyncContext asyncContext = asyncEvent.getAsyncContext();  
  56.             ServletResponse response = asyncContext.getResponse();  
  57.             ServletRequest request = asyncContext.getRequest();  
  58.             PrintWriter out= response.getWriter();  
  59.             if (request.getAttribute("timeout") != null &&  
  60.                     StringUtil.equals("true",request.getAttribute("timeout").toString())) {//超时  
  61.                 out.println("onComplete timeout ");  
  62.                 LOGGER.info("onComplete timeout");  
  63.             }else {//未超时  
  64.                 out.println("OnComplete normal");  
  65.                 LOGGER.info("OnComplete normal");  
  66.             }  
  67.             out.close();  
  68.         } catch (IOException e) {  
  69.             e.printStackTrace();  
  70.         }  
  71.     }  
  72.   
  73.     @Override  
  74.     public void onError(AsyncEvent asyncEvent) throws IOException {  
  75.         LOGGER.info("=== onError");  
  76.     }  
  77.   
  78.     @Override  
  79.     public void onStartAsync(AsyncEvent arg0) throws IOException {  
  80.         LOGGER.info("=== onStartAsync");  
  81.     }  
  82.   
  83.     @Override  
  84.     public void onTimeout(AsyncEvent asyncEvent) throws IOException {  
  85.         ServletRequest request = asyncEvent.getAsyncContext().getRequest();  
  86.         request.setAttribute("timeout""true");  
  87.         LOGGER.info("=== onTimeout");  
  88.     }  
  89. }  

总结

Listener.onComplete方法永远都会执行;

Listener.onTimeout方法在超时时才会执行。

其他的东西可以复制demo自己跑一下看一下就明白了。

对我有用,我要     转载  
文章分类: JavaWeb  
所属标签: SpringMVC   Servlet   异步   AsyncContext  
  • 0条评论
  • 只看作者
  • 按时间|按热度
  • 由于本人多次涉及需要打印这个证明,而每次都会忘记入口,在网上各种搜索各种摸索很是浪费时间。故本次将操作流程整理记录下来,以备忘。同时也分享给大家。1、打开湖北政务服务网,地址:http://zwfw.hubei.gov.cn/s/index.html2、切换区域到“武汉市”3、在“特色服务”模块找到“(个人)武汉市社会保险公共服务平台”4、进入“(个人)武汉市社会保险公共服务平台”,登录账号密码<imgsrc="https://cdnstatic.hoscen.cn/blog/article/184053017752895488/img/497065960be44747825acb86a17483c1.png"style=
  • 如何使用postman模拟http发送xml参数报文的POST请求?1、postman工具通过安装软件或使用谷歌插件都可以,这里不再赘述。2、配置postman,选择POST,填写URL;切换到Headers,添加Content-Type:text/xml 3、切换到body,选择raw,XML,下方填写你的请求报文4、点击Send发送请求,如图可以看到响应状态、时间、结果等信息5、讲到这里就结束了,是不是学会了?快去试试吧!
  • java中的注解@Generated用来标注源代码中的某些东西是由某些工具生成的,而不是人写的。这个注解可以用于:包、类、注解类、方法、构造方法、变量、本地变量、方法参数。
  • 解决办法:是idea的加载有问题,关闭IDEA,在工程的根目录下删除.idea文件,重新打开IDEA加载就好了。
  • Failedtoloadprojectconfiguration:cannotparsefileF:/xx/.idea/modules.xml:ParseErrorat[row,col]:[1,1]Message:文件提前结束。解决办法:关闭idea,删掉这个文件,重新打开idea
  • 目录:1、安装node.js环境2、安装cnpm3、安装vue-cli脚手架构建工具4、用vue-cli构建项目5、安装项目所需的依赖6、项目运行7、项目打包1、安装node.js环境下载地址:https://nodejs.org/zh-cn/安装过程没有太多好说的,安装完成后 win+R打开命令行输入node -v , 如图,出现版本号说明安装成功。npm包管理器是集成在node中的 , npm -v可以查看版本2、安装cnpm由于有些npm有些资源被屏蔽或者是国外资源的原因,经常会导致用npm安装依赖包的时
  • 建立服务器内网其他IP端口的隧道,可以将远程的服务映射到本地进行访问。finalshell配置隧道方法:
  • 上传图片微服务网关报错:UT000054:Themaximumsize1048576foranindividualfileinamultipartrequestwasexceeded原因:所用容器对文件的限制一般项目用的是spring 对spring参数进行配置即可spring:servlet:multipart:#MultipartPropertiesmax-request-size:10MB#总文件大小max-file-size:10MB#单个文件大小注意如果是nginx代理配置限制,报错信息里面会标记nginx。届时需要设置nginx在server_name下加上client_max_body_size20m;
  • Idea启动报PluginError错误解决方法:找到IDEA的配置文件夹下的disabled_plugins.txt,删除然后重启IDEA即可。错误描述    PluginError    Problemsfoundloadingplugins:    Plugin"GlassFishIntegration"wasnotloaded:requiredplugin"JavaEE:EJB,JPA,Servlets"isdisabled.    Plugin"JBossjBPM"wasnotloaded:requiredplugin"JavaEE:EJB,JPA,Servlets"isdisabled.    Plugin"JBossIntegration"wasnotloaded:requiredplugin"JavaEE:EJB,JPA,Servlets"isdisabled.    Plugin"JSR45Integration"wasnotloaded:requiredplugin"JavaEE:EJB,JPA,Servlets"isdisabled.    Plugin"JettyIntegration"wasnotloaded:requiredplugin"JavaEE:EJB,JPA,Servlets"isdisabled.    Plugin"ResinIntegration"wasnotloaded:requiredplugin"JavaEE:EJB,JPA,Servlets"isdisabled.    Plugin"TomcatandTomEEIntegration"wasnotloaded:requiredplugin"JavaEE:EJB,JPA,Servlets"isdisabled.    Plugin"CloudBeesintegration
  • 很多时候我们需要Linux服务器定时去运行一个脚本来触发一个操作,比如写缓存数据到硬盘、定时备份、定时重启服务、定期清除日志等。下面就简单讲解一下Linuxcrontab命令如何实现自动循环执行shell脚本。一、准备shell脚本比如我们准备一个hello.shvim/hcn/sh/hello.sh#!/bin/bash  DATETIME=$(date"+%Y%m%d%H%M%S") echo"hello, www.hoscen.cn,时间:${DATETIME}"  通过chmod命令赋予该脚本的执行权限chmod755hello.sh测试正确性二、开启crontab服务 linux应该都有crontab,没有的话可以安装一下:yuminstall vixie-cronyuminstall crontabsvixie-cron软