繁体   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