【问题标题】:admin.messaging().sendToTopic exceeds daily CPU allocation limit [duplicate]admin.messaging().sendToTopic 超出每日 CPU 分配限制 [重复]
【发布时间】:2019-05-31 18:50:54
【问题描述】:

我有以下 Firebase 函数代码:

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

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

exports.sendNotification = functions.https.onRequest((request, response) => {
    const payLoad = {
        data: {
            execute_noise_measure: "true"
        }
    };

    const options = {
        priority: "high"
    };

    return admin.messaging().sendToTopic("all", payLoad, options).then(function(response) {
            return console.log("Successfully sent message:", response);
        })
        .catch(function(error) {
            return console.log("Error sending message:", error);
        });
});

函数正确执行,在控制台中给出“成功发送消息:”响应。不幸的是,每个函数调用都会消耗大量的“函数调用中的 CPU 分配”。几次通话后,我的每日限额超出了:“错误:超出配额(配额组“CPUMilliSecondsDailyNonbillable”超出配额”

这可能是什么原因?如何改进我的代码?

【问题讨论】:

  • 我不认为sendToTopic 应该占用大量本地 CPU 时间,因为从主题到设备 ID 的实际扇出发生在 Google 的服务器上。你能计时/找出每个单独的电话需要多长时间吗?
  • @FrankvanPuffelen 我刚刚添加了带有日志输出的屏幕截图。检查我的编辑。该函数似乎以超时结束。我怎样才能避免这种情况?
  • 这听起来像是您返回的承诺永远不会解决,这肯定可以解释为什么您会在几次调用中耗尽您的免费 CPU 配额。 return console.log(...) 在我看来很可疑,因为 console.log() 返回 undefined。我会分离出console.log(...); return true;
  • 这似乎是问题的一部分。我根据您的建议将这些陈述分开,但这还不够。我还需要添加response.status(200).send("ok");。现在一切正常,CPU 分配使用率下降了大约 400 次。
  • 啊,我没有注意到你的函数是HTTP触发的。在这种情况下,您确实需要向客户端发送响应以终止该功能。

标签: javascript google-cloud-platform firebase-cloud-messaging google-cloud-functions firebase-admin


【解决方案1】:

感谢 Frank van Puffelen comment 我终于获得了 OK 200。看来我的代码缺少响应状态发送。这是有效的代码:

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

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

exports.sendNotification = functions.https.onRequest((request, response) => {
    const payload = {
        data: {
            execute_noise_measure: "true"
        }
    };

    const options = {
        priority: "high"
    };

    admin.messaging().sendToTopic("all", payload).then(() => {
        response.status(200).send("ok");

        return true;
    }).catch((err) => {
        response.status(500).send(err);

        return true;
    });
});

【讨论】:

    猜你喜欢
    • 2021-09-21
    • 2020-07-28
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2011-08-15
    相关资源
    最近更新 更多