何时使用服务器发送的事件推送数据

我想在新logging添加到数据库时stream式传输数据。 现在,我正在每隔10秒查询db的新logging为每个连接的用户。 有没有更好的方法来做到这一点? 我觉得我应该在插入新logging后提出事件,并以某种方式访问​​相关用户和用户的请求。

(我已经简化了我的代码,使其清晰明了,所以可能还没有完全正常工作。)

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(更快,使用更less的资源)
  • 数据库查询:由于您没有提供如何input数据的基础,这里有两个线索:

    如果您可以修改代码插入数据,然后通过WebSockets(或通过HTTP,如果您想要,但WebSocket更快)将它们发送到后端,并更新logging(或新连接的用户)的数据库,

    如果你不能,这里有一个链接: 如何监听对MongoDB集合的更改?

希望这可以帮助