Phân phát nội dung đi kèm trên Firestore từ một CDN

Nhiều ứng dụng phân phát cùng một nội dung cho tất cả người dùng trong lượt tải trang đầu tiên. Ví dụ: trang web tin tức có thể hiển thị các tin bài mới nhất hoặc trang web thương mại điện tử có thể hiển thị các mặt hàng bán chạy nhất.

Nếu nội dung này được phân phát từ Cloud Firestore, thì mỗi người dùng sẽ đưa ra một truy vấn mới cho cùng kết quả khi họ tải ứng dụng. Vì các kết quả này không được lưu vào bộ nhớ đệm giữa những người dùng, nên ứng dụng sẽ chạy chậm hơn và tốn kém hơn mức cần thiết.

Giải pháp: Gói

Các gói Cloud Firestore cho phép bạn tập hợp các gói dữ liệu từ các kết quả truy vấn phổ biến trên phần phụ trợ bằng cách sử dụng SDK quản trị của Firebase, đồng thời phân phát các blob được tính toán trước này được lưu vào bộ nhớ đệm trên CDN. Nhờ đó, người dùng có trải nghiệm tải đầu tiên nhanh hơn nhiều và giảm chi phí truy vấn trên Cloud Firestore.

Trong hướng dẫn này, chúng ta sẽ sử dụng Cloud Functions để tạo gói và tính năng Lưu trữ Firebase để tự động lưu nội dung gói vào bộ nhớ đệm và phân phát nội dung gói. Bạn có thể xem thêm thông tin về các gói trong hướng dẫn.

Trước tiên, hãy tạo một hàm HTTP công khai đơn giản để truy vấn 50 "tin bài" mới nhất và phân phát kết quả dưới dạng một gói.

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()));
  }
}
      

Tiếp theo, hãy định cấu hình tính năng Lưu trữ Firebase để phân phát và lưu Hàm đám mây này vào bộ nhớ đệm bằng cách sửa đổi firebase.json. Với cấu hình này, CDN lưu trữ của Firebase sẽ phân phát nội dung gói theo chế độ cài đặt bộ nhớ đệm do Chức năng đám mây thiết lập. Khi bộ nhớ đệm hết hạn, bộ nhớ đệm sẽ làm mới nội dung bằng cách kích hoạt lại hàm.

firebase.json
{
  "hosting": {
    // ...
    "rewrites": [{
      "source": "/createBundle",
      "function": "createBundle"
    }]
  },
  // ...
}

Cuối cùng, trong ứng dụng web, hãy tìm nạp nội dung đi kèm từ CDN rồi tải nội dung đó vào 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
  // ...
}

Mức tiết kiệm ước tính

Hãy xem xét một trang web tin tức có 100.000 người dùng mỗi ngày và mỗi người dùng tải cùng 50 tin bài hàng đầu trong lần tải ban đầu. Nếu không lưu vào bộ nhớ đệm, kết quả sẽ là 50 x 100.000 = 5.000.000 lượt đọc tài liệu mỗi ngày từ Cloud Firestore.

Bây giờ, giả sử trang web áp dụng kỹ thuật trên và lưu 50 kết quả đó vào bộ nhớ đệm trong tối đa 5 phút. Vì vậy, thay vì tải kết quả truy vấn cho mọi người dùng, kết quả sẽ được tải chính xác 12 lần mỗi giờ. Bất kể có bao nhiêu người dùng truy cập vào trang web, số lượng truy vấn đến Cloud Firestore không thay đổi. Thay vì 5.000.000 lượt đọc tài liệu, trang này sẽ sử dụng 12 x 24 x 50 = 14.400 lượt đọc tài liệu mỗi ngày. Việc tiết kiệm chi phí trong Cloud Firestore có thể giúp bạn dễ dàng bù đắp những khoản chi phí nhỏ bổ sung cho tính năng Lưu trữ Firebase và Chức năng đám mây.

Mặc dù việc tiết kiệm chi phí là lợi ích của nhà phát triển, nhưng người thụ hưởng lớn nhất chính là người dùng. Việc tải 50 tài liệu này từ CDN lưu trữ của Firebase thay vì trực tiếp từ Cloud Firestore có thể dễ dàng cắt giảm từ 100 đến 200 mili giây trở lên trong thời gian tải nội dung của trang. Các nghiên cứu đã nhiều lần chỉ ra rằng các trang nhanh có nghĩa là người dùng hài lòng hơn.