แสดงเนื้อหา Firestore แบบรวมจาก CDN

แอปพลิเคชันจำนวนมากแสดงเนื้อหาเดียวกันต่อผู้ใช้ทุกคนเมื่อการโหลดหน้าเว็บแรก เช่น เว็บไซต์ข่าวอาจแสดงข่าวสารล่าสุด หรือเว็บไซต์อีคอมเมิร์ซอาจแสดงสินค้าขายดี

หากแสดงเนื้อหาจาก Cloud Firestore ผู้ใช้แต่ละรายจะส่ง คำค้นหาใหม่เพื่อดูผลลัพธ์เดียวกันเมื่อโหลดแอปพลิเคชัน เนื่องจากระบบไม่ได้แคชผลลัพธ์เหล่านี้ระหว่างผู้ใช้แต่ละราย แอปพลิเคชันจึงทำงานช้าลงและมีค่าใช้จ่ายสูงกว่าที่ควรจะเป็น

วิธีแก้ปัญหา: บันเดิล

Cloud Firestore บันเดิลช่วยให้คุณประกอบบันเดิลข้อมูลจากผลการค้นหาทั่วไป ในแบ็กเอนด์โดยใช้ Firebase Admin SDK และแสดง Blob ที่ คำนวณไว้ล่วงหน้าซึ่งแคชไว้ใน CDN ซึ่งจะช่วยให้ผู้ใช้ได้รับประสบการณ์การโหลดครั้งแรกที่เร็วขึ้นมาก และลดค่าใช้จ่ายในการค้นหา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 เพื่อแสดงและแคช Cloud Function นี้โดยแก้ไข firebase.json การกำหนดค่านี้จะทำให้ Firebase Hosting CDN แสดงเนื้อหาบันเดิลตามการตั้งค่าแคชที่กำหนดโดย Cloud Function เมื่อแคชหมดอายุ ระบบจะรีเฟรชเนื้อหาโดยเรียกใช้ฟังก์ชันอีกครั้ง

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 จะยังคงเท่าเดิม แทนที่จะอ่านเอกสาร 5,000,000 ครั้ง หน้าเว็บนี้จะอ่านเอกสาร 12 x 24 x 50 = 14,400 ครั้งต่อวัน ค่าใช้จ่ายเพิ่มเติมเล็กน้อยสำหรับโฮสติ้งของ Firebase และ Cloud Functions จะถูกชดเชยได้ง่ายๆ จากค่าใช้จ่ายที่ประหยัดได้จาก Cloud Firestore

แม้ว่านักพัฒนาจะได้รับประโยชน์จากค่าใช้จ่ายที่ประหยัดได้ แต่ผู้ที่ได้รับประโยชน์มากที่สุดคือผู้ใช้ การโหลดเอกสาร 50 รายการนี้จาก CDN ของโฮสติ้งของ Firebase แทนที่จะโหลดจาก Cloud Firestore โดยตรงจะช่วยลดเวลาที่ใช้ในการโหลดเนื้อหาของหน้าเว็บได้ 100-200 มิลลิวินาทีหรือมากกว่านั้น การศึกษาแสดงให้เห็นซ้ำๆ ว่าหน้าเว็บที่โหลดเร็วหมายถึงผู้ใช้ที่มีความสุขมากขึ้น