PSUBSCRIBE

Introduction and Use Case(s)

The PSUBSCRIBE command in Redis is used to subscribe to channels using pattern matching. It’s particularly useful for real-time applications where you need to listen to multiple channels that follow a naming convention. Common scenarios include chat applications, live notifications, and monitoring systems where messages are broadcasted on various channels.

Syntax

1. PSUBSCRIBE pattern [pattern ...]

Parameter Explanations

  • pattern: A string pattern to match against channel names. Patterns can include special characters like * which matches any sequence of characters.
  • [pattern ...]: Optional additional patterns to subscribe to multiple patterns at once.

Return Values

Upon issuing the PSUBSCRIBE command, it returns a confirmation in the format:

1. 1) "psubscribe"
2. 2) "pattern"
3. 3) (integer) number_of_subscribed_channels

When a message is published to a matching channel, the client receives a message in the following format:

1. 1) "pmessage"
2. 2) "pattern"
3. 3) "channel"
4. 4) "message"

Code Examples

1. dragonfly> PSUBSCRIBE news.*
2. Reading messages... (press Ctrl-C to quit)
3. 1) "psubscribe"
4. 2) "news.*"
5. 3) (integer) 1

7. # In another client, publish a message
8. dragonfly> PUBLISH news.sports "Breaking News!"
9. (integer) 1

11. # Back in the subscribing client
12. 1) "pmessage"
13. 2) "news.*"
14. 3) "news.sports"
15. 4) "Breaking News!"

If you subscribe to additional patterns:

1. dragonfly> PSUBSCRIBE updates.*, logs.*
2. Reading messages... (press Ctrl-C to quit)
3. 1) "psubscribe"
4. 2) "updates.*"
5. 3) (integer) 2
6. 1) "psubscribe"
7. 2) "logs.*"
8. 3) (integer) 3

10. # Publish a message to match one of the new patterns
11. dragonfly> PUBLISH logs.error "An error occurred."
12. (integer) 1

14. # Subscriber receives the message
15. 1) "pmessage"
16. 2) "logs.*"
17. 3) "logs.error"
18. 4) "An error occurred."

Best Practices

  • Combine PSUBSCRIBE with PUBLISH efficiently by keeping channel patterns simple and predictable.
  • Use pattern subscriptions judiciously to avoid performance overhead from too many pattern matches.

Common Mistakes

  • Subscribing to overly broad patterns which might lead to receiving an excess of unwanted messages.
  • Forgetting to handle the case when no messages are received, leading to potential blocking of the client.

FAQs

Can I use PSUBSCRIBE with other commands?

No, once a client has issued a PSUBSCRIBE command, it enters a mode where it can’t issue other commands until it unsubscribes.

How do I unsubscribe from a pattern?

You can use the PUNSUBSCRIBE command followed by the pattern you want to unsubscribe from.

1. dragonfly> PUNSUBSCRIBE news.*