kafka干货(五):kakfka的python客户端----Confluent-kafka

版权声明:本博客所有文章均为原创,如有转载,请注明原文地址,谢谢!----桃花惜春风 https://blog.csdn.net/xiaoyu_BD/article/details/82051993

Confluent-kafka是由Confluent公司维护的一个kafka-client,同产品下还有c/c++,java、Go、.net和JMS。它是企业级支持的一款产品。

coufluent-kafka是Python模块,是对librdkafka的轻量级封装,librdkafka又是基于c/c++的kafka库,性能上不必多说。使用上要优于kafka-python。

参考:kafka干货(四):kafka-python和confluent-kafka比较

安装

首先安装librdkafka

git clone https://github.com/edenhill/librdkafka.git
cd librdkafka/
./configure
make
sudo make install

安装confluent-kafka

pip install confluent-kafka

测试

Producer

from confluent_kafka import Producer

##producer配置,dict格式
p = Producer({'bootstrap.servers': '192.168.56.101,192.168.56.103,192.168.56.102'})

##回调函数
def delivery_report(err, msg):
    if err is not None:
        print('Message delivery failed: {}'.format(err))
    else:
        print('Message delivered to {} [{}]'.format(msg.topic(), msg.partition()))

##发送
for data in ['hello','word’]:
    p.produce('mytopic', data.encode('utf-8'), callback=delivery_report)

p.poll(10)  ##等待返回结果最大时常,单位秒
p.flush() 

参数详解

Producer()
指定生产者配置,参数类型:dict。

len(int)
等待发送的消息数,参数类型:int。

flush(timeout)
发送调用poll(),发送消息,直到len()为0。参数类型:timeout

poll(timeout)
轮询发送消息,并调用相应的返回函数,Callbacks。参数为等待返回的超市时间。

produce()
发送消息,支持回调函数。参数包含:

  1. topic
  2. value
  3. key
  4. partition
  5. on_delivery(err,msg)
  6. timestamp
  7. dict|list

Consumer

from confluent_kafka import Consumer, KafkaError


c = Consumer({
    'bootstrap.servers': '192.168.56.101',
    'group.id': 'mygroup',
    'default.topic.config': {
        'auto.offset.reset': 'smallest'
 }
})

c.subscribe(['mytopic'])

while True:
    msg = c.poll()

    if msg is None:
        continue
    if msg.error():
        if msg.error().code() == KafkaError._PARTITION_EOF:
            continue
        else:
            print(msg.error())
            break

    print('Received message: {}'.format(msg.value().decode('utf-8')))

c.close()

参数详解

Consumer(config)
指定消费者配置,参数类型:dict。bootstrap.servers and group.id是必须配置。

on_commit(err, partitions)
回调函数

close()
关闭消费者,主要有三步:

  1. 停止消费。
  2. 提交偏移量。前提是enable.auto.commit=true。
  3. 离开消费者组。

commit([message=None][, offsets=None][, asynchronous=True])
提交消息或偏移量。如果两者都没有输入,则提交当前分区偏移。前提是enable.auto.commit=true。
asynchronous=True为异步提交,不回会塞。

poll(timeout)
消费消息,参数为等待超时时间。

consume([num_messages=1][, timeout=-1])
批量消费,指定一次消费条数和等待超时时间。返回一个list。关于返回报错:

  1. RuntimeError - 如果消费者已经关闭
  2. KafkaError - 如果出现kafka内部错误
  3. ValueError - 如果num_messages> 1M

pause(partitions)
暂停。

resume(partitions)
恢复。

position(partitions[, timeout=None])
返回分区偏移量。

seek(partition)
指定偏移量消费。参数:TopicPartition(topic[, partition][, offset])。

store_offsets()
提交偏移量。参数:message或offset。前提是enable.auto.offset.store=false。

subscribe(topics[, listener=None])
指定消费的主题。参数:list。可使用正则。包含两个回调函数:

  1. on_assign(consumer, partitions)
  2. on_revoke(consumer, partitions)

unassign()
删除当前分区分配

unsubscribe()
删除订阅


下班了,更多关于序列化/topic操作/配置修改/返回报错处理等更多内容会在近期更新

更多:kafka深入理解专栏
——————————————————————————————————
作者:桃花惜春风
转载请标明出处,原文地址:
https://blog.csdn.net/xiaoyu_BD/article/details/82051993
如果感觉本文对您有帮助,您的支持是我坚持写作最大的动力,谢谢!

猜你喜欢

转载自blog.csdn.net/xiaoyu_BD/article/details/82051993