smo*_*mok 5 android firebase google-cloud-firestore
刚开始探索Firestore存储和要做的第一件事-通过文档密钥(已通过Google认证,请在我的Android应用中阅读一个简单的小文档),但这可能并不重要。这是一个片段:
public void readDoc(final String key) {
final long start = System.currentTimeMillis();
docsCollection.document(key).get().addOnCompleteListener(
new OnCompleteListener<DocumentSnapshot>() {
@Override public void onComplete(@NonNull Task<DocumentSnapshot> task) {
long end = System.currentTimeMillis();
Log.d("FirestoreStorage", "get() time: " + (end - start));
}
});
}
Run Code Online (Sandbox Code Playgroud)
这是我在LogCat中看到的内容:
10-10 22:30:06.026 D/FirestoreStorage: get() time: 1666
10-10 22:30:08.199 D/FirestoreStorage: get() time: 264
Run Code Online (Sandbox Code Playgroud)
第一次读取总是很慢,随后的读取大约为200ms。该文档非常小,当前只有4个属性,并且只有一个(int)为非null,因此大小不是问题。在真实手机上运行应用程序,在Android 7.1上运行Nexus 6
问题:我做错了什么?我基本上使用的是“使用指南”的“获取数据 ”中的示例。
这样的读取应该花费0毫秒。如果没有解决方法,我想我必须放弃实时存储作为该应用程序的唯一存储的想法,然后回到普通的SQLite并将Firebase / Firestore用作独立的云存储。
UPDATE从版本16.0.0开始DocumentReference.get()和Query.get()具有新的参数“ source”,该参数可控制从何处读取数据-仅服务器,仅缓存或尝试服务器然后缓存。
PS Firestore存储初始化和相应的日志,抱歉,不是500ms,而是350,这是不同的,有时是400,有时是300:
public FirestoreStorage(String userRef) {
Log.i(TAG, "User ref: \"" + userRef + "\"");
db = FirebaseFirestore.getInstance();
Log.i(TAG, "Is persistence enabled: " + db.getFirestoreSettings().isPersistenceEnabled());
DocumentReference userDoc = db.collection("users").document(userRef);
prefsCollection = userDoc.collection("prefs");
prefsCollection.addSnapshotListener(
Executors.newFixedThreadPool(2),
new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
Log.d(TAG, "Prefs.onEvent");
}
});
Log.i(TAG, "Snapshot listener added");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
日志:
10-11 23:11:42.382 I/FirestoreStorage: User ref: "<cut>"
10-11 23:11:42.474 I/FirestoreStorage: Is persistence enabled: true
10-11 23:11:42.496 I/FirestoreStorage: Snapshot listener added
10-11 23:11:42.855 D/FirestoreStorage: Prefs.onEvent
Run Code Online (Sandbox Code Playgroud)
These get() requests are reading the data from the Cloud Firestore backend, over the network, so they'll necessarily be much slower than SQLite which is just reading locally from disk. The first read is also likely to be slower than subsequent ones since it has to initiate the network channel to the backend. We'll look at improving performance over time, but you can't expect 0 ms if you're retrieving data over the network.
您可能需要启用脱机持久性,这将启用对先前读取的数据进行本地缓存。请注意,尽管get()呼叫仍然会尝试首先连接到网络,以便为您提供尽可能最新的数据。如果您addSnapshotListener()改为使用,我们将立即与您缓存的数据联系,而无需等待网络。
| 归档时间: |
|
| 查看次数: |
1964 次 |
| 最近记录: |