To perform concurrent operations like publishing and consuming in separate threads, pass the rabbitpy.Connection object to your worker threads. Inside each thread, use connection.channel() to create a thread-local channel. This ensures that each thread operates on its own isolated AMQP channel, maintaining protocol safety.
import rabbitpy
import threading
EXCHANGE = 'threading_example'
QUEUE = 'threading_queue'
ROUTING_KEY = 'test'
MESSAGE_COUNT = 100
def consumer(connection):
"""Consume MESSAGE_COUNT messages then exit."""
received = 0
# Create a dedicated channel for this thread
with connection.channel() as channel:
for message in rabbitpy.Queue(channel, QUEUE):
print(message.body)
message.ack()
received += 1
if received == MESSAGE_COUNT:
break
def publisher(connection):
"""Publish MESSAGE_COUNT messages."""
# Create a dedicated channel for this thread
with connection.channel() as channel:
for index in range(MESSAGE_COUNT):
message = rabbitpy.Message(channel, f'Message #{index}')
message.publish(EXCHANGE, ROUTING_KEY)
with rabbitpy.Connection() as connection:
# Setup topology in the main thread
with connection.channel() as channel:
exchange = rabbitpy.Exchange(channel, EXCHANGE)
exchange.declare()
queue = rabbitpy.Queue(channel, QUEUE)
queue.declare()
queue.bind(EXCHANGE, ROUTING_KEY)
kwargs = {'connection': connection}
consumer_thread = threading.Thread(target=consumer, kwargs=kwargs)
consumer_thread.start()
publisher_thread = threading.Thread(target=publisher, kwargs=kwargs)
publisher_thread.start()
consumer_thread.join()