DEV Community

Cover image for Simple Pub-Sub System using Redis and Python
rohit20001221
rohit20001221

Posted on • Updated on

Simple Pub-Sub System using Redis and Python

Hi guys i am here with an another blog post now let us build a simple publish subscribe system using python and redis

Running the redis server

i am using docker to start a redis instance in my computer. it's very easy to run a redis instance using docker and also it's very easy to remove redis instance, and the fun part is redis running through docker would not affect our system 😄

running redis instance

docker run --name demo-redis -p 6379:6379 -d redis:alpine
Enter fullscreen mode Exit fullscreen mode

if you want to stop or remove redis instance running through above command you can do the following

docker container stop demo-redis # <-- stop the redis instance

docker container rm demo-redis # <-- remove the redis container
Enter fullscreen mode Exit fullscreen mode

Creating the publisher

import redis

# initializing the redis instance
r = redis.Redis(
    host='127.0.0.1',
    port=6379,
    decode_responses=True # <-- this will ensure that binary data is decoded
)

while True:
    message = input("Enter the message you want to send to soilders: ")

    r.publish("army-camp-1", message)
Enter fullscreen mode Exit fullscreen mode

let's think publisher as a commander in army and he wants to send message to the soilders so here the the topic that he wants to publish message is army-camp-1. this analogy is only for fun 😂

Creating the subscriber

import redis

r = redis.Redis(
    host='127.0.0.1',
    port=6379,
    decode_responses=True
)

# pubsub() method creates the pubsub object
# but why i named it mobile 🧐
# just kidding 😂 think of it as the waki taki that listens for incomming messages
mobile = r.pubsub()

# use .subscribe() method to subscribe to topic on which you want to listen for messages
mobile.subscribe('army-camp-1')

# .listen() returns a generator over which you can iterate and listen for messages from publisher

for message in mobile.listen():
    print(message) # <-- you can literally do any thing with this message i am just printing it

Enter fullscreen mode Exit fullscreen mode

Here is a demo video of running the above code

Top comments (1)

Collapse
 
anu1996rag profile image
Anurag Patil

Exactly what I was looking for. Thank you for this. Simple and intuitive