0Pricing
RabbitMQ Messaging & Async Systems · 강의

게시/구독을 위한 Fanout 교환기

Fanout 교환기를 이해하고 구현해 연결된 모든 대기열에 메시지를 브로드캐스트합니다. 간단한 게시/구독 시나리오에 적합한 방식입니다.

게시/구독을 위한 Fanout 교환기은(는) CoddyKit의 무료 RabbitMQ Messaging & Async Systems 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 RabbitMQ Messaging & Async Systems 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. RabbitMQ Messaging & Async Systems 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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!

자주 묻는 질문

“게시/구독을 위한 Fanout 교환기” 강의는 무료인가요?

네 — “게시/구독을 위한 Fanout 교환기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 RabbitMQ Messaging & Async Systems 강의 전체를 잠금 해제할 수 있습니다. RabbitMQ Messaging & Async Systems 강의에는 총 4개의 강의가 포함되어 있습니다.

“게시/구독을 위한 Fanout 교환기”에서 뭘 배우나요?

Fanout 교환기를 이해하고 구현해 연결된 모든 대기열에 메시지를 브로드캐스트합니다. 간단한 게시/구독 시나리오에 적합한 방식입니다. 브라우저에서 직접 실행하는 실습 코드로 RabbitMQ Messaging & Async Systems을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

RabbitMQ Messaging & Async Systems을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 RabbitMQ Messaging & Async Systems은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“게시/구독을 위한 Fanout 교환기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 RabbitMQ Messaging & Async Systems 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 RabbitMQ Messaging & Async Systems 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 게시/구독을 위한 Fanout 교환기
  2. 라우팅을 위한 Direct 교환기
  3. 유연한 라우팅을 위한 Topic 교환기
  4. 기본 익스체인지 및 암시적 바인딩
← RabbitMQ Messaging & Async Systems(으)로 돌아가기