Sobes.tech
Junior — Middle

How does message passing occur in the RabbitMQ system?

sobes.tech AI

Answer from AI

In RabbitMQ, message transmission occurs through exchanges and queues. The process looks like this:

  1. Producer sends a message to an exchange.
  2. The exchange, based on routing rules (routing key, binding), directs the message to one or more queues.
  3. Consumer subscribes to a queue and receives messages from it.

Main types of exchanges:

  • Direct — routes messages based on exact key match.
  • Fanout — broadcasts messages to all bound queues.
  • Topic — routes based on key pattern matching.
  • Headers — routes based on message headers.

Example of sending a message using pika (Python client for RabbitMQ):

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='logs', exchange_type='fanout')

message = 'Hello RabbitMQ!'
channel.basic_publish(exchange='logs', routing_key='', body=message)

print(" [x] Sent 'Hello RabbitMQ!'")
connection.close()

Thus, RabbitMQ provides reliable and flexible message routing between system components.