为什么我不能让单个 Redis 客户端在同一连接中充当 PUB 和 Sub ?
我的思维模型是“聊天”,我订阅了某个频道,并且可以向该频道发布消息。
My mental model was that of a 'chat', where I am subscribed to a certain channel and I can publish messages to this channel.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于 pub/sub 是异步的,因此发布的消息可能随时出现,包括当您期望对命令的响应时。
尽管 Redis 是单线程的(通常会阻止此类事情),但网络延迟可能会导致一些有趣的影响 - 根据消息的内容,您可能会在服务器实际收到命令之前收到对命令的有效响应。
也就是说,如果您确实想要的话,您可能可以使用单个连接 - “不应该”与“不能”不同,并且 Redis 遵循简单的设计理念,即不会试图阻止您搬起石头砸自己的脚。然而,只打开两个到服务器的连接要容易得多。如果您达到每个客户端两个连接的连接限制,那么无论如何,您可能很快就会遇到每个客户端一个连接的问题。
Since pub/sub is asynchronous, the published message could appear at any time, including when you are expecting the response to a command.
Although redis is single threaded, which normally prevents that sort of thing, network latency can cause some interesting effects - depending on the content of the messages, you could receive a valid response to a command before the server has actually received it.
That said, you could probably use a single connection if you really wanted to - "should not" is not the same as "can not", and redis follows a simple design philosophy of not trying to prevent you from shooting yourself in the foot. However, it is a lot easier to just open two connections to the server. If you hit connection limits with two connections per client you will probably run into problems with one connection per client fairly soon anyway.
当客户端发出 SUBSCRIBE 或 PSUBSCRIBE 时,该连接将进入“发布/订阅”模式。此时,只有修改订阅集的命令才有效。当订阅集为空时,连接将恢复到常规模式。
如果您需要在发布/订阅模式下向 Redis 发送常规命令,只需打开另一个连接即可。
When a client issues a SUBSCRIBE or PSUBSCRIBE, that connection is put into "pub/sub" mode. At that point, only commands that modify the subscription set are valid. When the subscription set is empty, the connection is put back into regular mode.
If you need to send regular commands to Redis while in pub/sub mode, just open another connection.