微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

kafka python 指定分区消费

 

通过assign、subscribe两者之一为消费者设置消费的主题

consumer = KafkaConsumer(bootstrap_servers=['127.0.0.1:9092'],

                         auto_offset_reset='latest',

                         enable_auto_commit=True, # 自动提交消费数据的offset

                         consumer_timeout_ms= 10000, # 如果1秒内kafka中没有可供消费的数据,自动退出

                         value_deserializer=lambda m: json.loads(m.decode('ascii')), #消费json 格式的消息

                         client_id='consumer-python3'

                         )

 

 

# consumer.assign([TopicPartition('MY_TOPIC1', 0)])

# msg = next(consumer)

# print(msg)

 

consumer.subscribe('MY_TOPIC1')

for msg in consumer:

    print (msg)

 

 

API及常用参数说明:

class kafka.KafkaConsumer(*topics, **configs)

*topics (str) – 可选,设置需要订阅的topic,如果未设置,需要在消费记录前调用subscribe或者assign。

 

client_id (str) – 客户端名称认值: ‘kafka-python-{version}’

 

group_id (str or None) – 消费组名称。如果为None,则通过group coordinator auto-partition分区分配,offset提交被禁用。认为None

 

auto_offset_reset (str) – 重置offset策略: 'earliest'将移动到最老的可用消息, 'latest'将移动到最近消息。 设置为其它任何值将抛出异常。认值:'latest'。

 

enable_auto_commit (bool) –  如果为True,将自动定时提交消费者offset。认为True。

 

auto_commit_interval_ms (int) – 自动提交offset之间的间隔毫秒数。如果enable_auto_commit 为true,认值为: 5000。

 

value_deserializer(可调用对象) - 携带原始消息value并返回反序列化后的value

 

subscribe(topics=(), pattern=None, listener=None)

订阅需要的主题

topics (list) – 需要订阅主题列表

pattern (str) – 用于匹配可用主题的模式,即正则表达式。注意:必须提供topics、pattern两者参数之一,但不能同时提供两者。

 

metrics(raw=False)

获取消费者性能指标。

 

参考API:https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html

原文强参考:https://www.cnblogs.com/shouke/p/10463377.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐