3. Fanout Exchange
Concept
- Sends every message to all queues bound to the exchange.
- Ignores routing keys.
- Good for broadcast scenarios (notifications, pub/sub).
Code Example
fanout/publisher/main.go
ch.ExchangeDeclare("logs_fanout", "fanout", true, false, false, false, nil) ch.Publish("logs_fanout", "", false, false, amqp.Publishing{ ContentType: "text/plain", Body: []byte("Broadcast log"), })
fanout/consumer_1/main.go
q, _ := ch.QueueDeclare("", false, false, true, false, nil) // auto-generated queue ch.QueueBind(q.Name, "", "logs_fanout", false, nil) msgs, _ := ch.Consume(q.Name, "", true, false, false, false, nil) for d := range msgs { log.Printf("[fanout consumer] %s", d.Body) }
Diagram
flowchart LR P[Producer] --> F((Fanout Exchange: logs_fanout)) F --> Q1[Queue: c1] --> C1[Consumer1] F --> Q2[Queue: c2] --> C2[Consumer2] F --> Q3[Queue: c3] --> C3[Consumer3]
4. Topic Exchange
Concept
- Routes messages based on pattern-matching in the routing key.
- Supports wildcards:
*
matches one word.#
matches zero or more words.
- Good for event-driven systems where events have hierarchical names.
Code Example
topic/publisher/main.go
ch.ExchangeDeclare("logs_topic", "topic", true, false, false, false, nil) ch.Publish("logs_topic", "order.us.created", false, false, amqp.Publishing{ ContentType: "text/plain", Body: []byte("Order created in US"), })
topic/consumer_1/main.go
q, _ := ch.QueueDeclare("us_orders", true, false, false, false, nil) ch.QueueBind(q.Name, "order.us.*", "logs_topic", false, nil) msgs, _ := ch.Consume(q.Name, "", true, false, false, false, nil) for d := range msgs { log.Printf("[us_orders] %s", d.Body) }
Diagram
flowchart LR P[Producer] -->|order.us.created| T((Topic Exchange: logs_topic)) T -->|bind=order.us.*| Q1[Queue: us_orders] --> C1[Consumer1] T -->|bind=order.#| Q2[Queue: all_orders] --> C2[Consumer2]
Category: RabbitMQ