问题描述
我试图了解Firebase Realtime Database如何使用缓存.该文档未阐明有关缓存处理的某些情况.特别是对于Flutter,没有文档,而且在线资源还不够.我很困惑两种情况.
I'm trying to understand how Firebase Realtime Database uses cache. The documentation doesn't clarify some cases about cache handling. Especially for Flutter, there is no documentation and online sources are not enough. There are two different scenarios that I'm confused.
首先,我首先设置两种情况的缓存:
First of all, I start with setting the cache for both scenarios:
await FirebaseDatabase.instance.setPersistenceEnabled(true);
await FirebaseDatabase.instance.setPersistenceCacheSizeBytes(10000000);
方案1:我听的是特定用户的价值.我想一次下载用户数据.然后,请始终使用缓存并仅在有更新的情况下下载更新:
Scenario 1: I listen to the value of a specific user. I want to donwload user data for once. Then, always use cache and download only updates if there is any:
final stream = FirebaseDatabase().reference().child("users").child("some_id").onValue();
据我了解,如果没有更新,Firebase将首先下载该节点,然后再使用缓存.即使应用程序重新启动,也不会更改.
It's my understanding that Firebase will download the node first and use the cache later if there is no update. This won't change even if the app restarts.
方案2:我想查询仅在日期之后创建的帖子:
Scenario 2: I want to query the posts that are created only after the date:
final date = DateTime(2020,6,20);
final data = await FirebaseDatabase().reference().child("posts").orderByChild("createdAt").startAt(date).once();
在方案2中,我不确定如何完成缓存.如果Firebase Realtime Database缓存了查询,那么在该日期之后创建新帖子时,它将下载所有内容吗?还是只下载新帖子并从缓存中获取其他帖子?
Here for Scenario 2, I'm not sure how cache will be done. If Firebase Realtime Database caches the query, will it download everything when a new post created after the date? Or it will download only the new post and get others from the cache?
推荐答案
如果监听器所在的位置/查询发生更改,则Firebase将对该数据执行所谓的增量同步.在此增量同步中,客户端在其内部数据版本的子树上计算哈希,然后将其发送到服务器.服务器将这些哈希值与其自己的子树的哈希值进行比较,并仅将哈希值不同的子树发送回去.通常,它比完整数据要小很多,但不一定是最小增量.
If there is a change to a location/query that you have a listener on, Firebase performs a so-called delta-sync on that data. In this delta-sync, the client calculates hashes on subtrees of its internal version of the data, and sends those to the server. The server compares those hashes with those of its own subtrees and only sends back the subtrees where the hashes are different. This is usually quite a bit smaller than the full data, but not necessarily the minimal delta.
请注意,无论是否启用磁盘持久性,Firebase都会始终在内存中已经存在的用于查询/位置的数据与服务器上的数据之间执行增量同步.启用磁盘持久性只是意味着将首先从磁盘填充内存中的副本,但是此后,增量同步在两种情况下均相同.
Note that Firebase will always perform a delta sync between the data it has in memory already for the query/location and the data on the server, regardless of whether you enable disk persistence. Having disk persistence enabled just means the in-memory copy will initially be populated from disk, but after that the delta-sync works the same for both cases.
这篇关于Flutter上的Firebase实时数据库缓存行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!