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

คิวงาน: การกระจายงานอย่างเป็นธรรม

ใช้งานคิวงานเพื่อกระจายงานไปยังผู้บริโภคหลายรายด้วยกลยุทธ์การจัดส่งแบบวนรอบ เรียนรู้วิธีประมวลผลงานที่ใช้เวลานานแบบไม่พร้อมกัน

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

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

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

Meet Work Queues

Welcome to Work Queues! In distributed systems, you often have tasks that take time to complete, like processing an image or generating a report.

Work Queues are a pattern that helps distribute these time-consuming tasks among multiple workers (consumers) efficiently, preventing any single worker from getting overloaded.

Why Use Work Queues?

Imagine you have many jobs to do, but only one employee. If all jobs go to that single employee, they'll get overwhelmed and tasks will pile up.

  • Load Balancing: Work queues allow you to add more workers to share the load.
  • Asynchronous Processing: The producer doesn't wait for a task to finish, it just adds it to the queue.
  • Reliability: If one worker fails, others can pick up tasks.

How Work Queues Operate

The setup for a work queue is simple:

  • One producer sends messages (tasks) to a single queue.
  • Multiple consumers listen to this same queue.
  • RabbitMQ ensures that each message is delivered to only one of the waiting consumers.

This way, tasks are never duplicated and are processed in parallel.

Fair Dispatch: Round-Robin

By default, RabbitMQ distributes messages to consumers using a round-robin strategy. This means messages are sent to consumers in a rotating fashion:

  • Consumer 1 gets the first message.
  • Consumer 2 gets the second message.
  • Consumer 1 gets the third message, and so on.

This aims for an even distribution of tasks among all active consumers.

The Task Producer

Let's create a producer that sends 10 tasks to our queue. Each task will be a simple string like 'Processing image 1'.

Run this code once to populate the queue with tasks.

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

            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

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

Producer Code Breakdown

What's happening in our producer code?

  • We establish a connection and a channel to interact with RabbitMQ.
  • channel.queueDeclare(QUEUE_NAME, false, false, false, null); ensures the queue exists. The false flags keep it non-durable and non-exclusive for simplicity here.
  • A loop sends 10 messages to the task_queue. Each message represents a distinct task.

Our First Task Consumer

Now, let's create a consumer, which we'll call a 'worker'. This worker will listen for tasks from the task_queue.

We'll simulate a long-running task using Thread.sleep(). Run this code in one terminal window.

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"); // Assuming RabbitMQ is local

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

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

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
            try {
                // Simulate long-running task
                Thread.sleep(1000); // 1 second per task
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                System.out.println(" [x] Done with '" + message + "'");
            }
        };
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});
    }
}

Consumer Code Breakdown

Let's look at the consumer's logic:

  • Similar to the producer, it connects and declares the queue.
  • A DeliverCallback defines the actions when a message arrives.
  • Inside the callback, Thread.sleep(1000) simulates a 1-second task.
  • channel.basicConsume(QUEUE_NAME, true, deliverCallback, ...) starts consuming. The true means messages are automatically acknowledged after delivery.

Scale with Multiple Workers

Here's the core demonstration of work queues:

1. Run the TaskConsumer code in two separate terminal windows (or instances).

2. Then, run the TaskProducer code once.

You will observe that the 10 tasks are divided between your two worker instances, each processing roughly 5 tasks due to RabbitMQ's round-robin dispatch.

Work Queue Quiz

Imagine you have a single RabbitMQ queue and two consumers (Worker A and Worker B) listening to it. A producer sends 4 messages (M1, M2, M3, M4) to this queue.

Which statement accurately describes how the messages are typically distributed using RabbitMQ's default fair dispatch?

Work Queues: Key Takeaways

You've successfully implemented Work Queues, a fundamental pattern for distributing tasks across multiple consumers!

  • Work queues enable asynchronous processing and prevent single points of failure.
  • RabbitMQ's default round-robin dispatch strategy ensures tasks are distributed fairly.
  • By running multiple consumer instances, you can easily scale your task processing capacity.

Next, we'll dive into making your message handling even more robust with acknowledgements and message durability!

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

เรียนรู้ 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 ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “คิวงาน: การกระจายงานอย่างเป็นธรรม” ใช้เวลานานแค่ไหน

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

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

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

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

  1. สวัสดีชาวโลก: คิวอย่างง่าย
  2. คิวงาน: การกระจายงานอย่างเป็นธรรม
  3. การยืนยันข้อความและความคงทน
  4. การเผยแพร่/การสมัครรับด้วย Fanout Exchange
← กลับไปที่ RabbitMQ Messaging & Async Systems