許多應用程式會在第一次載入網頁時,為所有使用者提供相同的內容。舉例來說,新聞網站可能會顯示最新報導,電子商務網站可能會顯示最暢銷的商品。
如果這項內容是透過 Cloud Firestore 提供,則每位使用者載入應用程式時,都會在取得相同結果時發出新的查詢。由於系統不會在使用者之間快取這些結果,因此應用程式速度會較慢,成本也超出需求。
解決方案:套裝組合
Cloud Firestore 組合可讓您使用 Firebase Admin SDK 組合後端常見查詢結果的資料組合,並在 CDN 上提供這些預先運算的 blob。這可讓使用者大幅加快首次載入的速度,並降低 Cloud Firestore 查詢費用。
在本指南中,我們將使用 Cloud Functions 產生套裝組合,以及 Firebase 託管,以動態快取並提供組合內容。如要進一步瞭解套件,請參閱指南。
首先建立一個簡單的公開 HTTP 函式來查詢最新的 50 個「精選故事」,並以組合的形式提供結果。
Node.js
exports.createBundle = functions.https.onRequest(async (request, response) => { // Query the 50 latest stories const latestStories = await db.collection('stories') .orderBy('timestamp', 'desc') .limit(50) .get(); // Build the bundle from the query results const bundleBuffer = db.bundle('latest-stories') .add('latest-stories-query', latestStories) .build(); // Cache the response for up to 5 minutes; // see https://firebase.google.com/docs/hosting/manage-cache response.set('Cache-Control', 'public, max-age=300, s-maxage=600'); response.end(bundleBuffer); });
Java
package com.example; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.FirestoreBundle; import com.google.cloud.firestore.Query.Direction; import com.google.cloud.firestore.QuerySnapshot; import com.google.cloud.functions.HttpFunction; import com.google.cloud.functions.HttpRequest; import com.google.cloud.functions.HttpResponse; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.cloud.FirestoreClient; import java.io.BufferedWriter; import java.io.IOException; public class ExampleFunction implements HttpFunction { public static FirebaseApp initializeFirebase() throws IOException { if (FirebaseApp.getApps().isEmpty()) { FirebaseOptions options = FirebaseOptions.builder() .setCredentials(GoogleCredentials.getApplicationDefault()) .setProjectId("YOUR-PROJECT-ID") .build(); FirebaseApp.initializeApp(options); } return FirebaseApp.getInstance(); } @Override public void service(HttpRequest request, HttpResponse response) throws Exception { // Get a Firestore instance FirebaseApp app = initializeFirebase(); Firestore db = FirestoreClient.getFirestore(app); // Query the 50 latest stories QuerySnapshot latestStories = db.collection("stories") .orderBy("timestamp", Direction.DESCENDING) .limit(50) .get() .get(); // Build the bundle from the query results FirestoreBundle bundle = db.bundleBuilder("latest-stores") .add("latest-stories-query", latestStories) .build(); // Cache the response for up to 5 minutes // see https://firebase.google.com/docs/hosting/manage-cache response.appendHeader("Cache-Control", "public, max-age=300, s-maxage=600"); // Write the bundle to the HTTP response BufferedWriter writer = response.getWriter(); writer.write(new String(bundle.toByteBuffer().array())); } }
接著設定 Firebase 託管,修改 firebase.json
來提供和快取這個 Cloud 函式。完成這項設定後,Firebase 託管 CDN 將根據 Cloud 函式所設定的快取設定提供組合內容。快取到期時,會再次觸發函式來重新整理內容。
firebase.json
{
"hosting": {
// ...
"rewrites": [{
"source": "/createBundle",
"function": "createBundle"
}]
},
// ...
}
最後,在網頁應用程式中,從 CDN 擷取組合內容並載入 Firestore SDK。
// If you are using module bundlers.
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/firestore/bundle" // This line enables bundle loading as a side effect.
async function fetchFromBundle() {
// Fetch the bundle from Firebase Hosting, if the CDN cache is hit the 'X-Cache'
// response header will be set to 'HIT'
const resp = await fetch('/createBundle');
// Load the bundle contents into the Firestore SDK
await db.loadBundle(resp.body);
// Query the results from the cache
// Note: omitting "source: cache" will query the Firestore backend.
const query = await db.namedQuery('latest-stories-query');
const storiesSnap = await query.get({ source: 'cache' });
// Use the results
// ...
}
預估省下的費用
假設新聞網站每天吸引 100,000 位使用者,且每位使用者在初次載入時載入相同的 50 則焦點新聞。如未設定任何快取,則每天從 Cloud Firestore 讀取文件的次數為 50 x 100,000 = 5,000,000。
現在,假設網站採用上述技術,並快取這 50 個結果 (最長 5 分鐘)。因此,結果是每小時完全載入 12 次,而不是為每位使用者載入查詢結果。無論有多少使用者抵達網站,對 Cloud Firestore 的查詢數量都不會改變。本頁將使用 12 x 24 x 50 = 14,400 次文件讀取,而非 5,000,000 次文件讀取。只要支付少許的 Firebase 託管和 Cloud Functions 費用,就能輕鬆抵銷 Cloud Firestore 節省的費用。
雖然開發人員在節省成本方面有所收穫,但最大的受益人是使用者。從 Firebase 託管 CDN (而不是直接從 Cloud Firestore) 載入這 50 份文件時,頁面內容載入時間容易縮短 100 到 200 毫秒以上。研究不斷證實,載入速度飛快的網頁 對使用者而言更順暢