node.js - 使用云功能在 Google Cloud pub/sub 上发布只需 3 分钟 - NodeJS

标签 node.js google-cloud-functions google-cloud-pubsub

我正在做一个函数,它将在收到网络钩子(Hook)后发布事件的类型。 它正在工作,但它在函数启动后大约 3 分钟发布消息。 这个长时间的停顿来自于 const {PubSub} = require('@google-cloud/pubsub') 我怎样才能让它走得更快?谢谢!

源代码:

exports.Challenge = (req,res) => {
    var type = req.body['event']['type']   
    console.log(type)                       
    console.log("start pubsub msg function")
    msgpubsub(type)
    console.log("end pubsub msg function")
}

function msgpubsub(_type){
    const topicName = "NAME_OF_TOPIC"
    console.log(`publishing message to topic: ${topicName}`)

    console.log("start require('@google-cloud/pubsub")
    const {PubSub} = require('@google-cloud/pubsub')
    console.log("end require(@google-cloud/pubsub)")

    console.log("start new pubsub")
    const pubSubClient = new PubSub('ID');
    console.log("end newpubsub")
    
    const messageBuffer = Buffer.from(_type)
    console.log("message buffer : " + messageBuffer)

    try{
        pubSubClient.topic(topicName).publish(messageBuffer)
    } catch(err){
        console.error(err)
    }

logs

最佳答案

最好创建一次客户端,然后在收到事件时使用客户端发布消息。就像现在一样,您在每次事件中都会创建一个全新的客户,这是昂贵的。

const topicName = "NAME_OF_TOPIC"
const {PubSub} = require('@google-cloud/pubsub')
const pubSubClient = new PubSub('ID');
const topicPublisher = pubSubClient.topic(topicName);

exports.Challenge = (req,res) => {
    var type = req.body['event']['type']   
    console.log(type)                       
    console.log("start pubsub msg function")
    msgpubsub(type)
    console.log("end pubsub msg function")
}

function msgpubsub(_type){    
    const messageBuffer = Buffer.from(_type)
    console.log("message buffer : " + messageBuffer)

    try {
        var publishFuture = topicPublisher.publish(messageBuffer);
        publishFuture.get();
    } catch(err){
        console.error(err)
    }
}

关于node.js - 使用云功能在 Google Cloud pub/sub 上发布只需 3 分钟 - NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63826979/

相关文章:

node.js - 如何在nodejs中使用firebase向超过10000个用户发送推送通知?

google-cloud-platform - 使用 python 中的访问 token 验证 Google Storage 对象

python - 如何在 Python 中创建从 Pub/Sub 到 GCS 的数据流管道

logging - GCP 日志路由器接收器没有将日志路由到主题?

node.js - MongoDB 保存用户时电子邮件和密码无效

javascript - 使用 __proto__ 扩展 Protractor 中的基本页面对象

node.js - Alexa session 保持打开状态,无需任何用户输入

javascript - Firebase 函数返回 "Response is not valid JSON object."

google-cloud-storage - 将新文件添加到 Cloud Storage 时触发 Dataflow 作业

python-3.x - 在 Mac OS 上安装 Pip 出现错误 : command '/usr/bin/clang' failed with exit code 1