rabbitMQ demo

worker.py
`

import pika
import time
import json
import signal
import sys

def callback(ch, method, properties, body):
    data = json.loads(body)
    print(f"Received task: {data}")
    # 模拟任务处理时间
    time.sleep(5)
    print("Task done.")
    ch.basic_ack(delivery_tag=method.delivery_tag)

def shutdown_handler(channel, connection):
    def handler(signum, frame):
        print("\nShutting down gracefully...")
        # 停止消费
        channel.stop_consuming()
        # 关闭连接
        connection.close()
        print("\ngracefully down...\n")
        sys.exit(0)
    return handler

connection = pika.BlockingConnection(pika.ConnectionParameters("host", 5672, "/", pika.PlainCredentials("admin", "admin")))
channel = connection.channel()
channel.queue_declare(queue="task_queue", durable=True)
channel.basic_qos(prefetch_count=1)


signal.signal(signal.SIGINT, shutdown_handler(channel, connection))
signal.signal(signal.SIGTERM, shutdown_handler(channel, connection))


channel.basic_consume(queue="task_queue", on_message_callback=callback)

print(" [*] Waiting for messages. To exit press CTRL+C")
channel.start_consuming()

`

main.py
`from fastapi import FastAPI, Request
import pika
import json

app = FastAPI()

def send_to_rabbitmq(message: dict):
connection = pika.BlockingConnection(pika.ConnectionParameters("host", 5672, "/", pika.PlainCredentials("admin", "admin")))
channel = connection.channel()
channel.queue_declare(queue="task_queue", durable=True)
channel.basic_publish(
exchange='',
routing_key='task_queue',
body=json.dumps(message),
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
)
)
connection.close()

@app.post("/submit")
async def submit_task(request: Request):
data = await request.json()
send_to_rabbitmq(data)
return {"status": "submitted", "data": data}
`

posted @ 2025-06-04 09:54  Python喵  阅读(12)  评论(0)    收藏  举报