gpt4 book ai didi

java - 以异步方式实现长轮询

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:10:56 24 4
gpt4 key购买 nike

是否可以将 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
}
}
});
}
}

关于java - 以异步方式实现长轮询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8081895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com