0Pricing
RabbitMQ Messaging & Async Systems · 강의

Headers 교환기 자세히 알아보기

라우팅 키 대신 헤더 속성을 기준으로 메시지를 라우팅하는 Headers 교환기를 살펴봅니다. 더욱 복잡하고 동적인 라우팅 규칙을 구현합니다.

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

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

Headers Exchange: New Routing

Meet the Headers exchange! Unlike Direct or Topic exchanges that use a simple routing_key string, Headers exchanges route messages based on their header attributes.

Think of it as a more flexible way to filter messages, using key-value pairs attached to the message itself.

Routing by Message Headers

When a producer sends a message, it includes a map of key-value pairs (headers). A consumer binds its queue to a Headers exchange with its own set of header rules.

The exchange then compares the message headers to the binding rules to decide where to deliver the message.

Matching Logic: 'all' or 'any'

Headers exchanges use a special argument called x-match in the binding to define the matching logic:

  • "all": The message's headers must contain all the key-value pairs specified in the binding.
  • "any": The message's headers must contain at least one of the key-value pairs specified in the binding.

This gives you powerful control over message delivery!

Producing with Custom Headers

Let's see how a producer adds custom headers to a message. We'll send a simple text message with format: json and type: report headers.

Run this code to send a message:

import com.rabbitmq.client.*;
import java.util.HashMap;
import java.util.Map;

public class HeadersProducer {
    private static final String EXCHANGE = "my_headers_exchange";

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

            channel.exchangeDeclare(EXCHANGE, "headers");

            Map<String, Object> headers = new HashMap<>();
            headers.put("format", "json");
            headers.put("type", "report"); // Add headers

            String msg = "Report Data (JSON)";
            AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
                                            .headers(headers)
                                            .build();
            channel.basicPublish(EXCHANGE, "", props, msg.getBytes("UTF-8"));
            System.out.println(" [x] Sent: '" + msg + "' with headers: " + headers);
        }
    }
}

Consumer 'All' Match Example

This consumer will only receive messages if all its specified headers (format: json AND type: report) are present in the incoming message.

Run this consumer first, then the producer from the previous scene.

import com.rabbitmq.client.*;
import java.util.HashMap;
import java.util.Map;

public class HeadersConsumerAll {
    private static final String EXCHANGE = "my_headers_exchange";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection conn = factory.newConnection();
        Channel channel = conn.createChannel();

        channel.exchangeDeclare(EXCHANGE, "headers");
        String queueName = channel.queueDeclare().getQueue();

        Map<String, Object> bindHeaders = new HashMap<>();
        bindHeaders.put("x-match", "all");
        bindHeaders.put("format", "json");
        bindHeaders.put("type", "report"); // Requires both

        channel.queueBind(queueName, EXCHANGE, "", bindHeaders);
        System.out.println(" [*] Waiting for msgs with ALL: " + bindHeaders);

        DeliverCallback dc = (ct, delivery) -> {
            String msg = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + msg + "' Headers: " + delivery.getProperties().getHeaders());
        };
        channel.basicConsume(queueName, true, dc, ct -> {});
    }
}

Consumer 'Any' Match Example

Now, let's create a consumer that receives messages if any of its specified headers (format: xml OR priority: high) are present.

Run this consumer. Then, try sending messages with different header combinations.

import com.rabbitmq.client.*;
import java.util.HashMap;
import java.util.Map;

public class HeadersConsumerAny {
    private static final String EXCHANGE = "my_headers_exchange";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection conn = factory.newConnection();
        Channel channel = conn.createChannel();

        channel.exchangeDeclare(EXCHANGE, "headers");
        String queueName = channel.queueDeclare().getQueue();

        Map<String, Object> bindHeaders = new HashMap<>();
        bindHeaders.put("x-match", "any");
        bindHeaders.put("format", "xml"); // Matches if format is xml
        bindHeaders.put("priority", "high"); // OR if priority is high

        channel.queueBind(queueName, EXCHANGE, "", bindHeaders);
        System.out.println(" [*] Waiting for msgs with ANY: " + bindHeaders);

        DeliverCallback dc = (ct, delivery) -> {
            String msg = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + msg + "' Headers: " + delivery.getProperties().getHeaders());
        };
        channel.basicConsume(queueName, true, dc, ct -> {});
    }
}

More on `x-match` Values

While "all" and "any" are the primary x-match values, you can also omit x-match. If x-match is not provided, it defaults to "all".

Remember that the header values must match exactly. For example, "type": "report" won't match "type": "Report".

When to Use Headers Exchange

Headers exchanges are great for:

  • Dynamic Routing: When routing logic changes often without code deployments.
  • Complex Filtering: Routing based on multiple, non-hierarchical attributes.
  • Policy-Based Routing: For example, routing high-priority messages to a dedicated queue.

It adds flexibility where routing keys might be too rigid.

Headers vs. Other Exchanges

How does Headers compare?

  • Direct: Routes by exact routing_key match.
  • Topic: Routes by routing_key patterns (wildcards).
  • Headers: Routes by arbitrary message header key-value pairs, offering more attribute-based flexibility.

Choose the exchange type that best fits your message routing needs!

Headers Exchange Quiz

A producer sends a message with headers {"color": "red", "size": "large"}.

Which consumer binding configuration(s) will receive this message?

Lesson Summary

In this lesson, we explored the powerful Headers exchange. You learned:

  • It routes messages based on header key-value pairs.
  • The x-match argument ("all" or "any") controls the matching logic.
  • How to use it for flexible, attribute-based message routing.

This exchange offers a robust alternative to routing keys for complex filtering scenarios.

자주 묻는 질문

“Headers 교환기 자세히 알아보기” 강의는 무료인가요?

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

“Headers 교환기 자세히 알아보기”에서 뭘 배우나요?

라우팅 키 대신 헤더 속성을 기준으로 메시지를 라우팅하는 Headers 교환기를 살펴봅니다. 더욱 복잡하고 동적인 라우팅 규칙을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 RabbitMQ Messaging & Async Systems을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“Headers 교환기 자세히 알아보기” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. Headers 교환기 자세히 알아보기
  2. 교환기 간 바인딩
  3. 배달 못한 편지 교환기(DLX)
  4. 라우팅할 수 없는 메시지를 위한 대체 익스체인지
← RabbitMQ Messaging & Async Systems(으)로 돌아가기