我目前正在使用Python进行Kafka集成,而且我是来自PHP背景的Kafka和Python的新手。
我设法让制作人工作但是由于等待来自Kafka的确认,它没有足够快地处理每条消息。
在GitHub页面(https://github.com/Parsely/pykafka)上,有以下示例应该异步处理消息并仍然允许发送报告:
>>> with topic.get_producer(delivery_reports=True) as producer:
... count = 0
... while True:
... count += 1
... producer.produce('test msg', partition_key='{}'.format(count))
... if count % 10**5 == 0: # adjust this or bring lots of RAM ;)
... while True:
... try:
... msg, exc = producer.get_delivery_report(block=False)
... if exc is not None:
... print 'Failed to deliver msg {}: {}'.format(
... msg.partition_key, repr(exc))
... else:
... print 'Successfully delivered msg {}'.format(
... msg.partition_key)
... except Queue.Empty:
... break
我修改了示例,但是从测试中我可以看到第一条消息发送成功,但是抛出了Queue.empty异常。
这是我修改后的代码:
from pykafka import KafkaClient
import Queue
import json
client = KafkaClient(hosts='1.1.1.1:9092')
topic = client.topics['test']
sync = False
# sync = True
if sync:
with topic.get_sync_producer() as producer:
count = 0
while True:
count += 1
producer.produce('Test message ' + str(count))
print 'Sent message ' + str(count)
else:
with topic.get_producer(delivery_reports=True) as producer:
count = 0
while True:
count += 1
if count >= 100:
print 'Processed 100 messages'
break
producer.produce('Test message ' + str(count))
while True:
try:
msg, exc = producer.get_delivery_report(block=False)
if exc is not None:
print 'Failed to deliver msg {}: {}'.format(msg.offset, repr(exc))
else:
print 'Successfully delivered msg {}'.format(msg.offset)
except Queue.Empty:
print 'Queue.empty'
break
输出:
/Users/jim/Projects/kafka_test/env/bin/python /Users/jim/Projects/kafka_test/producer.py
Queue.empty
...
... x100
Processed 100 messages
从检查我的消费者,我可以看到所有100条消息都已成功发送,但我无法告诉我的制作人。
您对如何改进此实施有任何建议吗,更具体地说,我是如何在保持检查邮件成功的能力的同时提高吞吐量的?
答案 0 :(得分:3)
我发现了与此相关的GitHub问题:https://github.com/Parsely/pykafka/issues/291
我通过将min_queued_messages降低到1来解决这个问题。
with topic.get_sync_producer(min_queued_messages=1) as producer:
count = 0
while True:
count += 1
time_start = time.time()
producer.produce('Test message ' + str(count))
time_end = time.time()
print 'Sent message %d, %ss duration' % (count, (time_end - time_start))