Implement long polls asynchronously

Is it possible to remove the HTTPServletRequest from its stream, dissolve this stream (i.e. return it to the pool), but maintain a basic connection to the browser until I get the results from a lengthy operation (say, image processing)? When the returned data is processed, another method should be called asynchronously and receive a request, as well as data as parameters.

Usually, long pool functions are pretty nicely blocked when the current thread does not dissolve, which reduces the scalability of the server application in terms of simultaneous connections.

+5
source share
2 answers

, 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
                         }
                   }
        });
  }
}
+5

, spec ver. 3.0. , , - Jetty. . .

+2

All Articles