use*_*232 6 java spring multithreading servlets long-polling
是否有可能从其线程中取出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);
}
}
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)
| 归档时间: |
|
| 查看次数: |
8568 次 |
| 最近记录: |