แสดงเนื้อหา Firestore แบบกลุ่มจาก CDN

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

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

วิธีแก้ไข: การรวมกลุ่ม

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