0Pricing
RabbitMQ Messaging & Async Systems · Lesson

Direct Exchange for Routing

Learn how to use the Direct exchange for precise message routing based on a routing key. Route messages to specific queues for targeted processing.

Direct Exchange for Routing is a free RabbitMQ Messaging & Async Systems lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the RabbitMQ Messaging & Async Systems learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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!

Frequently asked questions

Is the “Direct Exchange for Routing” lesson free?

Yes — the full text of “Direct Exchange for Routing” is free to read here on the web, and the RabbitMQ Messaging & Async Systems course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the RabbitMQ Messaging & Async Systems course, upgrade to CoddyKit PRO.

What will I learn in “Direct Exchange for Routing”?

Learn how to use the Direct exchange for precise message routing based on a routing key. Route messages to specific queues for targeted processing. You practise RabbitMQ Messaging & Async Systems with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start RabbitMQ Messaging & Async Systems?

No prior experience is required. RabbitMQ Messaging & Async Systems on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Direct Exchange for Routing” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this RabbitMQ Messaging & Async Systems lesson?

Yes. Every RabbitMQ Messaging & Async Systems lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Fanout Exchange for Pub/Sub
  2. Direct Exchange for Routing
  3. Topic Exchange for Flexible Routing
  4. Default Exchange & Implicit Bindings
← Back to RabbitMQ Messaging & Async Systems