Redis 如何跟踪每个客户端?

How does redis keep track of every client?

我正在学习如何使用 Redis

我专门learning the pub/sub功能。

我正在使用 ioredis with expressjs and 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 客户端是否都有一个唯一的标识来标识它们? (就像 socket.io 的情况一样)

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

  • channel -> list of subscribed clients 服务器的地图 - 订阅命名频道时,
  • 服务器的模式订阅列表 - 如果是模式订阅,
  • 客户的 channel/pattern 订阅列表。

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

何时需要发布消息:

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

客户端的 channel/pattern 订阅列表用于跟踪客户端订阅的内容并在客户端断开连接时删除这些订阅。

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