Skip to main content
 首页 » 编程设计

python之汇合卡夫卡: Consumer does not read from beginning for all partitions in a topic

2024年10月01日6java哥

我有一个包含 40 个分区的主题。设置是这样的:

def on_assign (c,ps): 
    for p in ps: 
        p.offset=0 
    print ps 
    c.assign(ps) 
 
conf = {'bootstrap.servers': 'localhost:9092' 
        'enable.auto.commit' : False, 
        'group.id' : 'confluent_consumer', 
        'default.topic.config': {'auto.offset.reset': 'earliest'} 
        } 
consumer = Consumer(**conf) 
consumer.subscribe(['topic.source'], on_assign=on_assign) 
 
msg = consumer.poll(timeout=100000) 
print "Topic is %s: | Partition is %d: | Offset is : %d | key is :%s " % (msg.topic(), msg.partition(), msg.offset(), msg.key()) 

我想从偏移量 0 开始读取主题 topic.source 的所有分区。但我没有看到它发生在所有分区上。对于某些分区,它从一个特定的偏移量读取,我假设这是提交的偏移量,每次更改 group.id 也无济于事。无论提交的偏移量如何,如何从头开始读取该主题的所有分区?

我在 on_assign() 中打印了 ps,它为所有 40 个分区打印了如下内容:

[TopicPartition{topic=topic.source,partition=0,offset=0,error=None},TopicPartition{topic=topic.source,partition=1,offset=0,error=None}....] and so on 

请您参考如下方法:

如果您将 group.id 设置为新值,或者使用尚未提交任何偏移量的组,并且 auto.offset.reset 设置为 earliest 然后消费者将从分区的开头开始。

也就是说,开头可能不是偏移量 0。根据代理的日志保留设置,Kafka 可以删除消息,因此分区中的第一条可用消息可以位于任何偏移量。