【问题标题】:How does redis keep track of every client?redis 如何跟踪每个客户端?
【发布时间】:2019-11-13 07:10:14
【问题描述】:

我正在学习如何使用Redis。

我特指learning the pub/sub 功能。

我将ioredis 与expressjs 和nodejs 一起使用。

我遇到过this code

var Redis = require("ioredis");
var redis = new Redis();
var pub = new Redis();
redis.subscribe("news", "music", function(err, count) {
  // Now we are subscribed to both the 'news' and 'music' channels.
  // `count` represents the number of channels we are currently subscribed to.

  pub.publish("news", "Hello world!");
  pub.publish("music", "Hello again!");
});

redis.on("message", function(channel, message) {
  // Receive message Hello world! from channel news
  // Receive message Hello again! from channel music
  console.log("Receive message %s from channel %s", message, channel);
});

// There's also an event called 'messageBuffer', which is the same as 'message' except
// it returns buffers instead of strings.
redis.on("messageBuffer", function(channel, message) {
  // Both `channel` and `message` are buffers.
});

现在我的问题是:

redis 是如何知道谁订阅了什么,以便向他们发送消息?每个 redis 客户端是否都有一个唯一的 id 来标识它们? (就像socket.io 的情况一样)

【问题讨论】:

  • 我猜是使用整数的客户端 ID。当你在 redis-cli 中输入 CLIENT ID 命令时得到的相同的数字

标签: redis publish-subscribe


【解决方案1】:

当客户订阅频道或模式时 - 此类订阅被引用:

  • channel -> list of subscribed clients 的服务器映射 - 订阅指定频道时,
  • 服务器的模式订阅列表 - 在模式订阅的情况下,
  • 客户的频道/模式订阅列表。

上面的服务器和客户端是指内存中的一个结构,它代表服务器和每个连接的客户端的各种属性,所以只要客户端连接 - 它的订阅只是上面列出的那些地方的参考(因此有无需使用任何特定 ID)。

当需要发布消息时:

  1. 在server.pubsub_channels 中查找频道,找到后 - 所有订阅该频道的客户端都会收到该消息,
  2. 当server.pubsub_patterns 列表不为空时 - 迭代所有模式订阅,如果模式匹配 - 通知创建此订阅的客户端。

客户端的频道/模式订阅列表用于跟踪客户端订阅的内容,并在客户端断开连接时删除这些订阅。

您也可以查看Redis/src/pubsub.c 了解详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2020-08-30
    相关资源
    最近更新 更多