前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 使用python-kafka类库开发kafka生产者&消费者&客户端

Python 使用python-kafka类库开发kafka生产者&消费者&客户端

作者头像
授客
发布2019-09-10 18:30:16
4.2K0
发布2019-09-10 18:30:16
举报
文章被收录于专栏:授客的专栏授客的专栏

1.测试环境

python 3.4

zookeeper-3.4.13.tar.gz

下载地址1:

http://zookeeper.apache.org/releases.html#download

https://www.apache.org/dyn/closer.cgi/zookeeper/

https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/

下载地址2:

https://pan.baidu.com/s/1dnBgHvySE9pVRZXJVmezyQ

kafka_2.12-2.1.0.tgz

下载地址1:

http://kafka.apache.org/downloads.html

下载地址2:

https://pan.baidu.com/s/1VnHkJgy4iQ73j5rLbEL0jw

pip-18.1.tar.gz

下载地址:https://pan.baidu.com/s/1VpYk8JvMuztzbvEF8mQoRw

说明:实践中发现,pip版本比较旧的话,没法安装whl文件

kafka_python-1.4.4-py2.py3-none-any.whl

下载地址1:

https://pypi.org/project/kafka-python/#files

https://files.pythonhosted.org/packages/5f/89/f13d9b1f32cc37168788215a7ad1e4c133915f6853660a447660393b577d/kafka_python-1.4.4-py2.py3-none-any.whl

下载地址2:

https://pan.baidu.com/s/10XtLXESp64NtwA73RbryVg

python_snappy-0.5.3-cp34-cp34m-win_amd64.whl

下载地址1:

https://www.lfd.uci.edu/~gohlke/pythonlibs/

下载地址2:

https://pan.baidu.com/s/10XtLXESp64NtwA73RbryVg

说明:

kafka-python支持gzip压缩/解压缩。如果要消费lz4方式压缩的消息,则需要安装python-lz4,如果要支持snappy方式压缩/解压缩则需要安装,否则可能会报错:kafka.errors.UnsupportedCodecError: UnsupportedCodecError: Libraries for snappy compression codec not found.

构建生产者对象时,可通过compression_type 参数指定由对应生产者生产的消息数据的压缩方式,或者在producer.properties配置中配置compression.type参数。

参考链接:

https://pypi.org/project/kafka-python/#description

https://kafka-python.readthedocs.io/en/master/install.html#optional-snappy-install

2.代码实践

生产者

#-*- encoding:utf-8 -*-

__author__ = 'shouke'

from kafka import KafkaProducer

import json

producer = KafkaProducer(bootstrap_servers=['127.0.0.1:9092'])

for i in range(0, 100):

producer.send('MY_TOPIC1', value=b'lai zi shouke de msg', key=None, headers=None, partition=None, timestamp_ms=None)

# Block直到单条消息发送完或者超时

future = producer.send('MY_TOPIC1', value=b'another msg',key=b'othermsg')

result = future.get(timeout=60)

print(result)

# Block直到所有阻塞的消息发送到网络

# 注意: 该操作不保证传输或者消息发送成功,仅在配置了linger_ms的情况下有用。(It is really only useful if you configure internal batching using linger_ms

# 序列化json数据

producer = KafkaProducer(bootstrap_servers='127.0.0.1:9092', value_serializer=lambda v: json.dumps(v).encode('utf-8'))

producer.send('MY_TOPIC1', {'shouke':'kafka'})

# 序列化字符串key

producer = KafkaProducer(bootstrap_servers='127.0.0.1:9092', key_serializer=str.encode)

producer.send('MY_TOPIC1', b'shouke', key='strKey')

producer = KafkaProducer(bootstrap_servers='127.0.0.1:9092',compression_type='gzip')

for i in range(2):

producer.send('MY_TOPIC1', ('msg %d' % i).encode('utf-8'))

# 消息记录携带header

producer.send('MY_TOPIC1', value=b'c29tZSB2YWx1ZQ==', headers=[('content-encoding', b'base64'),])

# 获取性能数据(注意,实践发现分区较多的情况下,该操作比较耗时

metrics = producer.metrics()

print(metrics)

producer.flush()

实践中遇到错误: kafka.errors.NoBrokersAvailable: NoBrokersAvailable,解决方案如下:

进入到配置目录(config),编辑server.properties文件,

查找并设置listener,配置监听端口,格式:listeners = listener_name://host_name:port,供kafka客户端连接用的ip和端口,例中配置如下:

listeners=PLAINTEXT://127.0.0.1:9092

API及常用参数说明:

class kafka.KafkaProducer(**configs)

bootstrap_servers –'host[:port]'字符串,或者由'host[:port]'组成的字符串,形如['10.202.24.5:9096', '10.202.24.6:9096', '10.202.24.7:9096']),其中,host为broker(Broker:缓存代理,Kafka集群中的单台服务器)地址,默认值为 localhost, port默认值为9092,这里可以不用填写所有broker的host和port,但必须保证至少有一个broker)

key_serializer (可调用对象) –用于转换用户提供的key值为字节,必须返回字节数据。 如果为None,则等同调用f(key)。 默认值: None.

value_serializer(可调用对象) – 用于转换用户提供的value消息值为字节,必须返回字节数据。 如果为None,则等同调用f(value)。 默认值: None.

send(topic, value=None, key=None, headers=None, partition=None, timestamp_ms=None)

topic(str) – 设置消息将要发布到的主题,即消息所属主题

value(可选) – 消息内容,必须为字节数据,或者通过value_serializer序列化后的字节数据。如果为None,则key必填,消息等同于“删除”。( If value is None, key is required and message acts as a ‘delete’)

partition (int, 可选) – 指定分区。如果未设置,则使用配置的partitioner

key (可选) – 和消息对应的key,可用于决定消息发送到哪个分区。如果平partition为None,则相同key的消息会被发布到相同分区(但是如果key为None,则随机选取分区)(If partition is None (and producer’s partitioner config is left as default), then messages with the same key will be delivered to the same partition (but if key is None, partition is chosen randomly)). 必须为字节数据或者通过配置的key_serializer序列化后的字节数据.

headers (可选) – 设置消息header,header-value键值对表示的list。list项为元组:格式 (str_header,bytes_value)

timestamp_ms (int, 可选) –毫秒数 (从1970 1月1日 UTC算起) ,作为消息时间戳。默认为当前时间

函数返回FutureRecordMetadata类型的RecordMetadata数据

flush(timeout=None)

发送所有可以立即获取的缓冲消息(即时linger_ms大于0),线程block直到这些记录发送完成。当一个线程等待flush调用完成而block时,其它线程可以继续发送消息。

注意:flush调用不保证记录发送成功

metrics(raw=False)

获取生产者性能指标。

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

注:生产者代码是线程安全的,支持多线程,而消费者则不然

消费者

#-*- encoding:utf-8 -*-

__author__ = 'shouke'

from kafka import KafkaConsumer

from kafka import TopicPartition

import json

consumer = KafkaConsumer('MY_TOPIC1', bootstrap_servers=['127.0.0.1:9092'], #auto_offset_reset='', auto_offset_reset='latest',# 消费kafka中最近的数据,如果设置为earliest则消费最早的数据,不管这些数据是否消费 enable_auto_commit=True, # 自动提交消费者的offset auto_commit_interval_ms=3000, ## 自动提交消费者offset的时间间隔 group_id='MY_GROUP1', consumer_timeout_ms= 10000, # 如果10秒内kafka中没有可供消费的数据,自动退出 client_id='consumer-python3' )

for msg in consumer:

print (msg)

print('topic: ', msg.topic)

print('partition: ', msg.partition)

print('key: ', msg.key, 'value: ', msg.value)

print('offset:', msg.offset)

print('headers:', msg.headers)

# Get consumer metrics

metrics = consumer.metrics()

print(metrics)

运行效果

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

客户端

#-*- encoding:utf-8 -*-

__author__ = 'shouke'

from kafka.client import KafkaClient

client = KafkaClient(bootstrap_servers=['127.0.0.1:9092'], request_timeout_ms=3000)

# 获取所有broker

brokers = client.cluster.brokers()

for broker in brokers:

print('broker: ', broker)

print('broker nodeId: ', broker.nodeId)

# 获取主题的所有分区

topic = 'MY_TOPIC1'

partitions = client.cluster.available_partitions_for_topic(topic)

print(partitions)

partition_dict = {}

partition_dict[topic] = [partition for partition in partitions]

print(partition_dict)

运行结果:

broker: BrokerMetadata(nodeId=0, host='127.0.0.1', port=9092, rack=None)

broker nodeId: 0

{0}

{'MY_TOPIC1': [0]}

API及常用参数说明:

class kafka.client.KafkaClient(**configs)

bootstrap_servers –'host[:port]'字符串,或者由'host[:port]'组成的字符串,形如['10.202.24.5:9096', '10.202.24.6:9096', '10.202.24.7:9096']),其中,host为broker(Broker:缓存代理,Kafka集群中的单台服务器)地址,默认值为 localhost, port默认值为9092,这里可以不用填写所有broker的host和port,但必须保证至少有一个broker)

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

request_timeout_ms (int) – 客户端请求超时时间,单位毫秒。默认值: 30000.

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

brokers()

获取所有broker元数据

available_partitions_for_topic(topic)

返回主题的所有分区

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-03-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 生产者
  • 消费者
  • 客户端
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档