Somebody asked me what PubSub was and how to create a channel (in comment from my answer) and I pointed him to the article on redis.io => http://redis.io/topics/pubsub. I think it is pretty clear, but I am wondering if somebody has a better explanation. Ideally, describe it clearly using redis-cli
.
Aside from data storage, Redis can be used as a Publisher/Subscriber platform. In this pattern, publishers can issue messages to any number of subscribers on a channel.
Redis Pub/Sub implements the messaging system where the senders (in redis terminology called publishers) sends the messages while the receivers (subscribers) receive them. The link by which the messages are transferred is called channel. In Redis, a client can subscribe any number of channels.
Synchronous point-to-point communication between the two endpoints is the best solution for media streaming. Pub/Sub is not suitable for carrying VoIP or video telephony traffic over the Internet.
The pub/sub messages are not queued, and even less persisted. They are only buffered in the socket buffers, and immediately sent to the subscribers in the same event loop iteration as the publication. If a subscriber fails to read a message, this message is lost for the subscriber. You could store them in lists.
Publish/subscribe is a pretty simple paradigm. Think of it like you're running a talk show on a radio station. That's PUBLISH. You're hoping at least one or more people will pick up your channel to listen to your messages on the radio show (SUBSCRIBE) and maybe even do some stuff, but you're not talking to folks directly.
Let's have some fun with redis-cli!
redis 127.0.0.1:6379> PUBLISH myradioshow "Good morning everyone!" (integer) 0 redis 127.0.0.1:6379> PUBLISH myradioshow "How ya'll doin tonight?" (integer) 0 redis 127.0.0.1:6379> PUBLISH myradioshow "Hello? Is anyone listening? I'm not wearing pants." (integer) 0
Notice there are no clients receiving the messages on your "myradioshow" channel (that's the 0 in the response). Nobody is listening. Now, open another redis-cli (or for more fun times have a friend open up their redis-cli and connect to your server) and SUBSCRIBE to the channel:
redis 127.0.0.1:6379> SUBSCRIBE myradioshow Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "myradioshow" 3) (integer) 1
Go back to your original redis-cli and continue your show:
redis 127.0.0.1:6379> PUBLISH myradioshow "Next caller gets a free loaf of bread!" (integer) 1
Notice that "1" at the end? You have a listener! Like magic, in your SUBSCRIBE-d terminal:
1) "message" 2) "myradioshow" 3) "Next caller gets a free loaf of bread!"
Of course, in reality, you're probably going to want to do stuff that's more useful than telling your clients about your pants-less lifestyle, such as firing events on your server or running some kind of tasks/jobs. Maybe not though! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With