簡體   English   中英

Python Kafka - 文件中的最大消息數

[英]Python Kafka - max messages in file

有沒有辦法只獲取一條消息,將其保存到文件中,然后終止腳本? 我想循環播放,以便將每條消息保存到一個單獨的文件中。 從 cmd 級別,我有一個參數:

max-messages 1 

但是在 python 中我還沒有發現這樣的東西。 代碼如下:

from kafka import KafkaConsumer
import sys
import datetime

now_day = datetime.datetime.now().strftime("%Y-%m-%d")
print(now_day)

directory = "D:/Kafka/test/files_" + now_day + "/earnix_topic_"
print(directory)

now_datetime = datetime.datetime.now().strftime("%Y-%m-%d_%H%M")
print("Current date: " + now_datetime)

full_path = directory + now_datetime + ".txt"
print(full_path)

bootstrap_servers = ['prod-kafka-wrk01:0000','prod-kafka-wrk02:0001','prod-kafka-wrk03:0003']

# Define topic name from where the message will recieve
topicName = 'notify.products.client.topic'

consumer = KafkaConsumer(topicName,  group_id ='groupABasdsadC',bootstrap_servers = bootstrap_servers)

# Read and print message from consumer
for msg in consumer:
   file = open(full_path, "w+")
   file.write(str(msg.value))
   file.close()

sys.exit()

如果__getitem__()使用__iter__()

for msg in consumer:
  #do something...

您可以使用內置的next() function,它也將使用__iter__()方法:

msg = next(consumer)

有關 python 可迭代類型的更多信息,請參閱: https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Iterables.html

或者您可以忽略迭代器適配器並使用poll(...)方法,該方法將返回主題中當前的較小消息列表。 參見https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html

如果只想使用一條記錄並結束腳本,則需要將sys.exit()縮進到循環中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM