什么是 Redis pubsub 以及如何使用它? [英] What is Redis pubsub and how do I use it?

查看:51
本文介绍了什么是 Redis pubsub 以及如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人问我什么是 PubSub 以及如何创建频道(来自 我的回答),我向他指出了关于 redis.io => http://redis.io/topics/pubsub.我认为这很清楚,但我想知道是否有人有更好的解释.理想情况下,使用 redis-cli 清楚地描述它.

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.

推荐答案

发布/订阅是一个非常简单的范例.把它想象成你在广播电台播放脱口秀.那是发布.您希望至少有一个或多个人会选择您的频道来收听您在广播节目中的消息(订阅),甚至可能做一些事情,但是您并没有直接地与人们交谈.

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.

让我们玩转 redis-cli!

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

请注意,没有客户端在您的myradioshow"频道上接收消息(即响应中的 0).没有人在听.现在,打开另一个 redis-cli(或者为了更有趣的时间,让朋友打开他们的 redis-cli 并连接到您的服务器)并订阅频道:

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

回到你原来的 redis-cli 并继续你的表演:

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

注意到末尾的1"了吗?你有一个听众!就像魔术一样,在您的 SUBSCRIBE-d 终端中:

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! :)

这篇关于什么是 Redis pubsub 以及如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆