[英]How to get consumer group offsets for partition in Golang Kafka 10
现在,Golang Kafka 库 (sarama) 提供了消费者组功能,而没有任何外部库对 kafka 10 的帮助。如何在任何给定时间获取消费者组正在处理的当前消息偏移量?
以前我使用 kazoo-go ( https://github.com/wvanbergen/kazoo-go ) 来获取我的消费者组消息偏移量,因为它存储在 Zookeeper 中。 现在我使用 sarama-cluster ( https://github.com/bsm/sarama-cluster ),我不确定使用哪个 API 来获取我的消费者组消息偏移量。
在后台, consumerGroupSession
结构使用PartitionOffsetManager
来获取下一个偏移量:
if pom := s.offsets.findPOM(topic, partition); pom != nil {
offset, _ = pom.NextOffset()
}
这是pom.NextOffset()的文档。
当一个consumerGroupSession
通过newConsumerGroupClaim()
方法构造一个consumerGroupClaim
结构时,它传递偏移量,由pom.NextOffset()
返回,作为offset
参数。 您可以稍后通过claim.InitialOffset()
访问它。 开始消费消息后,可以使用当前处理的消息的message.Offset
。
不幸的是, consumerGroupSession.offsets.findPOM()
不能从ConsumerGroupHandler.ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim)
方法访问,因为它接收 session 作为ConsumerGroupSession
interface ,而不是作为consumerGroupSession
struct 。 所以 offsets 变量是私有的,不可访问。
因此,我们无法真正访问NextOffset()
方法,该方法正是 OP 想要的。
这是获取消费者组偏移量(即消费者组将开始的偏移量)的示例代码:
package main
import (
"context"
"log"
"strings"
"github.com/Shopify/sarama"
)
func main() {
groupName := "testgrp"
topic := "topic_name"
offset, e := GetCGOffset(context.Background(), "localhost:9092", groupName, topic)
if e != nil {
log.Fatal(e)
}
log.Printf("Consumer group %s offset for topic %s is: %d", groupName, topic, offset)
}
type gcInfo struct {
offset int64
}
func (g *gcInfo) Setup(sarama.ConsumerGroupSession) error {
return nil
}
func (g *gcInfo) Cleanup(sarama.ConsumerGroupSession) error {
return nil
}
func (g *gcInfo) ConsumeClaim(_ sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
g.offset = claim.InitialOffset()
return nil
}
func GetCGOffset(ctx context.Context, brokers, groupName, topic string) (int64, error) {
config := sarama.NewConfig()
config.Consumer.Offsets.AutoCommit.Enable = false // we're not going to update the consumer group offsets
client, err := sarama.NewConsumerGroup(strings.Split(brokers, ","), groupName, config)
if err != nil {
return 0, err
}
info := gcInfo{}
if err := client.Consume(ctx, []string{topic}, &info); err != nil {
return 0, err
}
return info.offset, nil
}
我自己一直在做这方面的工作。 正如@boris-burkov 提到的,您无法访问 getPOM 方法,但是,您可以自己创建一个 POM 并调用 NextOffset() 来获取当前消费者的实际偏移量:
offsetManager, _ := sarama.NewOffsetManagerFromClient(clientName, cl.Client)
offsetPartitionManager, _ := offsetManager.ManagePartition("test-topic", 0)
offsetPartitionManager.NextOffset()
我还与 Sarama 和 Kafka 合作以抵消某个主题。
您可以使用以下代码获得偏移量。
package main
import (
"gopkg.in/Shopify/sarama"
"fmt"
)
func main(){
client , err := sarama.Client([]string{"localhost:9092"},nil) // I am not giving any configuration
if err != nil {
panic(err)
}
lastoffset, err := client.GetOffset("topic-test",0,sarama.OffsetNewest)
if err != nil {
panic(err)
}
fmt.Println("Last Commited Offset ",lastoffset)
}
让我知道这是否是您正在寻找的答案以及它是否有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.