ตัวแลกเปลี่ยน Fanout สำหรับ Pub/Sub
ทำความเข้าใจและใช้งานตัวแลกเปลี่ยน Fanout เพื่อเผยแพร่ข้อความไปยังคิวที่เชื่อมโยงทั้งหมด เหมาะสำหรับสถานการณ์เผยแพร่/สมัครรับข้อมูลแบบง่าย
ตัวแลกเปลี่ยน Fanout สำหรับ Pub/Sub เป็นบทเรียน RabbitMQ Messaging & Async Systems ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน RabbitMQ Messaging & Async Systems และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส RabbitMQ Messaging & Async Systems มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Pub/Sub & Fanout Explained
Imagine you want to broadcast a message to everyone interested, without knowing who they are. This is the idea behind the Publish/Subscribe (Pub/Sub) messaging pattern.
In RabbitMQ, the Fanout exchange is perfect for this. It acts like a megaphone, shouting your message to all connected listeners.
How Fanout Exchanges Work
A Fanout exchange is the simplest type of exchange. When a message arrives at a Fanout exchange, it doesn't care about routing keys.
- It takes the message.
- It duplicates it for every queue that is bound to it.
- Then, it sends a copy of the message to each of those bound queues.
Think of it as a broadcast to all subscribers.
Key Components
Let's quickly recap the main players:
- Producer: Sends the message.
- Exchange: Receives messages from producers and routes them to queues. Fanout is one type.
- Queue: A buffer that stores messages until a consumer picks them up.
- Consumer: Receives messages from queues and processes them.
With Fanout, the exchange ensures all bound queues get the message.
Routing Keys Are Ignored
A crucial detail about Fanout exchanges: they completely ignore routing keys!
When a producer sends a message to a Fanout exchange, it might still provide a routing key (often an empty string), but the exchange simply disregards it.
Its only job is to broadcast to all queues bound to it, regardless of any key.
Setting Up the Fanout Exchange
First, our producer needs to declare the Fanout exchange. This tells RabbitMQ to create or ensure this exchange exists.
Notice the "fanout" type parameter. Try running this code to declare your exchange!
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class FanoutProducerSetup {
private final static String EXCHANGE_NAME = "fanout_logs";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
// Declare a fanout exchange
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
System.out.println("Fanout exchange '" + EXCHANGE_NAME + "' declared.");
}
}
}Binding a Queue to Fanout
Consumers don't receive directly from exchanges. They receive from queues. Each consumer needs its own queue, and that queue must be bound to the Fanout exchange.
queueDeclare() with no arguments creates a unique, exclusive, auto-delete queue. The routing key for binding is an empty string, as it's ignored by Fanout.
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class FanoutConsumerSetup {
private final static String EXCHANGE_NAME = "fanout_logs";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
String queueName = channel.queueDeclare().getQueue(); // A unique, auto-delete queue
channel.queueBind(queueName, EXCHANGE_NAME, ""); // Bind with empty routing key
System.out.println("Queue '" + queueName + "' declared and bound to '" + EXCHANGE_NAME + "'.");
System.out.println("Ready for messages (but not consuming yet).");
}
}Publishing to Fanout Exchange
Once the exchange is declared, the producer can send messages to it. Notice how the basicPublish method specifies the exchange name, but the routing key is an empty string.
Run this code after you've set up your exchange. It will publish one message.
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.nio.charset.StandardCharsets;
public class FanoutPublisher {
private final static String EXCHANGE_NAME = "fanout_logs";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); // Ensure exchange exists
String message = "Hello everyone, this is a broadcast!";
// Publish to the exchange, routing key is ignored for fanout
channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes(StandardCharsets.UTF_8));
System.out.println(" [x] Sent '" + message + "'");
}
}
}Consuming Broadcasts
Now, let's make our consumer actually receive messages. The DeliverCallback defines what happens when a message arrives. Remember, each consumer has its own queue!
To see the broadcast in action, first run two separate instances of this consumer code. Then, run the publisher code from the previous scene. Both consumers should receive the message!
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import java.nio.charset.StandardCharsets;
public class FanoutSubscriber {
private final static String EXCHANGE_NAME = "fanout_logs";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
String queueName = channel.queueDeclare().getQueue(); // Exclusive, auto-delete queue
channel.queueBind(queueName, EXCHANGE_NAME, ""); // Bind to fanout exchange
System.out.println(" [*] Waiting for messages in queue '" + queueName + "'. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
System.out.println(" [x] Received '" + message + "'");
};
// Auto-ack set to true for simplicity in this example
channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});
}
}Fanout in Action
When you ran two consumers and then the publisher, you observed the core concept of Fanout: every active consumer received a copy of the message.
This is because each consumer had its own unique queue, and both queues were bound to the same fanout_logs exchange. The exchange simply duplicated the message to all bound queues.
This makes Fanout ideal for scenarios like real-time logging, notifications, or broadcasting updates.
Test Your Knowledge
Time for a quick check on Fanout exchanges!
Fanout Recap
You've successfully learned about the Fanout exchange!
- It implements the Pub/Sub pattern.
- It broadcasts messages to all bound queues.
- It ignores routing keys when distributing messages.
- It's perfect for scenarios where multiple consumers need to receive the same message.
Next, we'll explore the Direct exchange, which uses routing keys for more precise message delivery!
คำถามที่พบบ่อย
บทเรียน “ตัวแลกเปลี่ยน Fanout สำหรับ Pub/Sub” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ตัวแลกเปลี่ยน Fanout สำหรับ Pub/Sub” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส RabbitMQ Messaging & Async Systems ให้อัปเกรดเป็น CoddyKit PRO คอร์ส RabbitMQ Messaging & Async Systems มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ตัวแลกเปลี่ยน Fanout สำหรับ Pub/Sub”
ทำความเข้าใจและใช้งานตัวแลกเปลี่ยน Fanout เพื่อเผยแพร่ข้อความไปยังคิวที่เชื่อมโยงทั้งหมด เหมาะสำหรับสถานการณ์เผยแพร่/สมัครรับข้อมูลแบบง่าย คุณปฏิบัติ RabbitMQ Messaging & Async Systems ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน RabbitMQ Messaging & Async Systems หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน RabbitMQ Messaging & Async Systems บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “ตัวแลกเปลี่ยน Fanout สำหรับ Pub/Sub” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน RabbitMQ Messaging & Async Systems นี้ได้ไหม
ได้ บทเรียน RabbitMQ Messaging & Async Systems ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ตัวแลกเปลี่ยน Fanout สำหรับ Pub/Sub
- ตัวแลกเปลี่ยน Direct สำหรับการกำหนดเส้นทาง
- ตัวแลกเปลี่ยน Topic สำหรับการกำหนดเส้นทางที่ยืดหยุ่น
- Exchange เริ่มต้นและการผูกโดยนัย