【问题标题】:How to get the latest offset value from a confluent_python AVRO consumer如何从 confluent_python AVRO 消费者那里获取最新的偏移值
【发布时间】:2018-04-22 16:45:03
【问题描述】:

我对 confluent_kafka 很陌生,但我已经获得了一些使用 kafka-python 的经验。我想要做的是改变开始消费消息的偏移量。这就是为什么我想构建一个消费者客户端,它能够返回到以前的消息,以便返回将填充仪表板的数据。说使用kafka-python包我可以使用seek_to_end(https://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 并且它不会返回我的偏移数值最新和最大的一个。我也可以使用“seek”功能,但我需要一种方法来获取最新偏移量的数值,而不是-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}]

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

【问题讨论】:

  • 如果你想要最新的,你为什么要使用'auto.offset.reset': 'smallest'
  • 你是对的。它应该是 'auto.offset.reset': 'latest'。

标签: python confluent-platform kafka-python


【解决方案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))

【讨论】:

    猜你喜欢
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2016-03-11
    • 2016-03-28
    • 2017-01-20
    • 1970-01-01
    相关资源
    最近更新 更多