zoukankan      html  css  js  c++  java
  • Servlet 3中的异步处理

    有人可能会质疑,既然都有多线程了,还需要异步处理请求吗?答案是肯定的,因为如果一个任务处理时间相当长,那么Servlet或Filter会一直占用着请求处理线程直到任务结束,随着并发用户的增加,容器将会遭遇线程超出的风险,这这种情况下很多的请求将会被堆积起来而后续的请求可能会遭遇拒绝服务,直到有资源可以处理请求为止。异步特性可以帮助应用节省容器中的线程,特别适合执行时间长而且用户需要得到结果的任务,如果用户不需要得到结果则直接将一个Runnable对象交给Executor并立即返回即可

    import
    java.io.IOException;
     import javax.servlet.AsyncContext;
     import javax.servlet.ServletException;
     import javax.servlet.annotation.WebServlet;
     import javax.servlet.http.HttpServlet;
     import javax.servlet.http.HttpServletRequest;
     import javax.servlet.http.HttpServletResponse;
     @WebServlet(urlPatterns = {"/async"}, asyncSupported = true)
     public class AsyncServlet extends HttpServlet {
         private static final long serialVersionUID = 1L;
         @Override
         public void doGet(HttpServletRequest req,
    HttpServletResponse resp)
                 throws
    ServletException, IOException {
             // 开启Tomcat异步Servlet支持
             
    req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED"true);
             final AsyncContext ctx =
    req.startAsync();  // 启动异步处理的上下文
             // ctx.setTimeout(30000);
             ctx.start(new Runnable() {
                 @Override
                 public void
    run() {
                     
    // 在此处添加异步处理的代码
                     
    ctx.complete();
                 }
             });
         }
     }
     
  • 相关阅读:
    centos8重置root密码
    Mysql查询某列最长字符串记录
    ssm连接mysql出现Connections could not be acquired from the underlying database 问题
    spring-基于xml配置Bean
    WinForm控件命名缩写
    SQL Server 将一张表的某个字段更新到另一张表中
    SQL Server 取出指定字符后字符串(用于分割)
    小白学CMD下运行MySQL
    Bootstrap3.0和bootstrap2.x的区别
    有关js弹出提示框几种方法
  • 原文地址:https://www.cnblogs.com/xp0813/p/11032852.html
Copyright © 2011-2022 走看看