![](/img/trans.png)
[英]Horizontally Autoscaled Kubernetes pods not pulling messages from Google Cloud Pub/Sub subscription
[英]Reading all the available messages from Google Pub Sub using Go
我正在尝试从 google pub-sub 中的主题获取所有可用消息。 但是在 go 中,一旦 Pub-Sub 中没有更多消息,我无法找到可以取消接收回调的配置。
一种方法我认为是使用谷歌云监视API的discribed在这个答案从PubSub的获取消息的总数谷歌PubSub的-个主题计数的消息,然后保存信息阅读次数的计数,并呼吁取消的话计数等于数字,但我不太确定这是否是继续前进的正确方法。
var mu sync.Mutex
received := 0
sub := client.Subscription(subID)
cctx, cancel := context.WithCancel(ctx)
err = sub.Receive(cctx, func(ctx context.Context, msg *pubsub.Message) {
mu.Lock()
defer mu.Unlock()
fmt.Fprintf(w, "Got message: %q\n", string(msg.Data))
msg.Ack()
received++
if received == TotalNumberOfMessages {
cancel()
}
})
if err != nil {
return fmt.Errorf("Receive: %v", err)
}
我也尝试过使用带有超时的上下文,即在未满足此上下文截止日期之前提取,然后取消。
ctx, cancel := context.WithTimeout(ctx, 100*time.Second)
defer cancel()
err = subscription.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) {
}
但话又说回来,这不会让我确定所有消息都已处理。
请提出一个解决方案,以确保在 Pub-Sub 中没有更多消息时,subscribe.Receive 函数会停止。
我已经在我以前的公司中实现了它(遗憾的是我不再拥有代码,它在我以前的公司 git 中......)。 然而它奏效了。
其原理如下
msg := make(chan *pubsub.Message, 1)
sub := client.Subscription(subID)
cctx, cancel := context.WithCancel(ctx)
go sub.Receive(cctx, func(ctx context.Context, m *pubsub.Message) {
msg <- m
})
for {
select {
case res := <-msg:
fmt.Fprintf(w, "Got message: %q\n", string(res.Data))
res.Ack()
case <-time.After(3 * time.Second):
fmt.Println("timeout")
cancel()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.