Tech C**P
15 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
Publish & Subscribe for dummies:

Open 2 different windows (pane) in terminal and go to redis console:
redis-cli

Now to subscribe into a specific channel:
127.0.0.1:6379> SUBSCRIBE first second
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "first"
3) (integer) 1
1) "subscribe"
2) "second"
3) (integer) 2

As you can see we have subscribed to 2 channels called first and second. In another window open redis console again by redis-cli command and try to publish to those channels:
PUBLISH second Hello

Now you should see the output below in the first window where you have subscribed to channels:
1) "message"
2) "second"
3) "Hello"

If you want to know more about pub-sub scenario:
https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern

#redis #pub_sub #publish #subscribe #redis_cli
As you may remember we have explained redis pubsub in which someone subscribe to a specific channel and then another console publish messages to that channel. The publisher has no idea who is listening on the other side, it just publish messages which is received.

Today we are gonna give a python example of the redis pubsub using threading and redis python module. Take a look at the code in the link below:

https://gist.github.com/alirezastack/ff2515cc434360f544d8a9341155947e

I prefer not to clutter the post by pasting the whole script here. :)

subscribe method is used to subscribe to a given channel, here it is called test. start method is used as part of the threading
module which causes run method to be called. Both run and start is Thread super class methods. When you run the script it will subscribe to test channel and wait for new messages.

NOTE: you can publish to test channel in redis console (`redis-cli`) as below:

127.0.0.1:6379> publish test hello_python
(integer) 1

Usecases are endless! You can use as part of messaging infrastructure in your microservice environment or as a chat system, you name it! :)

#python #redis #pubsub #publish #subscribe #thread