以异步方式实现长轮询

use*_*232 6 java spring multithreading servlets long-polling

是否有可能从其线程中取出HTTPServletRequest,解散此线程(即将其带回池中),但保持与浏览器的底层连接正常工作,直到我从耗时的操作中获得结果(例如,处理一个图像)?处理返回数据时,应异步调用另一个方法,并将请求和数据作为参数给出.

通常,长池功能以非常阻塞的方式运行,其中当前线程未解散,这在并发连接方面降低了服务器端应用程序的可伸缩性.

Ram*_*PVK 5

是的,您可以使用Servlet 3.0执行此操作

以下是每30秒写一次警报的示例(未测试).

@WebServlet(async =“true”)
public class AsyncServlet extends HttpServlet {

Timer timer = new Timer("ClientNotifier");

public void doGet(HttpServletRequest req, HttpServletResponse res) {

    AsyncContext aCtx = request.startAsync(req, res);
    // Suspend request for 30 Secs
    timer.schedule(new TimerTask(aCtx) {

        public void run() {
            try{
                  //read unread alerts count
                 int unreadAlertCount = alertManager.getUnreadAlerts(username); 
                  // write unread alerts count
    response.write(unreadAlertCount); 
             }
             catch(Exception e){
                 aCtx.complete();
             }
        }
    }, 30000);
}
}
Run Code Online (Sandbox Code Playgroud)

以下是基于事件编写的示例.必须实现alertManager,当必须提醒客户端时通知AlertNotificationHandler.

@WebServlet(async=“true”)
public class AsyncServlet extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) {
        final AsyncContext asyncCtx = request.startAsync(req, res);
        alertManager.register(new AlertNotificationHandler() {
                   public void onNewAlert() { // Notified on new alerts
                         try {
                               int unreadAlertCount =
                                      alertManager.getUnreadAlerts();
                               ServletResponse response = asyncCtx.getResponse();
                               writeResponse(response, unreadAlertCount);
                               // Write unread alerts count
                         } catch (Exception ex) {
                               asyncCtx.complete();
                               // Closes the response
                         }
                   }
        });
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果用户访问该页面,并且创建了异步对象,然后他们刷新页面会发生什么?是另一个创建的对象?现在两个请求会被送回去吗?或者如果他们离开页面怎么办?响应是否会被发送到外太空?对不起,我无法绕过这个! (2认同)

Vic*_*kin 2

是的,可以使用 Servlet 规范版本。3.0。我推荐的实现是 Jetty 服务器。看这里