작업 대기열: 공정한 분배
라운드 로빈 분배 전략으로 여러 소비자 사이에 작업을 분산하는 작업 대기열을 구현합니다. 시간이 오래 걸리는 작업을 비동기적으로 처리하는 방법을 학습합니다.
작업 대기열: 공정한 분배은(는) CoddyKit의 무료 RabbitMQ Messaging & Async Systems 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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. Thefalseflags 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
DeliverCallbackdefines 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. Thetruemeans 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!
자주 묻는 질문
“작업 대기열: 공정한 분배” 강의는 무료인가요?
네 — “작업 대기열: 공정한 분배” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 RabbitMQ Messaging & Async Systems 강의 전체를 잠금 해제할 수 있습니다. RabbitMQ Messaging & Async Systems 강의에는 총 4개의 강의가 포함되어 있습니다.
“작업 대기열: 공정한 분배”에서 뭘 배우나요?
라운드 로빈 분배 전략으로 여러 소비자 사이에 작업을 분산하는 작업 대기열을 구현합니다. 시간이 오래 걸리는 작업을 비동기적으로 처리하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 RabbitMQ Messaging & Async Systems을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
RabbitMQ Messaging & Async Systems을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 RabbitMQ Messaging & Async Systems은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“작업 대기열: 공정한 분배” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 RabbitMQ Messaging & Async Systems 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 RabbitMQ Messaging & Async Systems 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Hello World: 간단한 대기열
- 작업 대기열: 공정한 분배
- 메시지 확인과 내구성
- Fanout 익스체인지를 활용한 발행/구독