python 消費 kafka 數(shù)據(jù)教程
更新時間:2019年12月21日 15:18:46 作者:bigdataf
今天小編就為大家分享一篇python 消費 kafka 數(shù)據(jù)教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
1.安裝python模塊
pip install --user kafka-python==1.4.3
如果報錯壓縮相關的錯嘗試安裝下面的依賴
yum install snappy-devel yum install lz4-devel pip install python-snappy pip install lz4
2.生產者
#!/usr/bin/env python
# coding : utf-8
from kafka import KafkaProducer
import json
def kafkaProducer():
producer = KafkaProducer(bootstrap_servers='ip:9092',value_serializer=lambda v: json.dumps(v).encode('utf-8'))
producer.send('world', {'key1': 'value1'})
if __name__ == '__main__':
kafkaProducer()
2.消費者
from kafka import KafkaConsumer
from kafka.structs import TopicPartition
import time
import click
import ConfigParser
import json
import threading
import datetime
import sched
config = ConfigParser.ConfigParser()
config.read("amon.ini")
@click.group()
def cli():
pass
@cli.command()
@click.option('--topic',type=str)
@click.option('--offset', type=click.Choice(['smallest', 'earliest', 'largest']))
@click.option("--group",type=str)
def client(topic,offset,group):
click.echo(topic)
consumer = KafkaConsumer(topic,
bootstrap_servers=config.get("KAFKA", "Broker_Servers").split(","),
group_id=group,
auto_offset_reset=offset)
for message in consumer:
click.echo(message.value)
# click.echo("%d:%d: key=%s value=%s" % (message.partition,
# message.offset, message.key,
# message.value))
if __name__ == '__main__':
cli()
3.多線程消費
#coding:utf-8
import threading
import os
import sys
from kafka import KafkaConsumer, TopicPartition, OffsetAndMetadata
from collections import OrderedDict
threads = []
class MyThread(threading.Thread):
def __init__(self, thread_name, topic, partition):
threading.Thread.__init__(self)
self.thread_name = thread_name
self.partition = partition
self.topic = topic
def run(self):
print("Starting " + self.name)
Consumer(self.thread_name, self.topic, self.partition)
def stop(self):
sys.exit()
def Consumer(thread_name, topic, partition):
broker_list = 'ip1:9092,ip2:9092'
'''
fetch_min_bytes(int) - 服務器為獲取請求而返回的最小數(shù)據(jù)量,否則請等待
fetch_max_wait_ms(int) - 如果沒有足夠的數(shù)據(jù)立即滿足fetch_min_bytes給出的要求,服務器在回應提取請求之前將阻塞的最大時間量(以毫秒為單位)
fetch_max_bytes(int) - 服務器應為獲取請求返回的最大數(shù)據(jù)量。這不是絕對最大值,如果獲取的第一個非空分區(qū)中的第一條消息大于此值,
則仍將返回消息以確保消費者可以取得進展。注意:使用者并行執(zhí)行對多個代理的提取,因此內存使用將取決于包含該主題分區(qū)的代理的數(shù)量。
支持的Kafka版本> = 0.10.1.0。默認值:52428800(50 MB)。
enable_auto_commit(bool) - 如果為True,則消費者的偏移量將在后臺定期提交。默認值:True。
max_poll_records(int) - 單次調用中返回的最大記錄數(shù)poll()。默認值:500
max_poll_interval_ms(int) - poll()使用使用者組管理時的調用之間的最大延遲 。這為消費者在獲取更多記錄之前可以閑置的時間量設置了上限。
如果 poll()在此超時到期之前未調用,則認為使用者失敗,并且該組將重新平衡以便將分區(qū)重新分配給另一個成員。默認300000
'''
consumer = KafkaConsumer(bootstrap_servers=broker_list,
group_id="test000001",
client_id=thread_name,
enable_auto_commit=False,
fetch_min_bytes=1024 * 1024, # 1M
# fetch_max_bytes=1024 * 1024 * 1024 * 10,
fetch_max_wait_ms=60000, # 30s
request_timeout_ms=305000,
# consumer_timeout_ms=1,
# max_poll_records=5000,
)
# 設置topic partition
tp = TopicPartition(topic, partition)
# 分配該消費者的TopicPartition,也就是topic和partition,根據(jù)參數(shù),每個線程消費者消費一個分區(qū)
consumer.assign([tp])
#獲取上次消費的最大偏移量
offset = consumer.end_offsets([tp])[tp]
print(thread_name, tp, offset)
# 設置消費的偏移量
consumer.seek(tp, offset)
print u"程序首次運行\(zhòng)t線程:", thread_name, u"分區(qū):", partition, u"偏移量:", offset, u"\t開始消費..."
num = 0 # 記錄該消費者消費次數(shù)
while True:
msg = consumer.poll(timeout_ms=60000)
end_offset = consumer.end_offsets([tp])[tp]
'''可以自己記錄控制消費'''
print u'已保存的偏移量', consumer.committed(tp), u'最新偏移量,', end_offset
if len(msg) > 0:
print u"線程:", thread_name, u"分區(qū):", partition, u"最大偏移量:", end_offset, u"有無數(shù)據(jù),", len(msg)
lines = 0
for data in msg.values():
for line in data:
print line
lines += 1
'''
do something
'''
# 線程此批次消息條數(shù)
print(thread_name, "lines", lines)
if True:
# 可以自己保存在各topic, partition的偏移量
# 手動提交偏移量 offsets格式:{TopicPartition:OffsetAndMetadata(offset_num,None)}
consumer.commit(offsets={tp: (OffsetAndMetadata(end_offset, None))})
if True == 0:
# 系統(tǒng)退出?這個還沒試
os.exit()
'''
sys.exit() 只能退出該線程,也就是說其它兩個線程正常運行,主程序不退出
'''
else:
os.exit()
else:
print thread_name, '沒有數(shù)據(jù)'
num += 1
print thread_name, "第", num, "次"
if __name__ == '__main__':
try:
t1 = MyThread("Thread-0", "test", 0)
threads.append(t1)
t2 = MyThread("Thread-1", "test", 1)
threads.append(t2)
t3 = MyThread("Thread-2", "test", 2)
threads.append(t3)
for t in threads:
t.start()
for t in threads:
t.join()
print("exit program with 0")
except:
print("Error: failed to run consumer program")
參考:https://kafka-python.readthedocs.io/en/master/index.html
http://chabaoo.cn/article/176911.htm
以上這篇python 消費 kafka 數(shù)據(jù)教程就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Pytorch出現(xiàn)錯誤Attribute?Error:module?‘torch‘?has?no?attrib
這篇文章主要給大家介紹了關于Pytorch出現(xiàn)錯誤Attribute?Error:module?‘torch‘?has?no?attribute?'_six'解決的相關資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2023-11-11
windows系統(tǒng)多個python中更改默認python版本
這篇文章主要給大家介紹了關于windows系統(tǒng)多個python中更改默認python版本的相關資料,在Python開發(fā)中,不同的項目往往需要使用不同的Python版本,需要的朋友可以參考下2023-09-09

