0Pricing
Redis Caching & Messaging (Pub/Sub, Streams) · 课时

按模式匹配订阅

使用 `PSUBSCRIBE` 根据模式订阅多个频道,提升灵活性

按模式匹配订阅 是 CoddyKit 上的免费 Redis Caching & Messaging (Pub/Sub, Streams) 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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 导师)并解锁 Redis Caching & Messaging (Pub/Sub, Streams) 课程的其余内容,请升级到 CoddyKit PRO。 Redis Caching & Messaging (Pub/Sub, Streams) 课程共包含 4 节课。

「按模式匹配订阅」这节课中我会学到什么?

使用 `PSUBSCRIBE` 根据模式订阅多个频道,提升灵活性 你通过在浏览器中直接运行的动手代码来练习 Redis Caching & Messaging (Pub/Sub, Streams),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Redis Caching & Messaging (Pub/Sub, Streams) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Redis Caching & Messaging (Pub/Sub, Streams) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「按模式匹配订阅」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Redis Caching & Messaging (Pub/Sub, Streams) 课中编写并运行代码吗?

能。每节 Redis Caching & Messaging (Pub/Sub, Streams) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 按模式匹配订阅
  2. 设计实时聊天
  3. 事件驱动架构
  4. 在线状态与在线用户跟踪
← 返回 Redis Caching & Messaging (Pub/Sub, Streams)