如何处理使用服务器发送的事件不断增长的数组

what to to with array that grows and grows using server sent events

我是 server sent events
的新手 我浏览了很多教程并观看了很多有用的视频,但我仍然不明白“如何处理根据每个用户请求不断增长的数据”??。

我用NodeJS所以我从这里开始..
How To Use Server-Sent Events in Node.js to Build a Realtime App

以下示例取自上述 link..

// in the following function they push each fact to facts array in order to later send it to the client
// the FACTS array can grow and grow and ... ??

async function addFact(request, respsonse, next) {
  const newFact = request.body;
  facts.push(newFact);
  respsonse.json(newFact); 
  return sendFactToAll(newFact);
}


// this is optimal, only 1 fact is send.
function sendFactToAll(newFact) {
   clients.forEach(client => 
   client.response.write(`data:${JSON.stringify(newFact)}\n\n`))
}

// what about sending all facts
function sendFactsToAll(facts) {
   clients.forEach(client => 
   client.response.write(`data:${JSON.stringify(facts)}\n\n`))
}
  1. 何时清除 FACTS 数组?
  2. 如果清除数组,那些需要从该数组中获取数据的用户怎么办?

谢谢!

what to do with the data that keep growing on every user request?

目前演示存储所有事实,并将它们作为客户端的启动历史全部发送出去。因为这是一个演示,所以他们没有深入讨论如何将它永远扩展到 运行 的混乱细节。

在真实的应用程序中,您可能希望为每个事实添加一个 ID(或时间戳)。然后您可以在重新连接时将其与 last-event-id 一起使用,以获取他们错过的事实。

您可能还想将事实存储在某种 SQL 数据库中,并可能提供单独的 Web 服务来访问历史记录。客户端将首先请求尽可能多的历史记录,然后启动事件源请求。

顺便说一句,如果您想扩展,我会将此历史请求服务设为单独的 Web 服务。对于事件源,缩放的限制因素是同时连接的数量,而对于存储历史记录,限制是磁盘 space.

另一种方法是只保留最近的 100 个左右的事实,而不用担心完整的历史记录。您可以通过让 addFact() 在执行推送之前先执行 facts = facts.slice(-99) 来做到这一点(如果不熟悉该语法,请参阅 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)。