การกระจายข้อความและการรับส่งแบบ Pub/Sub
นำการอัปเดตแบบเรียลไทม์มาใช้โดยกระจายข้อความไปยังไคลเอ็นต์ที่เชื่อมต่ออยู่ผ่านระบบ Pub/Sub ของ Phoenix
การกระจายข้อความและการรับส่งแบบ Pub/Sub เป็นบทเรียน Elixir & Phoenix: Scalable Backend Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Elixir & Phoenix: Scalable Backend Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Elixir & Phoenix: Scalable Backend Development มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Real-time Updates & Broadcasting
Imagine a chat app or a live dashboard. How do all users see new messages or data instantly?
This magic happens through real-time updates, and a key technique behind it is broadcasting. Broadcasting means sending a message to many recipients at once.
Phoenix Pub/Sub Explained
Phoenix provides a powerful Pub/Sub (Publish/Subscribe) system, built on top of Erlang's distributed capabilities, called Phoenix.PubSub.
- It allows different parts of your application (or even different nodes in a cluster!) to communicate without direct knowledge of each other.
- Think of it as a central message broker: publishers send messages to 'topics', and subscribers receive messages from topics they're interested in.
Topics: Message Channels
In Pub/Sub, a topic is simply a string or atom that categorizes messages. It's like a channel or a subject line for your messages.
- For a chat app, topics might be
"chat_room:lobby"or"user:123:notifications". - Clients (via Phoenix Channels) subscribe to these topics to receive updates.
Subscribing to Topics
Before a process can receive broadcasted messages, it must subscribe to a topic. In Phoenix Channels, when a client joins a channel, the channel process itself often subscribes to relevant Pub/Sub topics.
The function for this is typically Phoenix.PubSub.subscribe(pubsub_server, topic).
Code: Subscribing (Mocked)
Here's how a process would conceptually subscribe to a topic. We use a mock to make it runnable, but Phoenix.PubSub.subscribe works similarly.
defmodule MockPubSub do
def subscribe(topic) do
IO.puts " [MockPubSub] Process #{inspect(self())} subscribing to :#{topic}"
# In a real Phoenix.PubSub, this registers the process.
:ok
end
def broadcast(topic, message) do
IO.puts " [MockPubSub] Broadcasting '#{message}' to :#{topic}"
:ok
end
end
defmodule Main do
def main() do
IO.puts "Starting Subscription Demo..."
# Simulate a process subscribing
spawn(fn ->
MockPubSub.subscribe(:news_feed)
# In a real app, this process would now await messages
end)
Process.sleep(100) # Give time for spawn
IO.puts "Demo complete."
end
endPublishing/Broadcasting Messages
Once processes are subscribed, any part of your application can broadcast a message to a topic. All processes subscribed to that topic will receive the message.
The key function is Phoenix.PubSub.broadcast(pubsub_server, topic, message).
pubsub_server: UsuallyYourApp.PubSub.topic: The topic string or atom.message: Any Elixir term (map, list, string, etc.) to send.
Code: Broadcasting (Mocked)
Let's see how easy it is to broadcast a message using our mock. In a real Phoenix app, you'd use YourApp.PubSub instead of MockPubSub.
defmodule MockPubSub do
def subscribe(topic) do
IO.puts " [MockPubSub] Process #{inspect(self())} subscribing to :#{topic}"
:ok
end
def broadcast(topic, message) do
IO.puts " [MockPubSub] Broadcasting '#{message}' to :#{topic}"
:ok
end
end
defmodule Main do
def main() do
IO.puts "Starting Broadcast Demo..."
# Simulate broadcasting a message to a 'chat_room:general' topic
MockPubSub.broadcast(:"chat_room:general", "Hello everyone in the chat!")
# Another example: sending a notification
MockPubSub.broadcast(:"user:123:notifications", %{type: :new_message, from: "Alice"})
IO.puts "Demo complete."
end
endChannels & Pub/Sub Integration
Phoenix Channels often act as the bridge between client-side WebSockets and the server-side Pub/Sub system.
- When a client sends a message to a channel (e.g., a new chat message), the channel receives it.
- The channel then uses
Phoenix.PubSub.broadcast/3to send that message to the relevant topic. - All other channels subscribed to that topic will receive the broadcast and push it down to their connected clients.
Code: Channel Broadcasting Logic
This snippet shows the core logic within a Phoenix Channel's handle_in/3 callback. Remember, MockPubSub stands in for your actual YourApp.PubSub module.
defmodule MockPubSub do
def broadcast(topic, message) do
IO.puts " [MockPubSub] Broadcasting '#{inspect(message)}' to :#{topic}"
:ok
end
end
defmodule MyAppWeb.ChatChannel do
# This simulates a Phoenix Channel module
@doc "Handles incoming client messages and broadcasts them."
def handle_in("new_msg", %{"body" => msg_body}, socket) do
room_id = "general"
topic = "chat_room:#{room_id}"
# Construct the message to broadcast
full_message = %{sender: "client_user", body: msg_body, timestamp: System.system_time(:millisecond)}
# Broadcast the message to all subscribers of this topic
MockPubSub.broadcast(topic, full_message)
# Acknowledge receipt to the client (in a real channel, this is `{:reply, ...}` or `{:noreply, ...}`)
IO.puts "Channel received message: \"#{msg_body}\". Broadcasting..."
{:noreply, socket} # In a real channel, this would be the return value
end
def main() do
IO.puts "Simulating a client sending a message to a channel..."
# Simulate a call to handle_in
handle_in("new_msg", %{"body" => "Hello from the client!"}, :some_socket_state)
IO.puts "Demo complete."
end
endPub/Sub Flow Check
Consider a Phoenix application. What is the correct sequence of events when a user sends a chat message that needs to be seen by all other users in the same chat room?
Recap: Broadcasting with Pub/Sub
You've learned how Phoenix's Pub/Sub system enables powerful real-time communication!
- Broadcasting sends messages to many recipients via topics.
Phoenix.PubSubis the core module for this.- Processes (like Channels) subscribe to topics to receive messages.
- Any part of your app can broadcast to a topic using
Phoenix.PubSub.broadcast/3. - Phoenix Channels commonly integrate with Pub/Sub to pass client messages to other connected clients.
Next, we'll explore more advanced real-time features like presence tracking!
คำถามที่พบบ่อย
บทเรียน “การกระจายข้อความและการรับส่งแบบ Pub/Sub” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การกระจายข้อความและการรับส่งแบบ Pub/Sub” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Elixir & Phoenix: Scalable Backend Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Elixir & Phoenix: Scalable Backend Development มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การกระจายข้อความและการรับส่งแบบ Pub/Sub”
นำการอัปเดตแบบเรียลไทม์มาใช้โดยกระจายข้อความไปยังไคลเอ็นต์ที่เชื่อมต่ออยู่ผ่านระบบ Pub/Sub ของ Phoenix คุณปฏิบัติ Elixir & Phoenix: Scalable Backend Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Elixir & Phoenix: Scalable Backend Development หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Elixir & Phoenix: Scalable Backend Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การกระจายข้อความและการรับส่งแบบ Pub/Sub” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Elixir & Phoenix: Scalable Backend Development นี้ได้ไหม
ได้ บทเรียน Elixir & Phoenix: Scalable Backend Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- บทนำสู่ Phoenix Channels
- การกระจายข้อความและการรับส่งแบบ Pub/Sub
- การติดตามการมีอยู่และการอัปเดตข้อมูลสด
- การยืนยันตัวตนและการอนุญาตสำหรับ Channel