0Pricing
RabbitMQ Messaging & Async Systems · 강의

유연한 라우팅을 위한 Topic 교환기

와일드카드 일치로 복잡한 라우팅 패턴을 구현하는 Topic 교환기를 익힙니다. 유연하고 확장 가능한 메시지 라우팅 토폴로지를 설계합니다.

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

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

Topic Exchange: Flexible Routing

Welcome to the Topic Exchange! This exchange type offers the most flexible message routing, letting you send messages to queues based on complex patterns.

Unlike the simple Fanout or direct-match Direct exchange, Topic exchanges use special wildcards in routing keys to match messages dynamically.

Understanding Topic Routing Keys

With a Topic exchange, routing keys aren't exact matches. They are strings made of words separated by dots (.), much like parts of a filename or URL.

  • Example: animal.rabbit.fast
  • Example: log.error.database

Each word provides a level of detail, allowing for hierarchical routing.

The Single-Word Wildcard: `*`

The asterisk (*) wildcard matches exactly one word in a routing key segment.

  • Binding key: animal.*.fast matches animal.rabbit.fast
  • Binding key: animal.*.fast does not match animal.dog.lazy.fast (too many words)
  • Binding key: *.error.* matches log.error.database

It's great for matching a specific position in the key.

The Zero-or-More Wildcard: `#`

The hash (#) wildcard matches zero or more words in a routing key. It's much more powerful than *.

  • Binding key: log.# matches log.error, log.info.web, log.debug.cache.entry
  • Binding key: animal.# matches animal.rabbit, animal.cat.sleepy

Use # to capture all messages that start with a certain pattern.

Producer: Declaring Topic Exchange

First, our producer needs to declare the Topic exchange. The type is simply "topic".

Try running this snippet to set up the exchange:

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

public class TopicProducerSetup {
    private static final String EXCHANGE_NAME = "topic_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost"); // Connect to local RabbitMQ
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {

            channel.exchangeDeclare(EXCHANGE_NAME, "topic");
            System.out.println("Topic exchange '" + EXCHANGE_NAME + "' declared.");
        }
    }
}

Producer: Sending Messages

Now, let's send some messages using different routing keys. The exchange will use these keys to decide which queues receive the messages.

Notice how the keys are dot-separated, allowing for detailed categories.

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

public class TopicMessageSender {
    private static final String EXCHANGE_NAME = "topic_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, "topic");

            sendMessage(channel, "animal.rabbit.fast", "A fast rabbit runs.");
            sendMessage(channel, "animal.cat.sleepy", "A sleepy cat naps.");
            sendMessage(channel, "log.error.db", "Database connection failed!");
            sendMessage(channel, "log.info.web", "User logged in.");

            System.out.println("Sent various topic messages.");
        }
    }

    private static void sendMessage(Channel channel, String routingKey, String message) throws Exception {
        channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes(StandardCharsets.UTF_8));
        System.out.println(" [x] Sent '" + routingKey + ":'" + message + "'");
    }
}

Consumer: Binding with `*`

Consumers bind their queues to the Topic exchange using binding keys that can contain wildcards. This consumer uses *.orange.*.

It will receive messages like animal.orange.fast but not fruit.apple.sweet or animal.orange.

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

public class TopicConsumerOrange {
    private static final String EXCHANGE_NAME = "topic_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, "topic");
        String queueName = channel.queueDeclare().getQueue();

        String bindingKey = "*.orange.*"; // Matches e.g., 'animal.orange.fast'
        channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
        System.out.println(" [x] Waiting for messages matching: '" + bindingKey + "'");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + delivery.getEnvelope().getRoutingKey() + ":'" + message + "'");
        };
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});
    }
}

Consumer: Binding with `#`

This consumer uses the log.# binding key. This means it will receive all messages whose routing key starts with log., regardless of how many words follow.

This is extremely useful for systems like logging, where you might want a 'catch-all' listener for a category.

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

public class TopicConsumerLogs {
    private static final String EXCHANGE_NAME = "topic_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, "topic");
        String queueName = channel.queueDeclare().getQueue();

        String bindingKey = "log.#"; // Matches e.g., 'log.error.db', 'log.info.web'
        channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
        System.out.println(" [x] Waiting for messages matching: '" + bindingKey + "'");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + delivery.getEnvelope().getRoutingKey() + ":'" + message + "'");
        };
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});
    }
}

Topic Exchange Use Cases

Topic exchanges shine in scenarios requiring flexible and hierarchical routing:

  • Logging Systems: Route logs based on severity, source, and component (e.g., app.error.auth, app.info.payment).
  • Real-time Data Streams: Filter sensor data (e.g., sensor.room1.temp, sensor.room2.humidity).
  • Content Distribution: Deliver news articles to subscribers interested in specific categories or regions.

They provide fine-grained control over message flow.

Topic Routing Challenge

Consider the following messages and binding keys. Which messages will be delivered to a queue bound with the key animal.*.#.fast?

Recap: Topic Exchange Power

You've mastered the Topic exchange! It's an incredibly powerful tool for building flexible and scalable messaging architectures.

  • Uses dot-separated routing keys.
  • * matches exactly one word.
  • # matches zero or more words.
  • Ideal for logging, real-time analytics, and content filtering.

By using wildcards, you can create sophisticated routing rules to ensure messages go exactly where they're needed.

자주 묻는 질문

“유연한 라우팅을 위한 Topic 교환기” 강의는 무료인가요?

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

“유연한 라우팅을 위한 Topic 교환기”에서 뭘 배우나요?

와일드카드 일치로 복잡한 라우팅 패턴을 구현하는 Topic 교환기를 익힙니다. 유연하고 확장 가능한 메시지 라우팅 토폴로지를 설계합니다. 브라우저에서 직접 실행하는 실습 코드로 RabbitMQ Messaging & Async Systems을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“유연한 라우팅을 위한 Topic 교환기” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

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