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

ปลั๊กอินสำหรับข้อความล่าช้า

ใช้งานการส่งข้อความล่าช้าด้วยปลั๊กอิน RabbitMQ Delayed Message Exchange กำหนดเวลาให้ประมวลผลข้อความในอนาคตโดยไม่ต้องสร้างตัวจับเวลาเอง

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

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What are Delayed Messages?

Sometimes you don't want a message processed immediately. Think of sending a reminder email an hour from now, or processing a payment 30 minutes after an order is placed.

Delayed messages allow you to publish a message to RabbitMQ, but tell the broker to hold onto it for a specific duration before delivering it to consumers.

Scheduling Without the Plugin

Without a dedicated feature, scheduling messages can be complex:

  • Custom Timers: You might build your own service with timers, but this adds complexity and a single point of failure.
  • Polling Databases: Storing messages in a database and periodically checking for due times is inefficient.
  • External Schedulers: Using CRON jobs or other external schedulers still requires your application to manage the message state.

RabbitMQ's Delayed Message Plugin simplifies this greatly!

Meet the `x-delayed-message` Plugin

The RabbitMQ Delayed Message Exchange plugin provides a special exchange type that can hold messages and release them after a specified delay.

It acts like a buffer, managing the delay internally without requiring your application to keep track of message timings.

This makes scheduling messages much simpler and more robust.

Delayed Exchange Mechanics

When you publish a message to an `x-delayed-message` exchange, you include a special header: x-delay. This header's value is the delay in milliseconds.

The exchange holds the message until its delay expires. Once expired, the message is routed to queues exactly as if it were a regular message published to an exchange of its original type (e.g., direct, fanout, topic).

Enabling the Plugin (Admin)

Before using it, the plugin must be enabled on your RabbitMQ server. This is typically done via the command line:

rabbitmq-plugins enable rabbitmq_delayed_message_exchange

A server restart might be required for the changes to take effect. Always ensure your broker has the plugin enabled before attempting to use it.

Declaring a Delayed Exchange

To use delayed messages, you first declare an exchange with the type x-delayed-message. You also specify its underlying type (e.g., direct, fanout, topic) which determines how messages are routed after the delay.

Here's how to declare a delayed direct exchange in Java:

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.util.HashMap;
import java.util.Map;

public class DeclareDelayedExchange {
    private static final String EXCHANGE_NAME = "my_delayed_exchange";

    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()) {

            Map<String, Object> args = new HashMap<>();
            args.put("x-delayed-type", "direct"); // Underlying exchange type

            channel.exchangeDeclare(EXCHANGE_NAME, "x-delayed-message", true, false, args);
            System.out.println("Delayed exchange '" + EXCHANGE_NAME + "' declared.");
        }
    }
}

Sending with `x-delay` Header

When publishing to your x-delayed-message exchange, you add an x-delay header to your message properties. The value is an integer representing the delay in milliseconds.

Let's send a message that will be delivered after 5 seconds (5000 milliseconds).

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.util.HashMap;
import java.util.Map;

public class DelayedMessageProducer {
    private static final String EXCHANGE_NAME = "my_delayed_exchange";
    private static final String ROUTING_KEY = "delayed.key";

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

            // Ensure the delayed exchange is declared (from previous scene)
            Map<String, Object> args = new HashMap<>();
            args.put("x-delayed-type", "direct");
            channel.exchangeDeclare(EXCHANGE_NAME, "x-delayed-message", true, false, args);
            System.out.println("Exchange declared (if not exists).");

            String message = "Hello, delayed world!";
            int delayInMs = 5000; // 5 seconds

            Map<String, Object> headers = new HashMap<>();
            headers.put("x-delay", delayInMs); // Set the delay header

            AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
                .headers(headers)
                .build();

            channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, props, message.getBytes("UTF-8"));
            System.out.println(" [x] Sent '" + message + "' with delay " + delayInMs + "ms");
        }
    }
}

Consuming Delayed Messages

Consumers don't need any special logic to receive delayed messages. Once the delay expires, the x-delayed-message exchange routes the message to the bound queues, and consumers receive it like any other message.

The key is that the message arrives at the consumer after the specified delay. You'll need to bind a queue to your delayed exchange with the appropriate routing key.

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

public class DelayedMessageConsumer {
    private static final String EXCHANGE_NAME = "my_delayed_exchange";
    private static final String QUEUE_NAME = "delayed_queue";
    private static final String ROUTING_KEY = "delayed.key";

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

        // Declare the queue and bind it to the delayed exchange
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + message + "' at " + new Date());
        };
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});
    }
}

Common Use Cases

Delayed messages are incredibly useful for:

  • Reminders: Send a notification after a user's trial expires.
  • Scheduled Tasks: Process a batch job at a specific time in the future.
  • Retry Mechanisms: Requeue a failed message to be retried after a delay.
  • Drip Campaigns: Send a series of emails over several days.

They remove the need for complex external scheduling services.

Quick Check: Delayed Message Basics

You've learned how to declare an x-delayed-message exchange and publish messages with a delay. Let's test your understanding.

Recap: Delayed Messages Plugin

In this lesson, you learned about the RabbitMQ Delayed Message Exchange plugin. It allows you to schedule messages to be delivered at a future time.

  • You declare an exchange with type x-delayed-message and an underlying exchange type.
  • You publish messages with an x-delay header (value in milliseconds).
  • Consumers receive these messages normally, but only after the specified delay.

This powerful feature simplifies many time-based messaging patterns.

คำถามที่พบบ่อย

บทเรียน “ปลั๊กอินสำหรับข้อความล่าช้า” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ปลั๊กอินสำหรับข้อความล่าช้า” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส RabbitMQ Messaging & Async Systems ให้อัปเกรดเป็น CoddyKit PRO คอร์ส RabbitMQ Messaging & Async Systems มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ปลั๊กอินสำหรับข้อความล่าช้า”

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

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

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

บทเรียน “ปลั๊กอินสำหรับข้อความล่าช้า” ใช้เวลานานแค่ไหน

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

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

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

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

  1. ปลั๊กอินสำหรับข้อความล่าช้า
  2. ปลั๊กอิน Shovel สำหรับการรวมระบบ
  3. ปลั๊กอิน Federation สำหรับการทำคลัสเตอร์
  4. ปลั๊กอินขจัดข้อความซ้ำและ Consistent Hash Exchange
← กลับไปที่ RabbitMQ Messaging & Async Systems