Here’s an example of an adapter for RabbitMQ using pika with a focus on the topic exchange type:
import pika
import json
class RabbitMQAdapter:
def __init__(self, host='localhost', exchange='my_topic_exchange', queue='my_queue'):
self.host = host
self.exchange = exchange
self.queue = queue
self.connection = None
self.channel = None
def connect(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters(self.host))
self.channel = self.connection.channel()
self.channel.exchange_declare(exchange=self.exchange, exchange_type='topic')
self.channel.queue_declare(queue=self.queue)
self.channel.queue_bind(queue=self.queue, exchange=self.exchange, routing_key='my.routing.key')
def publish(self, routing_key, message):
if self.channel:
self.channel.basic_publish(
exchange=self.exchange,
routing_key=routing_key,
body=json.dumps(message),
properties=pika.BasicProperties(content_type='application/json')
)
print(f"Sent message: {message}")
def consume(self, callback):
if self.channel:
def on_message(ch, method, properties, body):
message = json.loads(body)
callback(message)
ch.basic_ack(delivery_tag=method.delivery_tag)
self.channel.basic_consume(queue=self.queue, on_message_callback=on_message)
print('Waiting for messages...')
self.channel.start_consuming()
def close(self):
if self.connection:
self.connection.close()
# Usage example
def message_handler(message):
print("Received message:", message)
adapter = RabbitMQAdapter()
adapter.connect()
# Publish a message
adapter.publish('my.routing.key', {'key': 'value'})
# Start consuming messages
adapter.consume(message_handler)
Key Features:
- Connection and Channel Setup: The adapter connects to RabbitMQ, declares the topic exchange, and binds a queue with a routing key.
- Publish Method: Publishes messages to the exchange with a specific routing key.
- Consume Method: Listens for messages on the queue and processes them using a callback function.
- Message Serialization: Messages are serialized as JSON when published.
Feel free to expand this with reconnection logic, error handling, or async support based on your specific needs.
Here’s an example of an adapter for RabbitMQ using
pikawith a focus on thetopicexchange type:Key Features:
Feel free to expand this with reconnection logic, error handling, or async support based on your specific needs.