0Pricing
RabbitMQ Messaging & Async Systems · 강의

라우팅을 위한 Direct 교환기

라우팅 키를 기준으로 메시지를 정확하게 라우팅하는 Direct 교환기의 사용법을 학습합니다. 대상 처리를 위해 메시지를 특정 대기열로 라우팅합니다.

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

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

Introduction to Direct Exchange

Welcome! In this lesson, we'll explore the Direct Exchange in RabbitMQ. It's a powerful tool for sending messages to specific queues based on a routing key.

Think of it like a postal service that delivers letters only to the exact address specified on the envelope.

What is a Routing Key?

A routing key is a string attribute that producers attach to messages. It's essentially an "address" for the message.

  • Producers specify a routing key when publishing.
  • Queues bind to an exchange with one or more routing keys.
  • Messages are delivered to queues whose binding key exactly matches the message's routing key.

How Direct Exchange Works

When a message arrives at a Direct Exchange, it looks at the message's routing key. The exchange then delivers the message to all queues that are bound to it with an identical routing key.

If no queue is bound with that specific routing key, the message is simply discarded by the exchange.

Producer's Role: Sending with Keys

As a producer, you decide the routing key for each message you send. This key determines which consumer (via its bound queue) will receive the message.

This allows for precise control over message delivery, ensuring only relevant consumers get specific types of messages.

Consumer's Role: Binding with Keys

Consumers define their interest in messages by binding their queues to a Direct Exchange using specific routing keys.

A single queue can be bound with multiple routing keys, allowing it to receive messages matching any of those keys.

Code: Producer Setup & Declare

Let's set up a basic producer that uses a Direct Exchange. We'll declare an exchange named "direct_logs" with type "direct".

This code establishes a connection and channel, then declares the exchange.

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

public class DirectProducerSetup {
    private static final String EXCHANGE_NAME = "direct_logs";

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

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

            channel.exchangeDeclare(EXCHANGE_NAME, "direct");
            System.out.println("Exchange '" + EXCHANGE_NAME + "' declared.");

            // In a real app, you'd send messages here
            // For this setup example, we just declare.
        }
    }
}

Code: Producer Sending Message

Now, let's send a message to our "direct_logs" exchange. We'll specify a routing key, for example, "error".

Run this code after ensuring your RabbitMQ server is running. It will publish a message with the specified key.

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

public class DirectProducerSend {
    private static final String EXCHANGE_NAME = "direct_logs";

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

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

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

            String routingKey = "error";
            String message = "A critical error occurred!";

            channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes(StandardCharsets.UTF_8));
            System.out.println(" [x] Sent '" + routingKey + ":'" + message + "'");
        }
    }
}

Code: Consumer Setup & Binding

On the consumer side, we'll create a queue and bind it to the "direct_logs" exchange using the routing key "error".

This consumer will only receive messages published with the "error" routing key. Run this consumer first, then the producer.

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

public class DirectConsumerError {
    private static final String EXCHANGE_NAME = "direct_logs";

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

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

        channel.exchangeDeclare(EXCHANGE_NAME, "direct");

        String queueName = channel.queueDeclare().getQueue(); // Create a non-durable, exclusive, auto-delete queue
        String bindingKey = "error";
        channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);

        System.out.println(" [*] Waiting for messages with routing key '" + bindingKey + "'. To exit press CTRL+C");

        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 -> {});
    }
}

Multiple Bindings & Use Cases

A single queue can bind to the same Direct Exchange with multiple routing keys. For instance, a "critical alerts" queue might bind to both "error" and "warning" keys to receive both types of messages.

Direct exchanges are perfect for scenarios like:

  • Distributing logs based on severity (e.g., info, warn, error).
  • Routing internal system events to specific processing modules.
  • Targeting updates to particular user segments.

Quick Check: Direct Routing

Consider a Direct Exchange named "my_exchange".

  • Queue A is bound with routing key "report".
  • Queue B is bound with routing key "alert".
  • Queue C is bound with routing keys "report" and "update".

A producer sends a message to "my_exchange" with the routing key "report".

Recap: Direct Exchange

Great job! You've learned about the Direct Exchange in RabbitMQ.

  • It routes messages based on an exact match of the routing key.
  • Producers attach a routing key to each message.
  • Consumers bind their queues to the exchange with specific routing keys to receive relevant messages.
  • This pattern allows for precise, targeted message delivery.

Next, we'll explore the Fanout Exchange, which broadcasts messages to all bound queues, regardless of routing key!

자주 묻는 질문

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

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

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

라우팅 키를 기준으로 메시지를 정확하게 라우팅하는 Direct 교환기의 사용법을 학습합니다. 대상 처리를 위해 메시지를 특정 대기열로 라우팅합니다. 브라우저에서 직접 실행하는 실습 코드로 RabbitMQ Messaging & Async Systems을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

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

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

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

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

이 강의의 모든 강의

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