0

I know Redis has the concept of transactions and pub/sub. I am wondering if you can do a transactional pubsub with Python redis client.

Here is the setup. I have two clients A and B who are pushing to the same two channels. Each time, each client might push their name to both channels. They might decide to do so at the same time (or similar enough time). I want the channels to look like either [A,B][A,B] or [B,A] [B,A], but not [A,B] [B,A]. i.e. I need to atomically have a client publish to two channels.

In Redis cli, I would write something like MULTI, PUBLISH FIRST A, PUBLISH SECOND A, EXEC.

How to do this in Python??

bumpbump
  • 542
  • 4
  • 17

1 Answers1

1

MULTI/EXEC: These are implemented as part of the Pipeline class. The pipeline is wrapped with the MULTI and EXEC statements by default when it is executed, which can be disabled by specifying transaction=False.

https://github.com/redis/redis-py#pipelines

Here is the example:

import redis
r = redis.Redis()
pipe=r.pipeline()
pipe.publish('A1','msg1')
pipe.publish('A2','msg2')
pipe.execute()

If you'll monitor it in redis-cli via MONITOR command, the following messages would be sent to Redis:

1641318120.640290 [0 [::1]:53268] "MULTI"
1641318120.640346 [0 [::1]:53268] "PUBLISH" "A1" "msg1"
1641318120.640362 [0 [::1]:53268] "PUBLISH" "A2" "msg2"
1641318120.640371 [0 [::1]:53268] "EXEC"
Anton
  • 3,587
  • 2
  • 12
  • 27
  • Can you show me how to write a redis pipeline with pubsub? – bumpbump Jan 04 '22 at 17:16
  • example added to the answer – Anton Jan 04 '22 at 17:47
  • I was under the impression that you can only call publish method on a pubsub object created by redis.pubsub(). Is this not true? Can you comment on the differences between pubsub object and pipeline object in your answer? Thanks! – bumpbump Jan 04 '22 at 17:54
  • 1
    You can *subscribe* only using pubsub object. Publish can be used with either regular redis connection or a pipeline. PUBLISH is a "regular" Redis command, unlike SUBSCRIBE which puts connection in the state where only limited set of commands are available. See example here: https://github.com/redis/redis-py#publish--subscribe note that subscribe() and get_message() are methods of pubsub object p and publish() is of a 'regular' Redis connection r. – Anton Jan 04 '22 at 18:04