[英]When to push data with Server-sent Events
当新记录添加到数据库时,我想流式传输数据。 现在,我正在每10秒为连接的每个用户查询db以获取新记录。 有什么更好的方法吗? 我觉得我应该在插入新记录后以某种方式引发事件,并以某种方式访问相关用户的请求并为用户流。
(为了简化说明,我简化了代码。因此,可能无法完全正常工作。)
router.get("/event", (req, res, next) => {
let userId = getUserIdFromRequest(req);
getData(userId, (err, data) => {
let stream = res.push("/notification/new");
stream.end(JSON.stringify(data));
res.write("data:/notification/new\n\n");
res.flush();
});
});
getData(userId, callback) {
model.find( {where: { and: [{ "userId": userId }, { "notified": false }] }}, (err, data =>) {
callback(null , data);
setTimeout(function () { getData(callback); }, 10000);
if (data) {
setDataAsNotified(data); // makes notified: true
}
})
}
前端:
let source = new EventSource("/route/notification/event")
source.onmessage = (event) => {
// display notification
}
数据库查询:由于您没有提供如何在基础中输入数据,因此有两个线索:
如果您可以修改插入数据的代码,则使其通过WebSockets(或根据需要通过HTTP,将这些数据发送到后端,但WebSocket更快)并更新记录数据库(或新连接的用户)
如果不能,那么这里是一个链接: 如何收听对MongoDB集合的更改?
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.