如何从confluent_python AVRO使用者获取最新的偏移值

时间:2018-04-22 16:45:03

标签: python confluent-kafka kafka-python

我对confluent_kafka很新,但我已经获得了一些kafka-python的经验。我想要做的是改变偏移开始消费消息的位置。这就是为什么我想构建一个能够移回以前的消息的消费者客户端,以便返回将填充仪表板的数据。说使用kafka-python包我可以使用seek_to_endhttps://github.com/dpkp/kafka-python/blob/c0fddbd24269d4333e3b6630a23e86ffe33dfcb6/kafka/consumer/group.py#L788)方法来获取最新提交的位置值。我可以使用seek方法(https://github.com/dpkp/kafka-python/blob/c0fddbd24269d4333e3b6630a23e86ffe33dfcb6/kafka/consumer/group.py#L738)减去值并返回之前的消息

另一方面,conflient_kafka似乎没有类似的功能,到目前为止我发现的是使用值为-1的变量OFFSET_END并且它不会返回偏移量最新和最大的数值。我可以使用'寻找'功能也是如此,但我需要一种方法来获得最新偏移的数值,而不是-1

我的avro消费者看起来像

from confluent_kafka.avro import AvroConsumer

if __name__ == '__main__':
     c = AvroConsumer({"bootstrap.servers": "locahost:29092", "group.id":"mygroup",'schema.registry.url': 'http://localhost:8081',
                  'enable.auto.commit': True,'default.topic.config': {'auto.offset.reset': 'smallest'}})

def my_assign (consumer, partitions):
    for p in partitions:
        p.offset = confluent_kafka.OFFSET_END
        print("offset=",p.offset)
    print('assign', partitions)
    print('position:',consumer.position(partitions))
    consumer.assign(partitions)

c.subscribe(["mytopic"],on_assign=my_assign)

while True:
    m = c.poll(1)
    if m is None:
        continue

    if m.error() is None:
        print('Received message', m.value(),m.offset())
c.close()

产生以下结果:

offset= -1
assign [TopicPartition{topic=mytopic,partition=0,offset=-1,error=None}]
position: [TopicPartition{topic=mytopic,partition=0,offset=-1001,error=None}]

并等待下一条消息。我想知道是否有人可以帮助我。谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用Consumer.get_watermark_offsets(请参阅docs

示例:

cfg = {
    # ... ...
    "group.id": str(uuid4())
}
consumer = AvroConsumer(cfg)
topic_partition = TopicPartition("topic-name", partition=123)
low, high = consumer.get_watermark_offsets(topic_partition)
print("the latest offset is {}".format(high))