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

รูปแบบคอนซูเมอร์แข่งขันกัน

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

บทเรียน 1 จาก 411 ขั้นตอน

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

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

Scaling with Competing Consumers

Welcome! In distributed systems, you often need to process many tasks efficiently. The Competing Consumers pattern is a powerful way to achieve this.

It allows you to scale your message processing capacity by simply adding more workers.

How Competing Consumers Work

Imagine a single queue of tasks. Instead of one worker taking all tasks, multiple workers (consumers) listen to this same queue.

  • Each message is delivered to only one of the competing consumers.
  • Consumers "compete" to receive the next available message.
  • This distributes the workload automatically.

Key Benefits of the Pattern

The Competing Consumers pattern offers several advantages:

  • Scalability: Easily increase processing power by adding more consumer instances.
  • Reliability: If one consumer fails, others can pick up its share of messages.
  • Load Balancing: Messages are spread across available consumers, balancing the workload.
  • Decoupling: Producers don't need to know how many consumers there are or where they are.

Producer: Sending Tasks

Let's set up a basic producer that sends messages (tasks) to a queue named task_queue. Each message will be a simple string.

Run this code to send a few messages:

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

public class TaskProducer {
    private final static String QUEUE_NAME = "task_queue";

    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()) {
            // Declare a durable queue
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);

            for (int i = 0; i < 10; i++) {
                String message = "Task " + (i + 1);
                channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
                System.out.println(" [x] Sent '" + message + "'");
                Thread.sleep(100); // Small delay to visualize
            }
        }
    }
}

Consumer 1: Processing Tasks

Now, let's create our first consumer. It will connect to task_queue and start processing messages. Each message will be acknowledged after simulating work.

Run this consumer in a terminal:

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

public class TaskConsumer {
    private final static String QUEUE_NAME = "task_queue";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        System.out.println(" [*] Consumer 1 waiting for messages.");

        // Basic QoS: Prefetch 1 message at a time to ensure fair dispatch
        channel.basicQos(1);

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

Running Multiple Consumers

To truly see the competing consumers pattern in action, open a new terminal window and run the exact same TaskConsumer code again.

You'll now have two consumer instances listening to the task_queue. Run the producer code (from Scene 4) once more. Observe how messages are now distributed between both consumer instances, demonstrating how they compete for messages and share the workload!

RabbitMQ's Dispatching Logic

By default, RabbitMQ uses a round-robin dispatching mechanism when multiple consumers are connected to the same queue. This means messages are sent to consumers sequentially.

  • Consumer 1 gets message 1.
  • Consumer 2 gets message 2.
  • Consumer 1 gets message 3, and so on.

The basicQos(1) setting in our consumer code is crucial here. It tells RabbitMQ not to send more than one unacknowledged message to a consumer at a time, ensuring fair dispatch even if consumers process at different speeds.

Common Use Cases

The Competing Consumers pattern is ideal for scenarios like:

  • Image processing: Multiple workers resizing images from a queue.
  • Email sending: Sending bulk emails without overwhelming a single service.
  • Log processing: Analyzing large volumes of logs in parallel.
  • Background jobs: Any task that can be processed independently by multiple workers.

Important Considerations

When using competing consumers, keep these in mind:

  • Message Ordering: If strict message order is critical, this pattern might not be suitable directly, as messages can be processed out of order by different consumers.
  • Idempotency: Consumers should ideally be idempotent. This means processing the same message multiple times should have the same effect as processing it once. This is vital for fault tolerance and retries.

Competing Consumers Quiz

Test your understanding of the Competing Consumers pattern.

Recap: Competing Consumers

Great job! You've learned about the Competing Consumers pattern:

  • It enables multiple consumers to process messages from a single queue.
  • It's excellent for scaling and load balancing message processing.
  • RabbitMQ's default round-robin dispatch and QoS settings facilitate fair distribution.
  • Consider idempotency and potential out-of-order processing for specific use cases.

Next, we'll dive deeper into optimizing consumer efficiency with prefetch counts!

เริ่มต้นได้ฟรี

เรียนรู้ RabbitMQ Messaging & Async Systems ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
11
บทเรียน
44

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

บทเรียน “รูปแบบคอนซูเมอร์แข่งขันกัน” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “รูปแบบคอนซูเมอร์แข่งขันกัน”

ใช้งานรูปแบบคอนซูเมอร์แข่งขันกัน เพื่อให้คอนซูเมอร์หลายตัวประมวลผลข้อความจากคิวเดียวกันได้ เพิ่มขีดความสามารถในการประมวลผลด้วยการเพิ่มคอนซูเมอร์ คุณปฏิบัติ 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. จำนวนข้อความล่วงหน้า (QoS)
  3. คอนซูเมอร์แบบเอกสิทธิ์และลำดับความสำคัญของคอนซูเมอร์
  4. ผู้บริโภคที่ทำงานอยู่เพียงรายเดียว
← กลับไปที่ RabbitMQ Messaging & Async Systems