python消费kafka性能_python中kafka生产者和消费者实现

Python

Python开发

Python语言

python中kafka生产者和消费者实现

CgpOIF5EAWWAQ0y_AAcB-fDz9P0878.png

安装kafka-python:

C:anaconda3Scripts>pip install kafka-python

import datetime

import json

from kafka import KafkaProducer

from kafka import KafkaConsumer

from kafka.errors import KafkaError

'''

使用kafka-python的生产模块

'''

class Kafka_producer():

def __init__(self, bootstrapServers, kafkaTopic):

self.bootstrapServers = bootstrapServers

self.kafkaTopic = kafkaTopic

self.producer = KafkaProducer(bootstrap_servers=self.bootstrapServers)

def sendjsondata(self, params):

try:

parmas_message = json.dumps(params)

producer = self.producer

future = producer.send(self.kafkaTopic, parmas_message.encode('utf-8'))

producer.flush()

recordMetadata = future.get(timeout=10)

print(recordMetadata, datetime.datetime.now().strftime('%Y%m%d%H%M%S'))

except KafkaError as e:

print(e)

'''

使用Kafka-python的消费模块

'''

class Kafka_consumer():

def __init__(self, bootstrapServers, kafkaTopic, groupId):

self.kafkaTopic = kafkaTopic

self.bootstrapServers = bootstrapServers

self.groupId = groupId

self.consumer = KafkaConsumer(self.kafkaTopic, group_id=self.groupId, bootstrap_servers=self.bootstrapServers)

def consume_data(self):

try:

for message in self.consumer:

yield message

except BaseException as e:

print(e)

if __name__ == '__main__':

bootstrapServers = ['ip1:port1', 'ip2:port2', 'ip3:port3']

topicStr = '主题'

print('-' * 20)

print('生产者')

print('-' * 20)

producer = Kafka_producer(bootstrapServers, topicStr)

for id in range(5):

params = '{tst}:{null}---' + str(id)

producer.sendjsondata(params)

print('-' * 20)

print('消费者')

print('-' * 20)

groupId = 'group名称'

consumer = Kafka_consumer(bootstrapServers, topicStr, groupId)

message = consumer.consume_data()

for i in message:

print(i.value)

内容来源于网络,如有侵权请联系客服删除

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值