【发布时间】:2017-10-10 07:49:12
【问题描述】:
我正在尝试制作系统,它接受请求,对它们进行一些操作(对相同的请求进行分组等),然后延迟 1-2 秒发送响应。
所以我尝试使用 AsyncContext 来防止立即发送响应并在我需要时发送它们。
但是当我使用 AsyncContext 时,它会阻止下一个响应,而第一个响应尚未完成。 对于测试,我一次发送 3 个 ajax get 请求。
因此,我的代码不是处理 3 个未完成的请求,而是等待第一个请求完成,然后处理第二个请求,而第三个等待第二个请求完成。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("GET " + new Date().toString());
if(!request.getRequestURL().toString().contains("localhost")) {
try {
AsyncContext context = request.startAsync();
context.start(new Runnable() {
@Override
public void run () {
try {
prepare(request, response);
addToPool(request, response, context);
System.out.println("fin GET " + new Date().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
在日志中是这样的:
GET Tue Oct 10 10:16:25
Try combine: false
Req added to waitlist
fin GET Tue Oct 10 10:16:25
Completed
GET Tue Oct 10 10:16:30
Try combine: false
Req added to waitlist
fin GET Tue Oct 10 10:16:30
Completed
GET Tue Oct 10 10:16:35
Try combine: false
Req added to waitlist
fin GET Tue Oct 10 10:16:35
Completed
AsyncContext 应该这样做还是我做错了什么?
附: 我尝试在没有“context.start(new Runnable() {...”的情况下使用 AsyncContext 并且得到相同的结果。
更新 - JS 代码。我在按钮点击事件上调用 multiReq。
function multiReq() {
getCurrAcc();
getCurrAcc();
getCurrAcc();
}
function getCurrAcc() {
$.ajax({
type: "GET",
contentType: 'application/json',
url: "http://new59d2023b5d1a4.amocrm.ru.myhost.localarea.local/private/api/v2/json/accounts/current",
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(JSON.stringify(data));
},
error: function (request, status, error) {
alert(JSON.stringify(request));
}
});
}
【问题讨论】:
-
请出示相关部分的javascript
-
可怕的袋熊,完成