Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 37 ยท Getting Started

Hello World: Publish and Consume

Write your first RabbitMQ producer and consumer with Python pika, understand every call, and practice with a runnable in-memory stand-in broker.

Time to send a message. This lesson shows the real Python code for a producer and a consumer using the pika library, explains each call, and then lets you run the same flow against a small in-memory stand-in so you can experiment right here.

The pika blocks are read-only: run them on your machine against a real broker (see Installing and Running RabbitMQ). The runnable blocks use a stand-in broker whose method names copy pika's, but which keeps everything in one Python process.

The producer

Install the client with pip install pika. A producer opens a connection, opens a channel, makes sure the queue exists, and publishes:

Python
# producer.py  (real pika code, read-only)
import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host="localhost")
)
channel = connection.channel()

channel.queue_declare(queue="hello")

channel.basic_publish(
    exchange="",            # the default exchange
    routing_key="hello",    # for the default exchange: the queue name
    body=b"Hello, RabbitMQ!",
)
print("sent")

connection.close()

Step by step:

  1. BlockingConnection opens a TCP connection to the broker. It is a simple, synchronous style of client, ideal for learning.
  2. connection.channel() opens a lightweight channel inside that connection. All your work happens on channels (Connections and Channels explains why).
  3. queue_declare creates the queue hello if it does not exist. Declaring is idempotent: running it again with the same settings changes nothing.
  4. basic_publish sends the message. The empty exchange name "" means the default exchange, which has a special rule: it routes a message to the queue whose name equals the routing key.
  5. The body is bytes. RabbitMQ does not care what is inside: text, JSON, protobuf, an image.

The consumer

Python
# consumer.py  (real pika code, read-only)
import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host="localhost")
)
channel = connection.channel()
channel.queue_declare(queue="hello")      # safe even if the producer did it

def on_message(ch, method, properties, body):
    print("received:", body.decode())

channel.basic_consume(
    queue="hello",
    on_message_callback=on_message,
    auto_ack=True,
)

print("waiting for messages, press Ctrl+C to stop")
channel.start_consuming()

The consumer also declares the queue. This is deliberate: either side may start first, and declaring on both sides guarantees the queue exists. basic_consume registers a callback; RabbitMQ pushes messages to it, and start_consuming() runs the event loop. The callback gets four arguments:

  • ch: the channel.
  • method: delivery details such as the delivery_tag and routing_key.
  • properties: message properties (content type, headers, and so on).
  • body: the payload bytes.

auto_ack=True tells the broker to forget the message as soon as it is delivered. It is convenient for hello-world but unsafe for real work: if your code crashes mid-task, the message is gone. The reliability chapter introduces manual acknowledgements.

sequenceDiagram
    participant P as producer.py
    participant B as RabbitMQ
    participant C as consumer.py
    P->>B: queue_declare("hello")
    P->>B: basic_publish(key="hello")
    C->>B: queue_declare("hello")
    C->>B: basic_consume("hello")
    B-->>C: deliver "Hello, RabbitMQ!"

The message waits in the queue until a consumer subscribes.

Try it: a stand-in broker

The class below is a stand-in. It is not RabbitMQ and implements only what this lesson needs: queues, the default exchange, basic_publish, basic_get and basic_consume. Use it to see the flow, then read the real docs for everything else.

Python Hello world against a stand-in broker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line shows a classic surprise: publishing to the default exchange with a routing key that matches no queue does not raise an error. In real RabbitMQ the message is silently discarded unless you ask for the mandatory flag or use publisher confirms (covered later).

Polling with basic_get

basic_consume pushes messages to you. There is also basic_get, which pulls a single message. It is handy for scripts and tests, but pushing is much more efficient for a long-running service, so use basic_consume in real consumers.

Python Pull one message at a time (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Running it for real

Open two terminals. In the first, run python consumer.py; it waits. In the second, run python producer.py; the consumer prints received: Hello, RabbitMQ!. Now stop the consumer, run the producer three times, then start the consumer again: it receives all three messages. That is the queue buffering work for an absent consumer.

If you open the management UI at port 15672 and look at the Queues tab, you can watch the hello queue's "Ready" count go up while no consumer runs.

Common mistakes

  • Forgetting queue_declare on the consumer: if the consumer starts before the queue exists, basic_consume fails.
  • Declaring a queue with different arguments: re-declaring an existing queue with different settings raises a channel error. Pick settings once.
  • Sending str instead of bytes: encode text with .encode("utf-8").
  • Leaving the connection open in a script: always close() it, or the broker keeps the connection until a heartbeat timeout.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the empty exchange name "" mean in basic_publish?

    The default exchange is nameless and routes a message to the queue whose name equals the routing key.
  2. 2. Why do both producer and consumer call queue_declare?

    Declaring is idempotent, so doing it on both sides removes any dependency on startup order.
  3. 3. What is the risk of auto_ack=True?

    With auto acknowledgement the broker removes the message on delivery, so a crash during processing loses it.
  4. 4. In what type is a message body sent?

    The body is an opaque byte string. You choose the format and encode it yourself.

Summary

  • A producer opens a connection and channel, declares a queue and publishes to an exchange.
  • The default exchange routes by queue name, so routing_key="hello" reaches the queue hello.
  • A consumer registers a callback with basic_consume; basic_get pulls one message.
  • Declare queues on both sides, send bytes, and avoid auto_ack for important work.

Next: Management UI and CLI Tools