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

时间:2019-08-21 11:26:02

标签: 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);
        }
    }
});

实际上,我知道如何通过过滤的查询来侦听以及从查询快照中侦听所有300条记录,但是,即使仅更新了一个文档,查询也会读取所有记录,并且大大增加了读取次数(成本也因此增加了)。

如果我有300个文档,并且想通过文档参考快照收听所有文档以进行实时更新,该怎么办。 将有300个单独的插槽或1个单例插槽用于全部监听。 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);
            }
        }
    });
}

1 个答案:

答案 0 :(得分:2)

与Cloud Firestore数据库进行交互时,将打开应用程序与Firebase服务器之间的单个套接字连接。从那一刻起,应用程序和数据库之间的所有流量都通过相同的套接字。因此,创建Firestore实例的次数无关紧要,它始终是单个连接。

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