การสมัครรับตามรูปแบบ
ใช้ `PSUBSCRIBE` เพื่อสมัครรับหลายช่องตามรูปแบบ เพิ่มความยืดหยุ่นในการใช้งาน
การสมัครรับตามรูปแบบ เป็นบทเรียน Redis Caching & Messaging (Pub/Sub, Streams) ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Redis Caching & Messaging (Pub/Sub, Streams) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Redis Caching & Messaging (Pub/Sub, Streams) มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Flexible Subscriptions with Patterns
Welcome to a powerful feature of Redis Pub/Sub: Pattern Matching Subscriptions. Instead of subscribing to a single, exact channel name, you can subscribe to multiple channels using flexible patterns.
This allows your application to listen for a wider range of related messages with a single subscription, making your message handling more dynamic.
Why Use Pattern Matching?
Imagine you have many services, each publishing events to channels like service.auth.login, service.orders.created, or service.inventory.updated.
- Centralized Logging: A single logger service can subscribe to
service.*to catch all events. - Dynamic Event Handling: Easily react to new event types without changing subscription code.
- Microservices: Decouple services further by allowing them to publish to specific sub-channels within a pattern.
PSUBSCRIBE in the Redis CLI
The command for pattern matching is PSUBSCRIBE. Let's see how it works in the Redis CLI.
First, open a Redis CLI client and run:
PSUBSCRIBE log.*The Asterisk (*) Wildcard
The * (asterisk) wildcard is used to match any sequence of characters (including an empty sequence) within a single part of a channel name.
For example, log.* will match log.app, log.system, but not log.web.server because * only matches up to the next . (dot).
If you then publish a message:
PUBLISH log.app "User logged in"The Question Mark (?) Wildcard
The ? (question mark) wildcard matches exactly one character at a specific position.
This is useful when you expect a fixed number of characters, like an ID or a specific status code.
Try this pattern in your CLI:
PSUBSCRIBE device.temp.??Combining Wildcards for Power
You can combine * and ? for even more granular control over your subscriptions. This allows for highly flexible and specific pattern matching.
Consider a pattern like chat.room.*.user.???. This pattern would match channels like chat.room.general.user.001 or chat.room.private.user.abc, but not chat.room.main.user.1 (too few chars for ???).
If a message is published to chat.room.general.user.007, it would be received by the above pattern.
Python `psubscribe` Example
Let's see how to implement pattern subscriptions using a Python client library (redis-py). This subscriber will listen for any message on channels matching events.*.
Run this code first, then the publisher in the next scene:
import redis
import time
r = redis.Redis(decode_responses=True)
pubsub = r.pubsub()
pubsub.psubscribe('events.*')
print("Subscribed to 'events.*'. Listening for 5 seconds...")
start_time = time.time()
for message in pubsub.listen():
if message['type'] == 'pmessage':
print(f"Pattern: {message['pattern']}")
print(f"Channel: {message['channel']}")
print(f"Data: {message['data']}")
if time.time() - start_time > 5: # Listen for 5 seconds
pubsub.punsubscribe('events.*')
break
time.sleep(0.01)
print("Subscriber stopped.")Python Publisher Interaction
Now, run this Python publisher. The messages it sends will be caught by the pattern subscriber you just ran, demonstrating the power of pattern matching.
import redis
import time
r = redis.Redis(decode_responses=True)
print("Publishing messages...")
r.publish('events.user.signup', 'New user: Alice')
time.sleep(0.5)
r.publish('events.product.view', 'Product ID: 12345')
time.sleep(0.5)
r.publish('events.order.placed', 'Order ID: 98765')
time.sleep(0.5)
r.publish('metrics.cpu', 'CPU usage: 85%') # This won't match 'events.*'
print("Messages published.")Real-World Use Cases
Pattern matching subscriptions are incredibly versatile for building real-time applications:
- Monitoring & Analytics: Collect data from various services (e.g.,
metrics.cpu.*,metrics.memory.*). - Notifications: Send alerts for different event types (e.g.,
alert.high_priority.*). - Multi-tenant Systems: Isolate messages for different tenants (e.g.,
tenant.123.events.*). - Dynamic Routing: Route messages to different handlers based on their channel patterns.
Test Your Pattern Skills
A client uses PSUBSCRIBE with the pattern device.*.status.?. Which of these published channel names would it receive messages from?
Recap: Dynamic Pub/Sub
You've learned how Redis PSUBSCRIBE allows for incredibly flexible and dynamic message routing in your applications. By using the * and ? wildcards, you can listen to broad categories of events or very specific sub-channels.
This capability is fundamental for building scalable and decoupled real-time systems, enabling powerful event-driven architectures.
คำถามที่พบบ่อย
บทเรียน “การสมัครรับตามรูปแบบ” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การสมัครรับตามรูปแบบ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Redis Caching & Messaging (Pub/Sub, Streams) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Redis Caching & Messaging (Pub/Sub, Streams) มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การสมัครรับตามรูปแบบ”
ใช้ `PSUBSCRIBE` เพื่อสมัครรับหลายช่องตามรูปแบบ เพิ่มความยืดหยุ่นในการใช้งาน คุณปฏิบัติ Redis Caching & Messaging (Pub/Sub, Streams) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Redis Caching & Messaging (Pub/Sub, Streams) หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Redis Caching & Messaging (Pub/Sub, Streams) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การสมัครรับตามรูปแบบ” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Redis Caching & Messaging (Pub/Sub, Streams) นี้ได้ไหม
ได้ บทเรียน Redis Caching & Messaging (Pub/Sub, Streams) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสมัครรับตามรูปแบบ
- การออกแบบแชตแบบเรียลไทม์
- สถาปัตยกรรมขับเคลื่อนด้วยเหตุการณ์
- การติดตามการมีอยู่และสถานะออนไลน์