简体   繁体   English

什么是初始化 pubsub 订阅的好方法

[英]What would be a good way to initialize a subscription for pubsub

I am trying to use pubsub for the first time outside of cloud functions in a cloud run service, and I am confused about the use of createSubscription .我第一次尝试在云运行服务中的云功能之外使用 pubsub,我对createSubscription的使用感到困惑。

I trigger the message from a job in cloud scheduler, and when I set the topic it creates the topic in the project for me if it doesn't exist yet.我从云调度程序中的作业触发消息,当我设置主题时,它会在项目中为我创建主题(如果主题尚不存在)。

Now the cloud run service, when it starts, could call createSubscription , because initially there is no subscription yet.现在云运行服务在启动时可以调用createSubscription ,因为最初还没有订阅。 But it seems that createSubscription should only be called once (like createTopic) because after that I get an error saying a subscription with that name already exists.但似乎 createSubscription 应该只被调用一次(如 createTopic),因为之后我收到一条错误消息,指出具有该名称的订阅已存在。

I could place a try/catch around createSubscription and ignore the error on subsequent service deployments, but that seems a bit odd.我可以在 createSubscription 周围放置一个 try/catch 并忽略后续服务部署中的错误,但这似乎有点奇怪。

What would be a good way to initialize the subscription?什么是初始化订阅的好方法?

This is what we do in production - we have a try-catch block, so if the sub is already there, we ignore the exception.这就是我们在生产中所做的——我们有一个 try-catch 块,所以如果 sub 已经存在,我们将忽略异常。 Make sure to also check the filters if necessary.如有必要,请务必检查过滤器。 They might change (if you change them programmatically, in this case you need to recreate the subscription)它们可能会更改(如果您以编程方式更改它们,在这种情况下您需要重新创建订阅)

    TopicName topic = TopicName.ofProjectTopicName(projectId, this.topic);
    try {
        client.createSubscription("projects/xxx/subscriptions/" + subscriptionId, topic, PushConfig.getDefaultInstance(), 600);
    } catch (AlreadyExistsException e) {
        // sub is already there. nothing to do
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM