การยืนยันจากผู้เผยแพร่เพื่อความน่าเชื่อถือ
ใช้งานการยืนยันจากผู้เผยแพร่เพื่อให้แน่ใจว่าข้อความได้รับและประมวลผลโดยโบรกเกอร์เรียบร้อยแล้ว สร้างโปรดิวเซอร์ที่เชื่อถือได้และกู้คืนจากปัญหาเครือข่ายหรือโบรกเกอร์ได้
การยืนยันจากผู้เผยแพร่เพื่อความน่าเชื่อถือ เป็นบทเรียน RabbitMQ Messaging & Async Systems ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน RabbitMQ Messaging & Async Systems และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส RabbitMQ Messaging & Async Systems มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Publisher Confirms?
When you send a message to RabbitMQ, how do you know if it actually arrived safely at the broker?
By default, producers send messages without waiting for any explicit confirmation from RabbitMQ. This is fast, but it means messages could be lost due to network issues or broker failures right after being sent.
Publisher Confirms are a mechanism that allows producers to receive acknowledgements (ACKs) from RabbitMQ when messages have been successfully received and processed by the broker.
The Unseen Gap in Delivery
Imagine sending an important order to a processing queue. Without publisher confirms, your application simply 'sends' the message and moves on.
- What if the network connection drops the message mid-flight?
- What if the RabbitMQ server crashes moments after receiving, but before persisting, your message?
Without a confirmation, your producer would assume success, potentially leading to data loss or inconsistent states in your system.
How Confirm Mode Works
To use publisher confirms, you enable 'confirm mode' on a channel. Once enabled, every message published on that channel is assigned a unique delivery tag.
- ACK (Acknowledgement): The broker sends an ACK back to the producer when a message has been successfully received, routed to its queues, and persisted (if durable).
- NACK (Negative Acknowledgement): The broker sends a NACK if it couldn't process the message (e.g., failed to route, internal error).
This feedback loop closes the 'delivery gap' between producer and broker.
Enabling Confirm Mode
Before publishing messages, you need to tell RabbitMQ that you want to use publisher confirms on your channel. This is a one-time setup for each channel.
Try running this example to see how to enable confirm mode:
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ConfirmSetup {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost"); // Assumes RabbitMQ is running locally
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.confirmSelect(); // This line enables confirm mode
System.out.println("Channel is now in confirm mode.");
// Further publishing code would go here
}
}
}Synchronous Confirms: `waitForConfirms`
One way to use publisher confirms is synchronously. After publishing one or more messages, the producer can call channel.waitForConfirms() or channel.waitForConfirmsOrDie().
- This method blocks the producer until all messages published since the last call have been ACKed or NACKed.
- It's simple to implement but can significantly slow down throughput, as the producer waits for each batch of messages.
- Ideal for low-volume, critical messages where immediate confirmation is paramount.
Sync Confirm Code Example
This example shows a producer sending a single message and then waiting for its confirmation. If the message isn't confirmed within 5 seconds, it times out.
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class SyncConfirmPublisher {
private static final String QUEUE_NAME = "sync_confirm_queue";
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.confirmSelect(); // Enable confirm mode
String message = "Hello, reliable world!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
// Wait for confirmation for up to 5 seconds
if (channel.waitForConfirms(5000)) {
System.out.println("Message confirmed by broker!");
} else {
System.out.println("Message not confirmed within timeout! It might be lost or delayed.");
}
}
}
}Asynchronous Confirms: Listeners
For higher throughput, you can use asynchronous publisher confirms. Instead of blocking, you register a ConfirmListener on the channel.
- The listener has two methods:
handleAck()for successful confirms andhandleNack()for negative confirms. - RabbitMQ delivers ACKs and NACKs to this listener, allowing your producer to continue publishing messages without waiting.
- This approach requires more complex logic to track unconfirmed messages, but offers superior performance for high-volume publishing.
Async Confirm Code Example
This example demonstrates an asynchronous publisher. It registers a listener to handle ACKs and NACKs without blocking the main thread.
Notice the Thread.sleep() to keep the program alive long enough to receive confirmations.
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
public class AsyncConfirmPublisher {
private static final String QUEUE_NAME = "async_confirm_queue";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.confirmSelect(); // Enable confirm mode
// Store unconfirmed messages by their delivery tag
ConcurrentNavigableMap<Long, String> outstandingConfirms = new ConcurrentSkipListMap<>();
channel.addConfirmListener(new ConfirmListener() {
@Override
public void handleAck(long deliveryTag, boolean multiple) throws IOException {
if (multiple) {
// Remove all messages up to this deliveryTag
outstandingConfirms.headMap(deliveryTag + 1).clear();
} else {
outstandingConfirms.remove(deliveryTag);
}
System.out.println(" [x] Message with deliveryTag " + deliveryTag + " ACKed! Remaining: " + outstandingConfirms.size());
}
@Override
public void handleNack(long deliveryTag, boolean multiple) throws IOException {
String message = outstandingConfirms.get(deliveryTag);
System.out.println(" [!] Message '" + message + "' (deliveryTag " + deliveryTag + ") NACKed! Re-sending or logging error.");
// Handle NACK: re-publish, log, etc.
if (multiple) {
outstandingConfirms.headMap(deliveryTag + 1).clear();
} else {
outstandingConfirms.remove(deliveryTag);
}
}
});
String message = "Hello, async reliable world!";
long nextPublishSeqNo = channel.getNextPublishSeqNo();
outstandingConfirms.put(nextPublishSeqNo, message);
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "' (deliveryTag: " + nextPublishSeqNo + ")");
// Keep main thread alive for a moment to receive confirms
Thread.sleep(2000);
}
}
}Sync vs. Async: Choosing Wisely
The choice between synchronous and asynchronous confirms depends on your application's needs:
- Synchronous (
waitForConfirms):- Simpler to implement.
- Lower throughput, as it blocks.
- Good for low-volume, highly critical messages where immediate confirmation is essential.
- Asynchronous (
ConfirmListener):- More complex implementation (requires tracking unconfirmed messages).
- Higher throughput, as it doesn't block.
- Ideal for high-volume message publishing where performance is key.
Confirm Check
You've learned about publisher confirms. Let's see if you can answer this question.
Recap: Reliable Publishing
Congratulations! You've learned how to make your RabbitMQ producers truly reliable using publisher confirms.
- Publisher confirms ensure that messages sent by a producer are successfully received and processed by the RabbitMQ broker.
- You enable confirm mode on a channel using
channel.confirmSelect(). - Synchronous confirms (
waitForConfirms()) are simple but block, suitable for low volume. - Asynchronous confirms (
addConfirmListener()) provide higher throughput for high-volume scenarios, requiring more complex tracking of messages.
By implementing publisher confirms, you can build robust systems that minimize message loss and ensure critical data integrity.
คำถามที่พบบ่อย
บทเรียน “การยืนยันจากผู้เผยแพร่เพื่อความน่าเชื่อถือ” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การยืนยันจากผู้เผยแพร่เพื่อความน่าเชื่อถือ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ 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 ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ข้อความและคิวแบบคงอยู่
- การยืนยันจากผู้เผยแพร่เพื่อความน่าเชื่อถือ
- การตอบรับจากคอนซูเมอร์และการจัดเข้าคิวใหม่
- ธุรกรรมกับการยืนยันจากผู้เผยแพร่