【问题标题】:Cloud function doesn't send messages to PubSub云功能不向 PubSub 发送消息
【发布时间】:2021-09-19 00:46:05
【问题描述】:

总结:

您好,我正在使用云功能作为由 PubSub 触发的异步后台工作程序。 我有 2 个云函数,第一个将向 Cloud SQL 发出请求,然后,对于每个结果,都会将此结果发送到 PubSub。当一条消息(数据库中的结果之一)发送到 PubSub 时,将触发第二个。

错误:

有时(完全随机)第一个云函数在 SQL 请求之后没有发送任何消息,并且我的日志中有 0 个错误,什么都没有。

问题:

我做错了吗?

我必须尝试确认消息吗? (我想没有原因'我在 PubSub 文档中看到由 PubSub 触发的 CF 会自动确认消息)

我必须尝试再次发送消息吗?但是如果我有 0 个错误,我怎么知道我是否必须这样做?

代码:

//[requirements]
const {PubSub} = require('@google-cloud/pubsub');
const pubSubClient = new PubSub('<PROJECT_ID>');
const topicName = "<TOPIC_NAME>";
const topicPublisher = pubSubClient.topic(topicName)
//[requirements]


//[request]
  //make the setted request 
  conn.query(sql, (e,results) => {
    //if there is an error send it
    if(e) console.log(e)
    //for each result of the query, log it and publish it on PubSub
    results.forEach(function (element){
      console.log(JSON.stringify(element))
      msgPubSub(JSON.stringify(element))
    })
  })
//[request]

//[PubSub message publish fonction]
async function msgPubSub(data){
  const messageBuffer = Buffer.from(data)
  try {
    var futurePublish = await topicPublisher.publish(messageBuffer)
    console.log("Message id: " + futurePublish)
  } catch (error) {
    console.error(`Error while publishing message: ${error.message}`)
  }
}
//[PubSub message publish fonction]

日志:

当它不工作时:

当它工作时:

【问题讨论】:

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


    【解决方案1】:

    我认为您应该将您的查询函数转换为:

    let results;
    try {
        results = await conn.query(sql);
    } catch (err) {
        console.error(`SQL Error: ${err.message}`);
        return;
    }
    
    // TODO Maybe you can place a check here whether `results` is array
    // Or something like that
    for(let result of results){
        console.log(JSON.stringify(result))
        await msgPubSub(JSON.stringify(result))
    }
    

    await 和callback 一起用是废话

    【讨论】:

    • 嗬,这是真的,我的错!我只会使用回调,我更喜欢这种方式:)
    • pubsub 呢?现在工作更稳定了吗?
    • 是的,现在很稳定!非常感谢 :) 顺便说一句,我了解回调并等待 ^^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 2021-08-09
    • 2019-10-28
    • 2020-12-06
    • 2020-08-30
    • 1970-01-01
    • 2018-05-29
    相关资源
    最近更新 更多