python 向kafka写数据

python 生产者

#import datetime
import time
import random
import schedule
from json import dumps
from faker import Faker
from kafka import KafkaProducer

kafka_nodes = "kafka:9092"
myTopic = "weather"

def gen_data():
    faker = Faker()
    prod = KafkaProducer(bootstrap_servers=kafka_nodes, value_serializer=lambda x:dumps(x).encode('utf-8'))
    my_data = {'city': faker.city(), 'temperature': random.uniform(10.0, 110.0)}
    prod.send(topic=myTopic, value=my_data)
    prod.flush()

schedule.every(2).seconds.do(gen_data)
while True:
    schedule.run_pending()
    time.sleep(0.5)

console 消费者

root@cb5907ae28c1:/# kafka-console-consumer.sh --topic weather --bootstrap-server localhost:9092 --from-beginning
{"city": "North Christopher", "temperature": 67.95115029391047}
{"city": "South Abigail", "temperature": 70.31666431169052}
{"city": "New Maryside", "temperature": 83.09965808226785}
{"city": "Reedside", "temperature": 65.03686535720038}
{"city": "Angelatown", "temperature": 104.81254312810289}
{"city": "Nelsonton", "temperature": 47.46181347087175}
{"city": "Port Mary", "temperature": 72.64499201774528}
{"city": "Bruceton", "temperature": 26.50020679433758}
{"city": "South Eric", "temperature": 102.74213254833768}
{"city": "Lake Patricia", "temperature": 99.37267854651625}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颹蕭蕭

白嫖?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值