A system I’m working on currently is receiving messages in redis. I would like to write a python script that can read in those messages , modify them and return them to a different channel/key in redis.
For example:
redis-cli -a 'redis' monitor | grep '"pushName"'
will return :
1707963448.404618 [0 192.168.86.75:51520] "LPUSH" "pushName" "{"uuid":"be70"...,{}}
How do I subscribe to get the messages from pushName
because when I try to do this
mobile = r.pubsub()
mobile.subscribe('pushName')
for message in mobile.listen():
print(message)
Nothing displays execept for :
{'type': 'subscribe', 'pattern': None, 'channel': 'pushName', 'data': 1}
. I already know my connection criteria is fine because I can get a list of the channels when I do this:
index_list = []
for key in r.scan_iter('*'):
index_list.append(key)
But messages are flying when I do :
redis-cli -a 'redis' monitor | grep '"pushName"'
2
Answers
You seem to be confusing debug output with messages, with Redis LISTs and with Redis Pub/Sub.
If your other (real) code is doing LPUSH operations it is appending items to a Redis LIST.
Those LPUSH operations will show up in your
redis-cli monitor
command because that is a debugging tool showing you all Redis internal operations.The LPUSH commands (which operate on a Redis LIST) will not show up when you subscribe to Redis Pub/Sub because that is a completely separate feature of Redis and you will only see messages when you subscribe to a topic and when somebody publishes on that topic… but nobody is doing any publishing as such, they are only doing LPUSH to a LIST.
Maybe you could adapt things so they work more like you are expecting. If you want to be notified every time there is an LPUSH onto a LIST, you could change your LPUSH to a MULTI/EXEC transaction that does the LPUSH and then PUBLISHES a message to notify all interested parties in one single transaction . That would make your sender look like this:
Then your receiver might look like this, subscribing to the notifications stream, and grabbing the LIST when notified:
When you run the receiver, it looks like this:
Note that there are actually 3 ways of waiting for messages you are subscribed to and they are described here. Basically, you can use:
Or you can use:
Or you can use a thread like I did.
Note that I am using a pipeline (MULTI/EXEC) for 2 reasons:
Note that you can chain the pipeline elements together, so that the 4-line pipeline in my sender code becomes: