簡體   English   中英

以異步方式實現長輪詢

[英]Implementing long polling in an asynchronous fashion

是否有可能從其線程中取出HTTPServletRequest,解散此線程(即將其帶回池中),但保持與瀏覽器的底層連接正常工作,直到我從耗時的操作中獲得結果(例如,處理一個圖像)? 處理返回數據時,應異步調用另一個方法,並將請求和數據作為參數給出。

通常,長池功能以非常阻塞的方式運行,其中當前線程未解散,這在並發連接方面降低了服務器端應用程序的可伸縮性。

是的,您可以使用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);
}
}

以下是基於事件編寫的示例。 必須實現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
                         }
                   }
        });
  }
}

是的,可以使用Servlet規范。 3.0。 我可以推薦的實現是Jetty服務器。 看到這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM