我有一个 web 服务,它非常频繁地向 Redis 服务器写入新条目,并且我有一个 NodeJS 应用程序,它将与 Redis 服务器交互。我意识到我可能会问一个过去以多种形式提出的问题,但我不得不问,以免我花更多的时间在圈子里寻找答案,但是“我的 NodeJS 应用程序服务器有什么方法可以自动接收新条目?';类似于 RSS 提要如何自动接收新文章。

我知道 Redis 有一个发布/订阅范例,但我难以理解的是“Redis 是否可以在收到新条目时自动发布新条目?”此外,Redis 是否可以在收到特定键的新条目时自动发布它们?

最佳答案

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

订阅(或 psubscribe 模式)使用 key 来指定连接 channel 。因此,例如(使用 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 代码了解这些 channel 之一中的某些内容时,只需发布​​一条消息即可。例如在 python 的 redis 客户端中:
connection.publish("myInterestingChannel", "poop goes in the potty");

在您的问题中,您会问“此外,Redis 能否在收到特定键的新条目时自动发布它们?”

如果您将它们发布在正在订阅的 channel 上,则可以。但是,当您执行类似操作时,它无法自动发布
connection.set("myInterestingChannel", "some other message")

相反,如果您想存储它,并让您的 Node 应用程序知道,您可以最轻松地执行以下操作:
msg = "some other message"
connection.set("some key", msg)
connection.publish("myInterestingChannel", msg)

关于javascript - Redis 自动发布新条目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14153179/

10-12 17:28
查看更多