gcloud 检查主题是否存在以及重用该主题的能力

gcloud check if a topic exist and ability to reuse the topic

我正在使用 gcloud-node

createTopic api returns 错误 409,如果该主题已经存在。是否有一个标志可以在发布消息时隐式创建一个主题,或者是否有一个 API 来检查一个主题是否已经存在?

使用 getTopics API 很容易,遍历响应主题数组并确定主题是否存在。只是想确保我不写东西,如果它已经存在的话。

Is there a flag that can implicitly create a topic when publishing a message or Is there an API to check if a topic exist already?

我相信您会 运行 遇到的问题是,如果将消息发布到不存在的主题,它会立即被删除。因此,它不会徘徊等待创建订阅;它会消失的。

但是,gcloud-node 确实有在必要时创建主题的方法:

var topic = pubsub.topic('topic-that-maybe-exists');
topic.get({ autoCreate: true }, function(err, topic) {
  // topic.publish(...
});

事实上,几乎所有 gcloud-node 对象都有 get 方法,其工作方式与上述相同,即 Pub/Sub subscription 或 Storage bucket 或 BigQuery dataset,等等

这是文档中 topic.get() 方法的 link:https://googlecloudplatform.github.io/gcloud-node/#/docs/v0.37.0/pubsub/topic?method=get

运行 最近进入这个,接受的答案会让你遇到 http 429 错误。 topic.get 是一种管理功能,其速率限制明显低于正常功能。你应该只在必要时打电话给他们,例如。发布期间错误代码 404(主题不存在),类似这样:

topic.publish(payload, (err) => {
  if(err && err.code === 404){
    topic.get({ autoCreate: true }, (err, topic) => {
      topic.publish(payload)
    });
  }
});