跳至主要内容
版本: 4.x

Redis 流适配器

工作原理

该适配器将使用 Redis 流 在 Socket.IO 服务器之间转发数据包。

与现有的 Redis 适配器(使用 Redis 发布/订阅机制)的主要区别在于,此适配器将正确处理与 Redis 服务器的任何临时断开连接,并在不丢失任何数据包的情况下恢复流。

注意

  • 所有命名空间使用单个流
  • maxLen 选项允许限制流的大小
  • 与基于 Redis PUB/SUB 机制的适配器不同,此适配器将正确处理与 Redis 服务器的任何临时断开连接,并恢复流
  • 如果启用了 连接状态恢复,会话将作为经典的键值对存储在 Redis 中

源代码: https://github.com/socketio/socket.io-redis-streams-adapter

支持的功能

功能socket.io 版本支持
套接字管理4.0.0✅ 是(自版本 0.1.0 起)
服务器间通信4.1.0✅ 是(自版本 0.1.0 起)
带有确认的广播4.5.0✅ 是(自版本 0.1.0 起)
连接状态恢复4.6.0✅ 是(自版本 0.1.0 起)

安装

npm install @socket.io/redis-streams-adapter redis

用法

使用 redis

import { createClient } from "redis";
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/redis-streams-adapter";

const redisClient = createClient({ url: "redis://localhost:6379" });

await redisClient.connect();

const io = new Server({
adapter: createAdapter(redisClient)
});

io.listen(3000);

使用 redis 包和 Redis 集群

import { createCluster } from "redis";
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/redis-streams-adapter";

const redisClient = createCluster({
rootNodes: [
{
url: "redis://localhost:7000",
},
{
url: "redis://localhost:7001",
},
{
url: "redis://localhost:7002",
},
],
});

await redisClient.connect();

const io = new Server({
adapter: createAdapter(redisClient)
});

io.listen(3000);

使用 ioredis

import { Redis } from "ioredis";
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/redis-streams-adapter";

const redisClient = new Redis();

const io = new Server({
adapter: createAdapter(redisClient)
});

io.listen(3000);

使用 ioredis 包和 Redis 集群

import { Cluster } from "ioredis";
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/redis-streams-adapter";

const redisClient = new Cluster([
{
host: "localhost",
port: 7000,
},
{
host: "localhost",
port: 7001,
},
{
host: "localhost",
port: 7002,
},
]);

const io = new Server({
adapter: createAdapter(redisClient)
});

io.listen(3000);

选项

名称描述默认值
streamNameRedis 流的名称。socket.io
maxLen流的最大大小。使用近似修剪 (~)。10_000
readCount每次 XREAD 调用要获取的元素数量。100
sessionKeyPrefix用于存储 Socket.IO 会话的键的前缀,当启用连接状态恢复功能时。sio:session
heartbeatInterval两次心跳之间的毫秒数。5_000
heartbeatTimeout在将节点视为已关闭之前,没有心跳的毫秒数。10_000

常见问题

使用 Redis 流适配器时,我是否仍然需要启用粘性会话?

是的。如果不这样做,将导致 HTTP 400 响应(您正在访问一个不知道 Socket.IO 会话的服务器)。

更多信息请参见 此处

Redis 服务器关闭时会发生什么?

与经典的 Redis 适配器 不同,此适配器将正确处理与 Redis 服务器的任何临时断开连接,并在不丢失任何数据包的情况下恢复流。

最新版本

版本发布日期发行说明差异
0.2.12024 年 3 月链接0.2.0...0.2.1
0.2.02024 年 2 月链接0.1.0...0.2.0
0.1.02023 年 4 月链接

完整变更日志