Sobes.tech
Junior — Middle

How does the message sender and receiver interact in RabbitMQ?

sobes.tech AI

Answer from AI

In RabbitMQ, the interaction between the message sender (producer) and the receiver (consumer) occurs through an intermediary — a message broker. The sender publishes messages to a queue or an exchange, and the receiver subscribes to the queue and receives messages from it.

Main steps:

  1. The sender connects to RabbitMQ and sends a message to the exchange.
  2. The exchange routes the message to one or more queues according to the rules (binding).
  3. The receiver connects to the queue and receives the messages, processing them.

This allows asynchronous data exchange, relieving components and increasing system reliability.

Example in Python using pika:

import pika

# Sender
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
channel.basic_publish(exchange='', routing_key='task_queue', body='Hello World!')
connection.close()

# Receiver
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)

def callback(ch, method, properties, body):
    print(f"Received {body.decode()}")
    ch.basic_ack(delivery_tag=method.delivery_tag)

channel.basic_consume(queue='task_queue', on_message_callback=callback)
channel.start_consuming()