Redis自动发布新条目

时间:2013-01-04 07:47:08

标签: javascript node.js redis publish-subscribe

我有一个非常频繁地向Redis服务器写入新条目的Web服务,我有一个NodeJS应用程序,它将与Redis服务器交互。我意识到我可能会问一个过去以多种形式提出过的问题,但是我必须要求我花更多的时间在圈子中寻找答案但是'我的NodeJS应用服务器有没有办法自动收到新条目?';类似于RSS源自动接收新文章的方式。

据我所知,Redis有一个发布/订阅范例,但我理解的是“Redis会在收到新条目时自动发布吗?”此外,Redis可以在收到特定密钥时自动发布新条目吗?

1 个答案:

答案 0 :(得分:5)

node.js有redis客户端。找一个实现完整协议的协议,包括subscribe

订阅(或模式的psubscribe)使用key来指定连接通道。所以,例如(使用https://github.com/mranney/node_redis

connection.on("message", function (channel, message) {
   if (channel == "myInterestingChannel") {
       console.log(message);
   } else if (channel == "anotherChannel") {
       console.warn(message);
   }
}

connection.subscribe("myInterestingChannel");
connection.subscribe("anotherChannel");

然后,当您希望node.js代码知道其中一个频道中的内容时,只需发布​​一条消息即可。例如在python的redis客户端中:

connection.publish("myInterestingChannel", "poop goes in the potty");

在您的问题中,您会问“另外,Redis会在收到特定密钥时自动发布新条目吗?”

如果您在正在订阅的频道上发布它们,则可以。但是,当您执行

之类的操作时,它无法自动发布
connection.set("myInterestingChannel", "some other message")

相反,如果您想存储它,并让您的节点应用程序知道,您可以最轻松地执行以下操作:

msg = "some other message"
connection.set("some key", msg)
connection.publish("myInterestingChannel", msg)