我希望在数据库添加新记录时能够流式传输数据。现在,我为每个已连接的用户每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
}