【问题标题】:Google Cloud Functions & PubSub - delay after idlingGoogle Cloud Functions 和 PubSub - 空闲后延迟
【发布时间】:2017-12-06 16:15:01
【问题描述】:

我正在触发一个 HTTP 云函数,然后它会向我的 PubSub 主题发布一条消息。每隔几秒发布一次,这工作得很快,通常延迟

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

  • 以某种方式配置 Pub/Sub 发布者立即执行此操作。不过,在 API 文档中找不到这样的参数。
  • 更改发布者功能。

发布者功能:

"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-cloud-functions google-cloud-pubsub


【解决方案1】:

原因是 Google Cloud Function 在发送响应后关闭了实例。

只需将异步发布更改为同步并在发布成功后发送响应。将发布时间缩短到几十毫秒。

"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

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2019-03-25
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多