redispy-redis

transactional pubsub in Redis with python redis client


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??


Solution

  • 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"