0Pricing
Redis Caching & Messaging (Pub/Sub, Streams) · 강의

패턴 일치 구독

`PSUBSCRIBE`를 활용해 패턴에 따라 여러 채널을 구독하고 유연성을 높입니다.

패턴 일치 구독은(는) CoddyKit의 무료 Redis Caching & Messaging (Pub/Sub, Streams) 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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.

자주 묻는 질문

“패턴 일치 구독” 강의는 무료인가요?

네 — “패턴 일치 구독” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Redis Caching & Messaging (Pub/Sub, Streams) 강의 전체를 잠금 해제할 수 있습니다. Redis Caching & Messaging (Pub/Sub, Streams) 강의에는 총 4개의 강의가 포함되어 있습니다.

“패턴 일치 구독”에서 뭘 배우나요?

`PSUBSCRIBE`를 활용해 패턴에 따라 여러 채널을 구독하고 유연성을 높입니다. 브라우저에서 직접 실행하는 실습 코드로 Redis Caching & Messaging (Pub/Sub, Streams)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Redis Caching & Messaging (Pub/Sub, Streams)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Redis Caching & Messaging (Pub/Sub, Streams)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“패턴 일치 구독” 강의는 얼마나 걸리나요?

대부분의 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)(으)로 돌아가기