python3实现定时拉取rabbitmq队列里面的数据,并输出到文件中。
使用pika
,一个Python RabbitMQ客户端库,结合Python的datetime
和json
库来实现定时从RabbitMQ队列中拉取数据,并将数据输出到按当天日期动态生成的文件中。
首先,确保您已经安装了 pika
库。如果尚未安装,可以使用以下命令进行安装:
pip install pika
实现代码如下:
import pika
import datetime
import json
# RabbitMQ连接参数(替换为实际信息)
credentials = pika.PlainCredentials('your_username', 'your_password')
connection_params = pika.ConnectionParameters('localhost', credentials=credentials)
queue_name = 'your_queue_name' # 替换为队列名
# 建立RabbitMQ连接和信道
connection = pika.BlockingConnection(connection_params)
channel = connection.channel()
# 声明队列
channel.queue_declare(queue=queue_name)
# 生成当天日期的文件名
current_date = datetime.datetime.now().strftime("%Y-%m-%d")
output_file = f"data_{current_date}.json"
# 拉取队列中的数据并写入文件
with open(output_file, 'a') as file:
while True:
method_frame, properties, body = channel.basic_get(queue=queue_name, auto_ack=True)
if method_frame:
data = json.loads(body.decode('utf-8'))
file.write(json.dumps(data) + '\n')
else:
break
# 关闭连接
connection.close()