0Pricing
RabbitMQ Messaging & Async Systems · Lección

Exchange Fanout para Pub/Sub

Comprenda e implemente el exchange Fanout para difundir mensajes a todas las colas vinculadas. Es ideal para escenarios sencillos de publicación y suscripción.

Exchange Fanout para Pub/Sub es una lección gratuita de RabbitMQ Messaging & Async Systems en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de RabbitMQ Messaging & Async Systems, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de RabbitMQ Messaging & Async Systems incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Pub/Sub & Fanout Explained

Imagine you want to broadcast a message to everyone interested, without knowing who they are. This is the idea behind the Publish/Subscribe (Pub/Sub) messaging pattern.

In RabbitMQ, the Fanout exchange is perfect for this. It acts like a megaphone, shouting your message to all connected listeners.

How Fanout Exchanges Work

A Fanout exchange is the simplest type of exchange. When a message arrives at a Fanout exchange, it doesn't care about routing keys.

  • It takes the message.
  • It duplicates it for every queue that is bound to it.
  • Then, it sends a copy of the message to each of those bound queues.

Think of it as a broadcast to all subscribers.

Key Components

Let's quickly recap the main players:

  • Producer: Sends the message.
  • Exchange: Receives messages from producers and routes them to queues. Fanout is one type.
  • Queue: A buffer that stores messages until a consumer picks them up.
  • Consumer: Receives messages from queues and processes them.

With Fanout, the exchange ensures all bound queues get the message.

Routing Keys Are Ignored

A crucial detail about Fanout exchanges: they completely ignore routing keys!

When a producer sends a message to a Fanout exchange, it might still provide a routing key (often an empty string), but the exchange simply disregards it.

Its only job is to broadcast to all queues bound to it, regardless of any key.

Setting Up the Fanout Exchange

First, our producer needs to declare the Fanout exchange. This tells RabbitMQ to create or ensure this exchange exists.

Notice the "fanout" type parameter. Try running this code to declare your exchange!

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class FanoutProducerSetup {
    private final static String EXCHANGE_NAME = "fanout_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {

            // Declare a fanout exchange
            channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
            System.out.println("Fanout exchange '" + EXCHANGE_NAME + "' declared.");
        }
    }
}

Binding a Queue to Fanout

Consumers don't receive directly from exchanges. They receive from queues. Each consumer needs its own queue, and that queue must be bound to the Fanout exchange.

queueDeclare() with no arguments creates a unique, exclusive, auto-delete queue. The routing key for binding is an empty string, as it's ignored by Fanout.

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class FanoutConsumerSetup {
    private final static String EXCHANGE_NAME = "fanout_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        String queueName = channel.queueDeclare().getQueue(); // A unique, auto-delete queue
        channel.queueBind(queueName, EXCHANGE_NAME, ""); // Bind with empty routing key

        System.out.println("Queue '" + queueName + "' declared and bound to '" + EXCHANGE_NAME + "'.");
        System.out.println("Ready for messages (but not consuming yet).");
    }
}

Publishing to Fanout Exchange

Once the exchange is declared, the producer can send messages to it. Notice how the basicPublish method specifies the exchange name, but the routing key is an empty string.

Run this code after you've set up your exchange. It will publish one message.

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.nio.charset.StandardCharsets;

public class FanoutPublisher {
    private final static String EXCHANGE_NAME = "fanout_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {

            channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); // Ensure exchange exists

            String message = "Hello everyone, this is a broadcast!";
            // Publish to the exchange, routing key is ignored for fanout
            channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes(StandardCharsets.UTF_8));
            System.out.println(" [x] Sent '" + message + "'");
        }
    }
}

Consuming Broadcasts

Now, let's make our consumer actually receive messages. The DeliverCallback defines what happens when a message arrives. Remember, each consumer has its own queue!

To see the broadcast in action, first run two separate instances of this consumer code. Then, run the publisher code from the previous scene. Both consumers should receive the message!

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import java.nio.charset.StandardCharsets;

public class FanoutSubscriber {
    private final static String EXCHANGE_NAME = "fanout_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        String queueName = channel.queueDeclare().getQueue(); // Exclusive, auto-delete queue
        channel.queueBind(queueName, EXCHANGE_NAME, ""); // Bind to fanout exchange

        System.out.println(" [*] Waiting for messages in queue '" + queueName + "'. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + message + "'");
        };
        // Auto-ack set to true for simplicity in this example
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});
    }
}

Fanout in Action

When you ran two consumers and then the publisher, you observed the core concept of Fanout: every active consumer received a copy of the message.

This is because each consumer had its own unique queue, and both queues were bound to the same fanout_logs exchange. The exchange simply duplicated the message to all bound queues.

This makes Fanout ideal for scenarios like real-time logging, notifications, or broadcasting updates.

Test Your Knowledge

Time for a quick check on Fanout exchanges!

Fanout Recap

You've successfully learned about the Fanout exchange!

  • It implements the Pub/Sub pattern.
  • It broadcasts messages to all bound queues.
  • It ignores routing keys when distributing messages.
  • It's perfect for scenarios where multiple consumers need to receive the same message.

Next, we'll explore the Direct exchange, which uses routing keys for more precise message delivery!

Preguntas frecuentes

¿La lección «Exchange Fanout para Pub/Sub» es gratis?

Sí — el texto completo de «Exchange Fanout para Pub/Sub» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de RabbitMQ Messaging & Async Systems, actualiza a CoddyKit PRO. El curso de RabbitMQ Messaging & Async Systems incluye 4 lecciones en total.

¿Qué aprenderé en «Exchange Fanout para Pub/Sub»?

Comprenda e implemente el exchange Fanout para difundir mensajes a todas las colas vinculadas. Es ideal para escenarios sencillos de publicación y suscripción. Practicas RabbitMQ Messaging & Async Systems con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar RabbitMQ Messaging & Async Systems?

No se requiere experiencia previa. RabbitMQ Messaging & Async Systems en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.

¿Cuánto tiempo toma la lección «Exchange Fanout para Pub/Sub»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de RabbitMQ Messaging & Async Systems?

Sí. Cada lección de RabbitMQ Messaging & Async Systems incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Exchange Fanout para Pub/Sub
  2. Exchange Direct para el enrutamiento
  3. Exchange Topic para un enrutamiento flexible
  4. Exchange predeterminado y bindings implícitos
← Volver a RabbitMQ Messaging & Async Systems