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

จำนวนข้อความล่วงหน้า (QoS)

กำหนดค่าจำนวนข้อความล่วงหน้า (คุณภาพการให้บริการ) เพื่อควบคุมจำนวนข้อความที่คอนซูเมอร์ได้รับในแต่ละครั้ง เพิ่มประสิทธิภาพคอนซูเมอร์และป้องกันไม่ให้คอนซูเมอร์แต่ละตัวรับภาระมากเกินไป

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

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

Control Message Flow with Prefetch

In a system with multiple consumers, how do you ensure messages are distributed fairly and no single consumer gets overwhelmed?

This lesson introduces the prefetch count, a crucial Quality of Service (QoS) setting in RabbitMQ.

The Challenge: Uneven Workload

By default, RabbitMQ dispatches messages in a round-robin fashion to available consumers. However, it doesn't wait for a consumer to finish processing a message before sending the next one.

If one consumer is slow, it might still receive many messages, while a fast consumer sits idle. This leads to an uneven workload.

Introducing Quality of Service (QoS)

RabbitMQ's Quality of Service (QoS) settings allow you to control how messages are delivered to consumers.

The most common QoS setting is the prefetchCount, which limits the number of unacknowledged messages a consumer can hold at any given time.

How Prefetch Count Works

The prefetch count tells RabbitMQ the maximum number of messages a consumer is willing to process at once.

  • Once a consumer reaches its prefetch limit, RabbitMQ stops delivering new messages to it.
  • It will only send more messages once the consumer acknowledges some of its current messages, bringing the unacknowledged count below the limit.

Implementing Prefetch with `basicQos`

You set the prefetch count using the channel.basicQos() method on the consumer side. The most common value for fair dispatch is 1.

This means a consumer will process one message at a time, acknowledge it, then receive the next.

    // Consumer setup
    Channel channel = connection.createChannel();
    channel.queueDeclare("my_queue", true, false, false, null);

    // Set prefetch count to 1
    channel.basicQos(1, false); // prefetchCount = 1, global = false

    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
        String message = new String(delivery.getBody(), "UTF-8");
        System.out.println(" [x] Received '" + message + "'");
        // Simulate work
        Thread.sleep(1000);
        System.out.println(" [x] Done processing '" + message + "'");
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    };
    channel.basicConsume("my_queue", false, deliverCallback, consumerTag -> {});

Sending Messages to the Queue

Let's create a simple producer that sends several messages to a queue. We'll use this with our QoS-enabled consumer.

Run this code first to populate the queue:

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

public class MessageProducer {
    private final static String QUEUE_NAME = "my_queue";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost"); // Assuming RabbitMQ is on localhost
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);

            for (int i = 0; i < 10; i++) {
                String message = "Task " + i;
                channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
                System.out.println(" [x] Sent '" + message + "'");
            }
        }
    }
}

Consumer with Prefetch in Action

Now, run this consumer code. Notice how basicQos(1) ensures that even if a consumer is slow (due to Thread.sleep), it won't hoard messages.

If you run multiple instances of this consumer, they will share the work more fairly.

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

public class QosConsumer {
    private final static String QUEUE_NAME = "my_queue";

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

        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        // Set prefetch count to 1 for fair dispatch
        channel.basicQos(1, false);

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
            try {
                // Simulate processing time
                Thread.sleep(2000); // 2 seconds per message
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                System.out.println(" [x] Done processing '" + message + "'");
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        };
        channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> {});
    }
}

Key Advantages of Using Prefetch

Using an appropriate prefetch count offers several benefits:

  • Fair Dispatch: Messages are distributed more evenly among competing consumers, preventing a single consumer from getting overloaded.
  • Prevents Consumer Overload: Slower consumers won't accumulate too many messages, reducing memory consumption and potential crashes.
  • Better Resource Utilization: Ensures all active consumers are working efficiently, leading to better overall throughput for the system.

`global` Flag for Channel-Wide QoS

The basicQos() method has an optional global parameter. If set to true, the prefetch count applies to all consumers on that channel.

Generally, it's safer to set global to false (the default) so the prefetch count applies per-consumer. This offers finer control and prevents unexpected behavior.

    // Per-consumer QoS (recommended)
    channel.basicQos(1, false);

    // Channel-wide QoS (use with caution)
    // channel.basicQos(1, true);

Optimizing Your Prefetch Count

The ideal prefetch count depends on your application's specifics. Consider:

  • Message Processing Time: If messages are processed quickly, a higher prefetch count can increase throughput.
  • Consumer Resources: How much memory and CPU can each consumer dedicate to holding and processing messages?
  • Network Latency: For high-latency networks, a slightly higher prefetch can reduce idle time waiting for the next message.

Experimentation is key to finding the optimal balance between throughput and fairness.

Prefetch Count Understanding

Consider two consumers, C1 and C2, both connected to the same queue. C1 processes messages in 5 seconds, C2 in 1 second. If basicQos(1) is set for both, and 10 messages are sent, what is the primary benefit?

Recap: Controlling Message Flow

Great job! You've learned about the prefetch count (QoS) in RabbitMQ.

  • It limits unacknowledged messages a consumer holds.
  • channel.basicQos(1) is common for fair dispatch.
  • It prevents consumer overload and ensures even workload distribution.

Mastering prefetch count is vital for building robust and scalable messaging systems with competing consumers.

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

บทเรียน “จำนวนข้อความล่วงหน้า (QoS)” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “จำนวนข้อความล่วงหน้า (QoS)”

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

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

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

บทเรียน “จำนวนข้อความล่วงหน้า (QoS)” ใช้เวลานานแค่ไหน

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

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

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

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

  1. รูปแบบคอนซูเมอร์แข่งขันกัน
  2. จำนวนข้อความล่วงหน้า (QoS)
  3. คอนซูเมอร์แบบเอกสิทธิ์และลำดับความสำคัญของคอนซูเมอร์
  4. ผู้บริโภคที่ทำงานอยู่เพียงรายเดียว
← กลับไปที่ RabbitMQ Messaging & Async Systems