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
  6. # In another client, publish a message
  7. dragonfly> PUBLISH news.sports "Breaking News!"
  8. (integer) 1
  9. # Back in the subscribing client
  10. 1) "pmessage"
  11. 2) "news.*"
  12. 3) "news.sports"
  13. 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
  9. # Publish a message to match one of the new patterns
  10. dragonfly> PUBLISH logs.error "An error occurred."
  11. (integer) 1
  12. # Subscriber receives the message
  13. 1) "pmessage"
  14. 2) "logs.*"
  15. 3) "logs.error"
  16. 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.*