0Pricing
RabbitMQ Messaging & Async Systems · บทเรียน

เจาะลึกตัวแลกเปลี่ยน Headers

ทำความรู้จักตัวแลกเปลี่ยน Headers สำหรับกำหนดเส้นทางข้อความตามแอตทริบิวต์ส่วนหัวแทนคีย์เส้นทาง พร้อมใช้งานกฎการกำหนดเส้นทางที่ซับซ้อนและปรับเปลี่ยนได้มากขึ้น

เจาะลึกตัวแลกเปลี่ยน Headers เป็นบทเรียน RabbitMQ Messaging & Async Systems ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส RabbitMQ Messaging & Async Systems ให้อัปเกรดเป็น CoddyKit PRO คอร์ส RabbitMQ Messaging & Async Systems มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “เจาะลึกตัวแลกเปลี่ยน Headers”

ทำความรู้จักตัวแลกเปลี่ยน Headers สำหรับกำหนดเส้นทางข้อความตามแอตทริบิวต์ส่วนหัวแทนคีย์เส้นทาง พร้อมใช้งานกฎการกำหนดเส้นทางที่ซับซ้อนและปรับเปลี่ยนได้มากขึ้น คุณปฏิบัติ RabbitMQ Messaging & Async Systems ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน RabbitMQ Messaging & Async Systems หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน RabbitMQ Messaging & Async Systems บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “เจาะลึกตัวแลกเปลี่ยน Headers” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน RabbitMQ Messaging & Async Systems นี้ได้ไหม

ได้ บทเรียน RabbitMQ Messaging & Async Systems ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. เจาะลึกตัวแลกเปลี่ยน Headers
  2. การเชื่อมโยงตัวแลกเปลี่ยนเข้าด้วยกัน
  3. ตัวแลกเปลี่ยนจดหมายตีกลับ (DLX)
  4. Exchange สำรองสำหรับข้อความที่กำหนดเส้นทางไม่ได้
← กลับไปที่ RabbitMQ Messaging & Async Systems