Redis如何与每个客户保持联系?

问题描述 投票:0回答:1

我正在学习如何使用Redis

我特别是learning the pub/sub功能。

我将ioredisexpressjsnodejs一起使用。

我遇到过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的情况)

redis publish-subscribe
1个回答
0
投票

[当客户订阅频道或模式时-在以下情况中引用了这种订阅:

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

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

当需要发布消息时:

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

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

您也可以查看Redis/src/pubsub.c以查看详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.