Python 多线程编写 Kafka Producer

多线程生产到同一 topic

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import time
import threading
from kafka import KafkaProducer
from traitlets import log


def on_send_success(record_metadata):
    print(record_metadata.topic)
    print(record_metadata.partition)
    print(record_metadata.offset)


def on_send_error(excp):
    log.error('I am an errback', exc_info=excp)
    # handle exception

def send_messag(topic, id, interval_time):

    producer = KafkaProducer(bootstrap_servers=['cdh01:9092', 'cdh02:9092', 'cdh03:9092'])
    while True:
        startTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        message = "|".join((id, startTime, str(interval_time)))

        producer.send(topic, message.encode("utf-8")).add_callback(on_send_success).add_errback(on_send_error)
        # 间隔多长时间生产一条消息
        time.sleep(interval_time)

interval_times = [60, 300, 600, 1200, 1800, 3600]

#开启50个线程
for i in range(0, 50):
    deviceId = "%06d" % random.randint(0, 999999)

    interval_time = times[random.randint(0, len(interval_times) - 1)]

    recv_thread = threading.Thread(target=send_messag, args=("my-topic", id, interval_time))
    
    # 守护主线程,主线程退出后子线程直接销毁
    recv_thread.setDaemon(True)
    recv_thread.start()

while True:
    #主线程一直运行
    time.sleep(5000)   
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
As an AI language model, I don't have the capability to execute Python code. However, I can provide you with an example code snippet for creating a producer using the Confluent Kafka Python library: ``` from confluent_kafka import Producer def delivery_report(err, msg): """ Called once for each message produced to indicate delivery result. Triggered by poll() or flush(). """ if err is not None: print('Message delivery failed: {}'.format(err)) else: print('Message delivered to {} [{}]'.format(msg.topic(), msg.partition())) # Set up configuration properties conf = { 'bootstrap.servers': '<your-bootstrap-server>', 'client.id': 'python-producer' } # Create a Kafka producer instance producer = Producer(conf) # Produce a message to a topic topic = '<your-topic>' message = 'Hello, Kafka!' producer.produce(topic, message.encode('utf-8'), callback=delivery_report) # Wait for any outstanding messages to be delivered and delivery reports to be received producer.flush() ``` In this example, a producer is created using the `Producer()` class of the Confluent Kafka Python library. The `delivery_report()` function is defined to handle delivery reports for produced messages. The producer instance is used to produce a message to a topic using the `produce()` method. The `flush()` method is called to wait for any outstanding messages to be delivered and delivery reports to be received. Note: Make sure to replace `<your-bootstrap-server>` and `<your-topic>` with your actual bootstrap server and topic names, respectively.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值