通过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 Non