python消费kafka某个topic某个分区的数据

from confluent_kafka import Consumer, TopicPartition

kafka_ip_port = 'ip:port'
consumer = Consumer({
        'bootstrap.servers': kafka_ip_port,
        'group.id': 'test_group',
        'auto.offset.reset': 'earliest'
})

topics = consumer.list_topics().topics

# print(topics, type(topics))
# topic_name = list(topics.keys())[0]

topic_name = 'your_topic_name'

topic_meta = topics[topic_name]

# partitions = list(topic_meta.partitions.keys())
# partition = partitions[0]

partition = 2

print(f'prepare to consume topic: {topic_name}, partition: {partition}')

consumer.assign([TopicPartition(topic=topic_name, partition=partition, offset=0)])

messages = consumer.consume(num_messages=5, timeout=5)

for message in messages:
    if message.error():
        print(f"consume error: {message.error()}")
        continue
    print(f'offset: {message.offset()}, key: {message.key().decode()}, value: {message.value().decode()}')

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值