75 lines
2.2 KiB
Python
75 lines
2.2 KiB
Python
"""RabbitMQ message sender"""
|
|
import pika
|
|
import json
|
|
from typing import Any, Dict
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class RabbitMQSender:
|
|
"""Generic RabbitMQ sender for publishing messages to queues"""
|
|
|
|
def __init__(self, host: str = 'localhost', port: int = 5672):
|
|
self.host = host
|
|
self.port = port
|
|
|
|
def send_message(self, queue_name: str, message: Dict[str, Any]) -> bool:
|
|
"""
|
|
Sends a message to a RabbitMQ queue
|
|
|
|
Args:
|
|
queue_name: Name of the queue to send to
|
|
message: Dictionary containing the message data
|
|
|
|
Returns:
|
|
True if successful, False otherwise
|
|
"""
|
|
try:
|
|
connection = pika.BlockingConnection(
|
|
pika.ConnectionParameters(host=self.host, port=self.port)
|
|
)
|
|
channel = connection.channel()
|
|
|
|
# Declare queue to ensure it exists
|
|
channel.queue_declare(queue=queue_name, durable=True)
|
|
|
|
# Convert message to JSON
|
|
message_json = json.dumps(message)
|
|
|
|
# Publish the message
|
|
channel.basic_publish(
|
|
exchange='',
|
|
routing_key=queue_name,
|
|
body=message_json,
|
|
properties=pika.BasicProperties(
|
|
delivery_mode=pika.spec.PERSISTENT_DELIVERY_MODE
|
|
)
|
|
)
|
|
|
|
connection.close()
|
|
logger.info(f"Message sent to queue '{queue_name}': {message_json}")
|
|
return True
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error sending message to RabbitMQ: {e}")
|
|
return False
|
|
|
|
|
|
def send_to_queue(queue_name: str, message: Dict[str, Any],
|
|
host: str = 'localhost', port: int = 5672) -> bool:
|
|
"""
|
|
Convenience function to send a message to RabbitMQ
|
|
|
|
Args:
|
|
queue_name: Name of the queue
|
|
message: Message dictionary
|
|
host: RabbitMQ host
|
|
port: RabbitMQ port
|
|
|
|
Returns:
|
|
True if successful, False otherwise
|
|
"""
|
|
sender = RabbitMQSender(host=host, port=port)
|
|
return sender.send_message(queue_name, message)
|