Cloud Firestore obsługuje trwałość danych offline. Ta funkcja buforuje kopię danych Cloud Firestore, z których aktywnie korzysta Twoja aplikacja, dzięki czemu aplikacja może uzyskać dostęp do danych, gdy urządzenie jest offline. Możesz pisać, czytać, słuchać i wysyłać zapytania do danych w pamięci podręcznej. Gdy urządzenie wróci do trybu online, Cloud Firestore synchronizuje wszelkie lokalne zmiany wprowadzone przez aplikację z backendem Cloud Firestore.
Aby korzystać z trwałości w trybie offline, nie musisz wprowadzać żadnych zmian w kodzie, którego używasz do uzyskiwania dostępu do danych Cloud Firestore. Po włączeniu trwałości w trybie offline biblioteka kliencka Cloud Firestore automatycznie zarządza dostępem do danych online i offline oraz synchronizuje dane lokalne, gdy urządzenie znów będzie online.
Skonfiguruj trwałość offline
Po zainicjowaniu Cloud Firestore możesz włączyć lub wyłączyć trwałość offline:
- W przypadku platform Android i Apple trwałość w trybie offline jest domyślnie włączona. Aby wyłączyć trwałość, ustaw opcję
PersistenceEnabled
nafalse
. - W przypadku Internetu trwałość offline jest domyślnie wyłączona. Aby włączyć trwałość, wywołaj metodę
enablePersistence
. Pamięć podręczna Cloud Firestore nie jest automatycznie czyszczona pomiędzy sesjami. W związku z tym, jeśli Twoja aplikacja internetowa obsługuje poufne informacje, przed włączeniem trwałości zapytaj użytkownika, czy korzysta z zaufanego urządzenia.
Web modular API
// Memory cache is the default if no config is specified.
initializeFirestore(app);
// This is the default behavior if no persistence is specified.
initializeFirestore(app, {localCache: memoryLocalCache()});
// Defaults to single-tab persistence if no tab manager is specified.
initializeFirestore(app, {localCache: persistentLocalCache(/*settings*/{})});
// Same as `initializeFirestore(app, {localCache: persistentLocalCache(/*settings*/{})})`,
// but more explicit about tab management.
initializeFirestore(app,
{localCache:
persistentLocalCache(/*settings*/{tabManager: persistentSingleTabManager()})
});
// Use multi-tab IndexedDb persistence.
initializeFirestore(app,
{localCache:
persistentLocalCache(/*settings*/{tabManager: persistentMultipleTabManager()})
});
Web namespaced API
firebase.firestore().enablePersistence() .catch((err) => { if (err.code == 'failed-precondition') { // Multiple tabs open, persistence can only be enabled // in one tab at a a time. // ... } else if (err.code == 'unimplemented') { // The current browser does not support all of the // features required to enable persistence // ... } }); // Subsequent queries will use persistence, if it was enabled successfully
Szybki
let settings = FirestoreSettings() // Use memory-only cache settings.cacheSettings = MemoryCacheSettings(garbageCollectorSettings: MemoryLRUGCSettings()) // Use persistent disk cache, with 100 MB cache size settings.cacheSettings = PersistentCacheSettings(sizeBytes: 100 * 1024 * 1024 as NSNumber) // Any additional options // ... // Enable offline data persistence let db = Firestore.firestore() db.settings = settings
Cel C
FIRFirestoreSettings *settings = [[FIRFirestoreSettings alloc] init]; // Use memory-only cache settings.cacheSettings = [[FIRMemoryCacheSettings alloc] initWithGarbageCollectorSettings:[[FIRMemoryLRUGCSettings alloc] init]]; // Use persistent disk cache (default behavior) // This example uses 100 MB. settings.cacheSettings = [[FIRPersistentCacheSettings alloc] initWithSizeBytes:@(100 * 1024 * 1024)]; // Any additional options // ... // Enable offline data persistence FIRFirestore *db = [FIRFirestore firestore]; db.settings = settings;
Kotlin+KTX
val settings = firestoreSettings { // Use memory cache setLocalCacheSettings(memoryCacheSettings {}) // Use persistent disk cache (default) setLocalCacheSettings(persistentCacheSettings {}) } db.firestoreSettings = settings
Java
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder(db.getFirestoreSettings()) // Use memory-only cache .setLocalCacheSettings(MemoryCacheSettings.newBuilder().build()) // Use persistent disk cache (default) .setLocalCacheSettings(PersistentCacheSettings.newBuilder() .build()) .build(); db.setFirestoreSettings(settings);
Dart
// Apple and Android db.settings = const Settings(persistenceEnabled: true); // Web await db .enablePersistence(const PersistenceSettings(synchronizeTabs: true));
Skonfiguruj rozmiar pamięci podręcznej
Gdy włączona jest trwałość, Cloud Firestore buforuje każdy dokument otrzymany z backendu w celu umożliwienia dostępu offline. Cloud Firestore ustawia domyślny próg rozmiaru pamięci podręcznej. Po przekroczeniu wartości domyślnej Cloud Firestore okresowo próbuje wyczyścić starsze, nieużywane dokumenty. Możesz skonfigurować inny próg rozmiaru pamięci podręcznej lub całkowicie wyłączyć proces czyszczenia:
Web modular API
import { initializeFirestore, CACHE_SIZE_UNLIMITED } from "firebase/firestore"; const firestoreDb = initializeFirestore(app, { cacheSizeBytes: CACHE_SIZE_UNLIMITED });
Web namespaced API
firebase.firestore().settings({ cacheSizeBytes: firebase.firestore.CACHE_SIZE_UNLIMITED });
Szybki
// The default cache size threshold is 100 MB. Configure "cacheSizeBytes" // for a different threshold (minimum 1 MB) or set to "FirestoreCacheSizeUnlimited" // to disable clean-up. let settings = Firestore.firestore().settings // Set cache size to 100 MB settings.cacheSettings = PersistentCacheSettings(sizeBytes: 100 * 1024 * 1024 as NSNumber) Firestore.firestore().settings = settings
Cel C
// The default cache size threshold is 100 MB. Configure "cacheSizeBytes" // for a different threshold (minimum 1 MB) or set to "kFIRFirestoreCacheSizeUnlimited" // to disable clean-up. FIRFirestoreSettings *settings = [FIRFirestore firestore].settings; // Set cache size to 100 MB settings.cacheSettings = [[FIRPersistentCacheSettings alloc] initWithSizeBytes:@(100 * 1024 * 1024)]; [FIRFirestore firestore].settings = settings;
Kotlin+KTX
// The default cache size threshold is 100 MB. Configure "setCacheSizeBytes" // for a different threshold (minimum 1 MB) or set to "CACHE_SIZE_UNLIMITED" // to disable clean-up. val settings = FirebaseFirestoreSettings.Builder() .setCacheSizeBytes(FirebaseFirestoreSettings.CACHE_SIZE_UNLIMITED) .build() db.firestoreSettings = settings
Java
// The default cache size threshold is 100 MB. Configure "setCacheSizeBytes" // for a different threshold (minimum 1 MB) or set to "CACHE_SIZE_UNLIMITED" // to disable clean-up. FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder() .setCacheSizeBytes(FirebaseFirestoreSettings.CACHE_SIZE_UNLIMITED) .build(); db.setFirestoreSettings(settings);
Dart
db.settings = const Settings( persistenceEnabled: true, cacheSizeBytes: Settings.CACHE_SIZE_UNLIMITED, );
Słuchaj danych offline
Gdy urządzenie jest w trybie offline, jeśli włączono trwałość w trybie offline, słuchacze będą otrzymywać zdarzenia odsłuchiwania, gdy zmienią się dane przechowywane lokalnie w pamięci podręcznej. Możesz odsłuchiwać dokumenty, zbiory i zapytania.
Aby sprawdzić, czy otrzymujesz dane z serwera, czy z pamięci podręcznej, użyj właściwości fromCache
w SnapshotMetadata
w zdarzeniu migawki. Jeśli fromCache
ma true
, dane pochodzą z pamięci podręcznej i mogą być nieaktualne lub niekompletne. Jeśli fromCache
ma wartość false
, dane są kompletne i aktualne z najnowszymi aktualizacjami na serwerze.
Domyślnie żadne zdarzenie nie jest wywoływane, jeśli zmieniono tylko SnapshotMetadata
. Jeśli polegasz na wartościach fromCache
, określ opcję nasłuchiwania includeMetadataChanges
podczas dołączania procedury obsługi nasłuchiwania.
Web modular API
import { collection, onSnapshot, where, query } from "firebase/firestore"; const q = query(collection(db, "cities"), where("state", "==", "CA")); onSnapshot(q, { includeMetadataChanges: true }, (snapshot) => { snapshot.docChanges().forEach((change) => { if (change.type === "added") { console.log("New city: ", change.doc.data()); } const source = snapshot.metadata.fromCache ? "local cache" : "server"; console.log("Data came from " + source); }); });
Web namespaced API
db.collection("cities").where("state", "==", "CA") .onSnapshot({ includeMetadataChanges: true }, (snapshot) => { snapshot.docChanges().forEach((change) => { if (change.type === "added") { console.log("New city: ", change.doc.data()); } var source = snapshot.metadata.fromCache ? "local cache" : "server"; console.log("Data came from " + source); }); });
Szybki
// Listen to metadata updates to receive a server snapshot even if // the data is the same as the cached data. db.collection("cities").whereField("state", isEqualTo: "CA") .addSnapshotListener(includeMetadataChanges: true) { querySnapshot, error in guard let snapshot = querySnapshot else { print("Error retreiving snapshot: \(error!)") return } for diff in snapshot.documentChanges { if diff.type == .added { print("New city: \(diff.document.data())") } } let source = snapshot.metadata.isFromCache ? "local cache" : "server" print("Metadata: Data fetched from \(source)") }
Cel C
// Listen to metadata updates to receive a server snapshot even if // the data is the same as the cached data. [[[db collectionWithPath:@"cities"] queryWhereField:@"state" isEqualTo:@"CA"] addSnapshotListenerWithIncludeMetadataChanges:YES listener:^(FIRQuerySnapshot *snapshot, NSError *error) { if (snapshot == nil) { NSLog(@"Error retreiving snapshot: %@", error); return; } for (FIRDocumentChange *diff in snapshot.documentChanges) { if (diff.type == FIRDocumentChangeTypeAdded) { NSLog(@"New city: %@", diff.document.data); } } NSString *source = snapshot.metadata.isFromCache ? @"local cache" : @"server"; NSLog(@"Metadata: Data fetched from %@", source); }];
Kotlin+KTX
db.collection("cities").whereEqualTo("state", "CA") .addSnapshotListener(MetadataChanges.INCLUDE) { querySnapshot, e -> if (e != null) { Log.w(TAG, "Listen error", e) return@addSnapshotListener } for (change in querySnapshot!!.documentChanges) { if (change.type == DocumentChange.Type.ADDED) { Log.d(TAG, "New city: ${change.document.data}") } val source = if (querySnapshot.metadata.isFromCache) { "local cache" } else { "server" } Log.d(TAG, "Data fetched from $source") } }
Java
db.collection("cities").whereEqualTo("state", "CA") .addSnapshotListener(MetadataChanges.INCLUDE, new EventListener<QuerySnapshot>() { @Override public void onEvent(@Nullable QuerySnapshot querySnapshot, @Nullable FirebaseFirestoreException e) { if (e != null) { Log.w(TAG, "Listen error", e); return; } for (DocumentChange change : querySnapshot.getDocumentChanges()) { if (change.getType() == Type.ADDED) { Log.d(TAG, "New city:" + change.getDocument().getData()); } String source = querySnapshot.getMetadata().isFromCache() ? "local cache" : "server"; Log.d(TAG, "Data fetched from " + source); } } });
Dart
db .collection("cities") .where("state", isEqualTo: "CA") .snapshots(includeMetadataChanges: true) .listen((querySnapshot) { for (var change in querySnapshot.docChanges) { if (change.type == DocumentChangeType.added) { final source = (querySnapshot.metadata.isFromCache) ? "local cache" : "server"; print("Data fetched from $source}"); } } });
Uzyskaj dane offline
Jeśli otrzymasz dokument, gdy urządzenie jest w trybie offline, Cloud Firestore zwróci dane z pamięci podręcznej.
Podczas wysyłania zapytania do kolekcji zwracany jest pusty wynik, jeśli nie ma żadnych dokumentów w pamięci podręcznej. Podczas pobierania określonego dokumentu zamiast tego zwracany jest błąd.
Zapytaj o dane offline
Zapytania działają z trwałością w trybie offline. Wyniki zapytań można pobrać bezpośrednio lub poprzez nasłuchiwanie, jak opisano w poprzednich sekcjach. Możesz także tworzyć nowe zapytania na danych utrwalonych lokalnie, gdy urządzenie jest w trybie offline, ale początkowo zapytania będą uruchamiane tylko w odniesieniu do dokumentów w pamięci podręcznej.
Skonfiguruj indeksy zapytań offline
Domyślnie pakiet SDK Firestore skanuje wszystkie dokumenty w kolekcji w lokalnej pamięci podręcznej podczas wykonywania zapytań offline. W przypadku tego domyślnego zachowania wydajność zapytań w trybie offline może ulec pogorszeniu, gdy użytkownicy pozostają w trybie offline przez dłuższy czas.
Po włączeniu trwałej pamięci podręcznej można poprawić wydajność zapytań offline, zezwalając pakietowi SDK na automatyczne tworzenie lokalnych indeksów zapytań.
Automatyczne indeksowanie jest domyślnie wyłączone. Twoja aplikacja musi umożliwiać automatyczne indeksowanie przy każdym uruchomieniu. Kontroluj, czy automatyczne indeksowanie jest włączone, jak pokazano poniżej.
Szybki
if let indexManager = Firestore.firestore().persistentCacheIndexManager { // Indexing is disabled by default indexManager.enableIndexAutoCreation() } else { print("indexManager is nil") }
Cel C
PersistentCacheIndexManager *indexManager = [FIRFirestore firestore].persistentCacheIndexManager; if (indexManager) { // Indexing is disabled by default [indexManager enableIndexAutoCreation]; }
Kotlin+KTX
// return type: PersistentCacheManager? Firebase.firestore.persistentCacheIndexManager?.apply { // Indexing is disabled by default enableIndexAutoCreation() } ?: println("indexManager is null")
Java
// return type: @Nullable PersistentCacheIndexManager PersistentCacheIndexManager indexManager = FirebaseFirestore.getInstance().getPersistentCacheIndexManager(); if (indexManager != null) { // Indexing is disabled by default indexManager.enableIndexAutoCreation(); } // If not check indexManager != null, IDE shows warning: Method invocation 'enableIndexAutoCreation' may produce 'NullPointerException' FirebaseFirestore.getInstance().getPersistentCacheIndexManager().enableIndexAutoCreation();
Po włączeniu automatycznego indeksowania zestaw SDK ocenia, które kolekcje zawierają dużą liczbę dokumentów w pamięci podręcznej i optymalizuje wydajność zapytań lokalnych.
Zestaw SDK zapewnia metodę usuwania indeksów zapytań.
Wyłącz i włącz dostęp do sieci
Możesz użyć poniższej metody, aby wyłączyć dostęp do sieci dla swojego klienta Cloud Firestore. Gdy dostęp do sieci jest wyłączony, wszystkie odbiorniki migawek i żądania dokumentów pobierają wyniki z pamięci podręcznej. Operacje zapisu są umieszczane w kolejce do momentu ponownego włączenia dostępu do sieci.
Web modular API
import { disableNetwork } from "firebase/firestore"; await disableNetwork(db); console.log("Network disabled!"); // Do offline actions // ...
Web namespaced API
firebase.firestore().disableNetwork() .then(() => { // Do offline actions // ... });
Szybki
Firestore.firestore().disableNetwork { (error) in // Do offline things // ... }
Cel C
[[FIRFirestore firestore] disableNetworkWithCompletion:^(NSError *_Nullable error) { // Do offline actions // ... }];
Kotlin+KTX
db.disableNetwork().addOnCompleteListener { // Do offline things // ... }
Java
db.disableNetwork() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { // Do offline things // ... } });
Dart
db.disableNetwork().then((_) { // Do offline things });
Użyj poniższej metody, aby ponownie włączyć dostęp do sieci:
Web modular API
import { enableNetwork } from "firebase/firestore"; await enableNetwork(db); // Do online actions // ...
Web namespaced API
firebase.firestore().enableNetwork() .then(() => { // Do online actions // ... });
Szybki
Firestore.firestore().enableNetwork { (error) in // Do online things // ... }
Cel C
[[FIRFirestore firestore] enableNetworkWithCompletion:^(NSError *_Nullable error) { // Do online actions // ... }];
Kotlin+KTX
db.enableNetwork().addOnCompleteListener { // Do online things // ... }
Java
db.enableNetwork() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { // Do online things // ... } });
Dart
db.enableNetwork().then((_) { // Back online });