Google Cloud Functions 和 PubSub - 空闲后延迟

Google Cloud Functions & PubSub - delay after idling

我正在触发一个 HTTP 云函数,然后它会向我的 PubSub 主题发布一条消息。当每隔几秒发布一次时,这工作起来非常快,通常延迟 <1 秒。但是,如果我有一段时间(比如 5 分钟)没有发布任何内容,则发布会延迟很长时间(~20 秒)。

我怎样才能使它始终如一地快速?想法:

发布者函数:

"use strict";
const PubSub = require("@google-cloud/pubsub");
const pubsub = PubSub({
    projectId: "pubsub-forwarders"
});

exports.testFunction = function testFunction(req, res) {
    publishMessage("testtopic", "testmessage");
    res.status(200).send();
}

function publishMessage(topicName, data) {
    const topic = pubsub.topic(topicName);
    const publisher = topic.publisher();
    const dataBuffer = Buffer.from(data);

    return publisher.publish(dataBuffer)
        .then((results) => {
            console.log("Message", JSON.stringify(results), "published.");
            return JSON.stringify(results);
    });
}

云函数日志:

16:57:05.938 Function execution started
16:57:05.948 Function execution took 11 ms, finished with status code: 200
16:57:22.987 Message "179492329652563" published.

非常感谢!

原因是 Google 云功能在发送响应后关闭实例。

只需要将异步发布改为同步发布,发布成功后发送响应即可。将发布时间缩短到几十毫秒。

"use strict";
const PubSub = require("@google-cloud/pubsub");
const pubsub = PubSub({
    projectId: "pubsub-forwarders"
});

exports.testFunction = async function testFunction(req, res) {
    const messageId = await publishMessage("testtopic", "testmessage");
    console.log("Message ", messageId, " published.");
    res.status(200).send();
}

async function publishMessage(topicName, data) {
    const topic = pubsub.topic(topicName);
    const publisher = topic.publisher();
    const dataBuffer = Buffer.from(data);
    return await publisher.publish(dataBuffer);
}

见参考:https://cloud.google.com/functions/docs/bestpractices/tips#do_not_start_background_activities