0Pricing
RabbitMQ Messaging & Async Systems · Lekcja

Exchange Topic do elastycznego routingu

Opanuj exchange Topic do tworzenia złożonych wzorców routingu z użyciem dopasowywania symboli wieloznacznych. Projektuj elastyczne i skalowalne topologie routingu komunikatów.

Exchange Topic do elastycznego routingu to bezpłatna lekcja RabbitMQ Messaging & Async Systems na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej RabbitMQ Messaging & Async Systems, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs RabbitMQ Messaging & Async Systems zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Często zadawane pytania

Czy lekcja „Exchange Topic do elastycznego routingu” jest bezpłatna?

Tak — pełny tekst „Exchange Topic do elastycznego routingu” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu RabbitMQ Messaging & Async Systems, przejdź na CoddyKit PRO. Kurs RabbitMQ Messaging & Async Systems zawiera 4 lekcji w sumie.

Co nauczysz się w „Exchange Topic do elastycznego routingu”?

Opanuj exchange Topic do tworzenia złożonych wzorców routingu z użyciem dopasowywania symboli wieloznacznych. Projektuj elastyczne i skalowalne topologie routingu komunikatów. Ćwiczysz RabbitMQ Messaging & Async Systems z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć RabbitMQ Messaging & Async Systems?

Nie wymagamy żadnego doświadczenia. RabbitMQ Messaging & Async Systems w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.

Ile czasu zajmuje lekcja „Exchange Topic do elastycznego routingu”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji RabbitMQ Messaging & Async Systems?

Tak. Każda lekcja RabbitMQ Messaging & Async Systems zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Exchange Fanout dla Pub/Sub
  2. Exchange Direct do routingu
  3. Exchange Topic do elastycznego routingu
  4. Domyślny exchange i niejawne bindingi
← Powrót do RabbitMQ Messaging & Async Systems