通过 DocumentReference 监听 firestore 时将打开多少个套接字

MSK*_*MSK 3 c# firebase flutter google-cloud-firestore

我是 Cloud Firestore 的新手。当我阅读文档时,我看到了下面的代码:

DocumentReference docRef = db.Collection("cities").Document("SF");
FirestoreChangeListener listener = docRef.Listen(snapshot =>
{
    Console.WriteLine("Callback received document snapshot.");
    Console.WriteLine("Document exists? {0}", snapshot.Exists);
    if (snapshot.Exists)
    {
        Console.WriteLine("Document data for {0} document:", snapshot.Id);
        Dictionary<string, object> city = snapshot.ToDictionary();
        foreach (KeyValuePair<string, object> pair in city)
        {
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

实际上,我知道如何通过过滤查询进行侦听并侦听查询快照中的所有 300 条记录,但是即使只有一个文档更新,查询也会读取所有记录,并且会显着增加读取计数(成本也会增加)。

如果我有 300 个文档,并且我想通过文档参考快照收听所有文档的实时更新,该怎么办? 会有 300 个独立的套接字还是一个单例套接字来监听所有这些套接字。C# 驱动程序和 Flutter 驱动程序行为相同吗?

实施将是这样的;

foreach (var docRef in docRefList) //300 records
{
    FirestoreChangeListener listener = docRef.Listen(snapshot =>
    {
        Console.WriteLine("Callback received document snapshot.");
        Console.WriteLine("Document exists? {0}", snapshot.Exists);
        if (snapshot.Exists)
        {
            Console.WriteLine("Document data for {0} document:", snapshot.Id);
            Dictionary<string, object> city = snapshot.ToDictionary();
            foreach (KeyValuePair<string, object> pair in city)
            {
                Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*amo 5

当您与 Firebase 实时数据库交互时,您的应用程序和 Firebase 服务器之间会打开一个套接字连接。从那时起,应用程序和数据库之间的所有流量都通过同一个套接字。因此,无论您创建实时数据库实例多少次,它始终是单个连接。

另一方面,根据 @Frank van Puffelen 的评论,当您与 Cloud Firestore 数据库交互时,客户端使用 HTTP/2 连接而不是 Web 套接字连接到 Firestore。HTTP/2 和 Web 套接字都通过单个连接发送多个请求。

如果一段时间内没有活动监听器,Cloud Firestore 客户端会自动关闭连接,但当您附加监听器或再次执行读/写操作时,它会重新打开连接。