簡體   English   中英

Google Cloud Function 部署后執行緩慢

[英]Google Cloud Function executes slowly once deployed

我正在使用執行以下步驟的 Cloud Function:

  • 從 API 中獲取一些數據
  • 准備先前檢索到的數據
  • 將數據存儲在 Firestore 中

這是我正在使用的代碼:

exports.syncItems = functions.https.onRequest((request, response) => {
    sync('url', 'colName').then(() => {
        response.status(200).send('Success!');
    }).catch((error) => {
        response.status(404).send('Failure!');
    });
});

async function sync(url, colName) {
    const response = await fetchData(url); // async function
    const items = prepareData(response); // not async function
    return await importData(colName, items); // async function
}

async function importData(colName, items) {
    const colRef = firestore.collection(colName);
    const batch = firestore.batch();

    items.forEach(item => {
        let docId = item.identifier;
        let docRef = colRef.doc(`${docId}`);
        batch.set(docRef, {
            // set data here
        });
    });
    return await batch.commit();
}

在后台訪問 Firestore 是由 AdminSDK 調解的。

const admin = require('firebase-admin');

admin.initializeApp({
    credential: admin.credential.applicationDefault(),
    projectId: 'myProjectId'
});

使用 Firebase 模擬器時,數據導入速度非常快。 Firestore 幾乎立即顯示集合和相關文檔。

相反,當將syncItems Google Cloud Function 部署到 Firebase 時,我看到了延遲(甚至 2/3 分鍾)。

有什么可能的原因嗎?

Google Cloud Functions 在部署后執行緩慢是否有任何可能的原因?

Firebase 模擬器的性能與 Firebase 在 Cloud Functions 中部署時的性能相比有很大不同。它們具有不同的代碼,並且在不同的計算資源上運行。

基於Firebase 的 Cloud Functions文檔:

Cloud Functions for Firebase 是一個無服務器框架,可讓您自動運行后端代碼以響應由 Firebase 功能和 HTTPS 請求觸發的事件。 您的 JavaScript 或 TypeScript 代碼存儲在 Google 的雲中,並在托管環境中運行。 無需管理和擴展您自己的服務器。

由於 Cloud Function 是無服務器的,因此很容易冷啟動。 它還具有可擴展性,因此您的數據可以分布在不同的地方。 Firebase 模擬器只加載測試項目時需要的資源。 當您將它部署到 Cloud Functions 時,我上面提到的因素就會發生。

您可以查看以下有關設計、實施、測試和部署 Cloud Functions 的最佳實踐的文檔:

如果您有任何疑問或需要澄清,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM