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.
Example 1: Using Redis-Py library to get the number of subscribers for a specific channel.
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.
In this example, there are multiple channels. We loop over them, getting and printing the number of subscribers for each.
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.
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.
PUBSUB NUMSUBcommand include pattern-based subscriptions? No, it only includes the number of subscribers for the specific channels. Use
PUBSUB NUMPATto get the global count of pattern-based subscriptions.