Search code examples
python-2.7redispublish-subscribe

PUBSUB CHANNELS returns empty list


I have a python programme as below

import json
import threading

import redis

CHANNELS_PREFIX = 'client'


class Listener(threading.Thread):
    STOP = 1
    CONTINUE = 0

    def __init__(self, r):
        threading.Thread.__init__(self)
        self.redis = r
        self.pubsub = self.redis.pubsub()
        self.pubsub.psubscribe(["%s:*" % CHANNELS_PREFIX])

    def reload(self, data):
        print "Reloaing", data
        return Listener.CONTINUE

    def shutdown(self, data):
        self.pubsub.unsubscribe()
        print "unsubscribed and finished"
        return Listener.STOP

    def run(self):
        for item in self.pubsub.listen():
            print item
            type = item['type']
            if type == 'psubscribe':
                continue
            data = item['data'].strip()
            channel, method_name = item['channel'].split(':')
            method = getattr(self, method_name)
            if method is not None:
                if method(data) == Listener.STOP:
                    break


class Publisher():

    def __init__(self, r):
        self.redis = r

    def key(self, command):
        return "%s:%s" % (CHANNELS_PREFIX, command)

    def send(self, command, data):
        self.redis.publish(self.key(command), json.dumps(data))

if __name__ == "__main__":
    client = Listener(redis.Redis())
    client.start()

    publisher = Publisher(redis.Redis())

When I execute this and try to find the list of channels in my Redis server using redis-cli using "PUBSUB CHANNELS" getting an empty list, how to list all the channels. The programme works perfectly fine.


Solution

  • PUBSUB CHANNELS

    Lists the currently active channels. An active channel is a Pub/Sub channel with one or more subscribers (not including clients subscribed to patterns).

    Your code uses PSUBSCRIBE command and subscribes to a pattern, NOT a channel, so PUBSUB CHANNELS returns an empty list.

    Also, you can take a look at the PUBSUB NUMPAT command, which returns the number of patterns.