RabbitMQ is one of the most popular message brokers for building distributed systems. It allows applications to communicate asynchronously by sending and receiving messages through queues. At the heart of RabbitMQ is the concept of an exchange, which decides how messages flow from producers (publishers) to consumers.
This article explains RabbitMQ’s most common exchange types (Default, Direct, Fanout, and Topic) using real Go examples from the repository rabbitmq-example
.
1. Default Exchange
Concept
- The default exchange is a direct exchange with an empty name (
""
). - Messages are routed directly to the queue with the same name as the routing key.
Code Example
default/publisher/main.go
// publish directly to queue "hello" q, _ := ch.QueueDeclare("hello", false, false, false, false, nil) ch.Publish("", q.Name, false, false, amqp.Publishing{ ContentType: "text/plain", Body: []byte("Hello World"), })
default/consumer_1/main.go
q, _ := ch.QueueDeclare("hello", false, false, false, false, nil) msgs, _ := ch.Consume(q.Name, "", true, false, false, false, nil) for d := range msgs { log.Printf("Received: %s", d.Body) }
Diagram
flowchart LR P[Producer] -->|routing key=hello| X((Default Exchange "")) X --> Q[Queue: hello] --> C[Consumer]
2. Direct Exchange
Concept
- Routes messages to queues where the binding key matches exactly the routing key.
- Useful for logs or task routing by category.
Code Example
direct/publisher/main.go
ch.ExchangeDeclare("logs_direct", "direct", true, false, false, false, nil) ch.Publish("logs_direct", "error", false, false, amqp.Publishing{ ContentType: "text/plain", Body: []byte("Error message"), })
direct/consumer_1/main.go
q, _ := ch.QueueDeclare("error_logs", true, false, false, false, nil) ch.QueueBind(q.Name, "error", "logs_direct", false, nil) msgs, _ := ch.Consume(q.Name, "", true, false, false, false, nil) for d := range msgs { log.Printf("[error_logs] %s", d.Body) }
Diagram
flowchart LR P[Producer] -->|routing key=error| X((Direct Exchange: logs_direct)) X -->|bind=error| Qe[Queue: error_logs] --> Ce[Consumer]
Category: RabbitMQ