프리페치 개수(QoS)
프리페치 개수(Quality of Service)를 구성하여 소비자가 한 번에 수신하는 메시지 수를 제어합니다. 소비자 효율성을 최적화하고 개별 소비자에 작업이 과도하게 몰리는 것을 방지합니다.
프리페치 개수(QoS)은(는) CoddyKit의 무료 RabbitMQ Messaging & Async Systems 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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)” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 RabbitMQ Messaging & Async Systems 강의 전체를 잠금 해제할 수 있습니다. RabbitMQ Messaging & Async Systems 강의에는 총 4개의 강의가 포함되어 있습니다.
“프리페치 개수(QoS)”에서 뭘 배우나요?
프리페치 개수(Quality of Service)를 구성하여 소비자가 한 번에 수신하는 메시지 수를 제어합니다. 소비자 효율성을 최적화하고 개별 소비자에 작업이 과도하게 몰리는 것을 방지합니다. 브라우저에서 직접 실행하는 실습 코드로 RabbitMQ Messaging & Async Systems을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
RabbitMQ Messaging & Async Systems을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 RabbitMQ Messaging & Async Systems은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“프리페치 개수(QoS)” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 RabbitMQ Messaging & Async Systems 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 RabbitMQ Messaging & Async Systems 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 경쟁 소비자 패턴
- 프리페치 개수(QoS)
- 전용 소비자 및 소비자 우선순위
- 단일 활성 소비자