我想在将新记录添加到数据库时流式传输数据。现在,我每 10 秒为每个连接的用户查询数据库一次新记录。有更好的方法吗?我觉得我应该在插入新记录后引发事件,并以某种方式访问相关用户的请求和用户流。
(我简化了我的代码以使要点清晰。所以,它可能无法完全正常工作。)
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 。这样数据通过 TCP 而不是 HTTP 传输(速度更快且使用更少的资源)
数据库查询:由于您没有提供在数据库中输入数据的方式,因此这里有两条线索:
如果您可以修改插入数据的代码,则使其通过 WebSockets(或根据需要通过 HTTP,但 WebSocket 更快)将这些数据发送到后端,并更新数据库记录(或新连接的用户)
如果你不能,这里有一个链接:How to listen for changes to a MongoDB collection?
希望这有帮助
关于node.js - 何时使用服务器发送的事件推送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43937472/