簡體   English   中英

何時使用服務器發送的事件推送數據

[英]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 這樣,數據通過TCP而不是HTTP傳輸(速度更快,使用的資源更少)
  • 數據庫查詢:由於您沒有提供如何在基礎中輸入數據,因此有兩個線索:

    如果您可以修改插入數據的代碼,則使其通過WebSockets(或根據需要通過HTTP,將這些數據發送到后端,但WebSocket更快)並更新記錄數據庫(或新連接的用戶)

    如果不能,那么這里是一個鏈接: 如何收聽對MongoDB集合的更改?

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM