許多應用程式在首次載入網頁時,會向所有使用者提供相同的內容。例如,新聞網站可能會顯示最新報導,電子商務網站則可能會顯示暢銷商品。
如果這項內容是由 Cloud Firestore 提供,每位使用者在載入應用程式時,都會針對相同結果發出新的查詢。由於這些結果不會在使用者之間快取,因此應用程式的速度會變慢,且費用會高於所需。
解決方案:套裝組合
Cloud Firestore 套件可讓您使用 Firebase Admin SDK,從後端的常見查詢結果組合資料套件,並提供在 CDN 上快取的預先計算 blob。這可大幅加快使用者首次載入的速度,並降低 Cloud Firestore 查詢成本。
在本指南中,我們將使用 Cloud Functions 產生套件,並使用 Firebase Hosting 動態快取及提供套件內容。如要進一步瞭解套裝組合,請參閱指南。
首先,建立簡單的公開 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.json,設定 Firebase 託管來提供及快取這項 Cloud 函式。完成這項設定後,Firebase Hosting 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 載入這 50 份文件,而不是直接從 Cloud Firestore 載入,可輕鬆縮短網頁內容載入時間 100 到 200 毫秒以上。研究一再顯示,網頁速度越快,使用者越滿意。