【发布时间】:2016-06-20 16:42:26
【问题描述】:
我正在构建一个具有推送通知功能并使用 Jersey 创建 API 的系统。
我阅读了关于彗星方法的 article 并最终得到以下代码:
Index.js
function checkExamNotification() {
$.ajax({
url: contextPath + '/api/notification/checkExamNotification',
type: 'get',
data: {
accountId: accountId,
sessionId: sessionId
},
success: function (res) {
console.log("success");
displayNumberOfNotification();
checkExamNotification();
},
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus === "timeout") {
checkExamNotification();
}
}
});
}
$(document).ready(function () {
$.ajaxSetup({
timeout: 1000*60*3
});
checkExamNotification();
});
检查考试通知 API
@GET
@Path("/checkExamNotification")
public Response checkExamNotification(@QueryParam("accountId") int accountId, @QueryParam("sessionId") String sessionId) throws InterruptedException {
if (memCachedClient.checkSession(sessionId, accountId)) {
while (!examNotificationQueue.hasItems()) {
Thread.sleep(5000);
}
ExamNotificationQueueItemModel examNotificationQueueItemModel = examNotificationQueue.dequeue();
if (examNotificationQueueItemModel.getAccountId() == accountId) {
LOGGER.info("[START] Check exam notification API");
LOGGER.info("Account ID: " + accountId);
LOGGER.info("Get notification with exam ID: " + examNotificationQueueItemModel.getExamId());
ExamEntity exam = examDAO.findById(examNotificationQueueItemModel.getExamId());
NotificationEntity notification = notificationDAO.findByExamId(exam.getExamid());
notification.setSend(1);
notificationDAO.getEntityManager().getTransaction().begin();
notificationDAO.update(notification);
notificationDAO.getEntityManager().getTransaction().commit();
LOGGER.info("[END]");
String result = gson.toJson(examNotificationQueueItemModel);
return Response.status(200).entity(result).build();
} else {
examNotificationQueue.enqueue(examNotificationQueueItemModel);
Thread.sleep(5000);
checkExamNotification(accountId, sessionId);
}
}
return Response.status(200).entity(gson.toJson("timeout")).build();
}
根据我的调试,API 确实完成返回,但成功事件 SOMETIMES 没有触发。
是的,有时控制台日志成功,但有时却没有。
谁能给我解释一下这个案例?
提前致谢。任何帮助将不胜感激。
【问题讨论】:
-
我不明白这是如何推动的。您应该查看球衣对多个已发送事件 (SSE) 的支持。这使用了真正的推送。
-
抱歉回复晚了。我会试试你的方法。但是你能解释一下为什么它没有正确返回响应吗?
标签: java jquery ajax jersey comet