kafka 使用python消费consumer

参考

python kafka 使用
大数据:kafka常见问题
kafka
python之操作kafka

Kafka基本了解

使用python读取consumer中的数据

安装kafka-python

pip install kafka-python

简单使用

import kafka import KafkaConsumer
#消费kafka中最新的数据 并且自动提交offsets[消息的偏移量]
consumer = KafkaConsumer('my-topic',group_id='my-group',bootstrap_servers=['localhost:9092'])
for message in consumer:
    #注意: message ,value都是原始的字节数据,需要decode
    #例如: message.value.decode('utf-8')
    #完成对每条数据中的操作
    print ("%s:%d:%d: key=%s value=%s" %s (message.topic, message.partition,
                                               message.offset, message.key,
                                               message.value))

其他使用

topic="****"
groupid="****"
brokerlist="*:9092,*:9092"

#读取目前可读最早的消息
consumer = KafkaConsumer(topic, auto_offset_reset='earliest', bootstrap_servers=brokerlist)
#获取topic主题的分区信息
consumer.partitions_for_topic(topic)  
#获取主题列表
print consumer.topics()  
#获取当前消费者订阅的主题
print consumer.subscription()  
#获取当前消费者topic、分区信息
print consumer.assignment()  
#获取当前消费者可消费的偏移量
print consumer.beginning_offsets(consumer.assignment()) 
#重置偏移量,从第5个偏移量消费
consumer.seek(TopicPartition(topic=topic, partition=0), 5)
#获取当前主题的最新偏移量
print consumer.position(TopicPartition(topic=u'test', partition=0)) 

#消费多个主题
consumer = KafkaConsumer(bootstrap_servers=brokerlist)
consumer.subscribe(topics=('test','test0'))  #订阅要消费的主题
for message in consumer:
。。。。

#手动拉取消息
while True:
    msg = consumer.poll(timeout_ms=5)   #从kafka获取消息
    print msg
    time.sleep(1)

#消息挂起与恢复
consumer.pause(TopicPartition(topic=u'test', partition=0))
print consumer.paused()   #获取当前挂起的消费者
#处理操作
consumer.resume(TopicPartition(topic=u'test', partition=0))
#pause执行后,consumer不能读取,直到调用resume后恢复。
  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值