Getting the Number of Redis Subscribers in Python (Detailed Guide w/ Code Examples)
Use Case(s)
The command PUBSUB NUMSUB <channel>
is used to return the number of subscribers (not counting clients subscribed to patterns) for the specified channels in Redis. This is especially useful in pub/sub scenarios where you need to monitor how many subscribers a certain channel has, for instance, if there are any consumers for the data being published.
Code Examples
Example 1: Using Redis-Py library to get the number of subscribers for a specific channel.
import redis r = redis.Redis(host='localhost', port=6379, db=0) subscribers = r.execute_command('PUBSUB NUMSUB channel-name') print(subscribers)
In this example, we're connecting to a local Redis server on port 6379, then executing a raw Redis command PUBSUB NUMSUB
for the channel-name
. The output will be a list with the channel name and the number of subscribers.
Example 2: When there are multiple channels.
import redis r = redis.Redis(host='localhost', port=6379, db=0) channels = ['channel1', 'channel2', 'channel3'] for channel in channels: subscribers = r.execute_command('PUBSUB NUMSUB', channel) print(f'{channel}: {subscribers[1]}')
In this example, there are multiple channels. We loop over them, getting and printing the number of subscribers for each.
Best Practices
Always ensure that your Redis server is protected and not exposed to the internet. Only trusted clients should be able to connect and issue commands.
Common Mistakes
-
Be careful with your channel names. Redis doesn't check whether a given channel has subscribers before publishing a message, which could lead to data being sent into a void.
-
Ensure that you have proper exception handling around your Redis code. Network-related problems can happen at any time and should be properly handled.
FAQs
- Does the
PUBSUB NUMSUB
command include pattern-based subscriptions? No, it only includes the number of subscribers for the specific channels. UsePUBSUB NUMPAT
to get the global count of pattern-based subscriptions.
Was this content helpful?
Similar Code Examples
- Getting All Keys Matching a Pattern in Redis using Python
- Getting the Length of a Redis List in Python
- Getting Server Info from Redis in Python
- Getting Number of Connections in Redis Using Python
- Getting Current Redis Version in Python
- Getting Memory Stats in Redis using Python
- Redis Get All Databases in Python
- Redis Get All Keys and Values in Python
- Retrieving a Key by Value in Redis Using Python
- Python Redis: Get Config Settings
- Getting All Hash Keys Using Redis in Python
- Getting Current Database in Redis Using Python
Switch & save up to 80%
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost