Redis Streams 適配器
運作方式
該適配器將使用 Redis 串流 在 Socket.IO 伺服器之間轉送封包。
與現有的 Redis 適配器(使用 Redis Pub/Sub 機制)的主要差異在於,此適配器將適當處理與 Redis 伺服器之間的任何暫時斷線,並在不遺失任何封包的情況下恢復串流。
備註
- 所有命名空間都使用單一串流
maxLen
選項允許限制串流的大小- 與基於 Redis PUB/SUB 機制的適配器不同,此適配器將適當處理與 Redis 伺服器之間的任何暫時斷線,並恢復串流
- 如果啟用 連線狀態復原,則會將工作階段儲存在 Redis 中,作為傳統的鍵值對
原始碼:https://github.com/socketio/socket.io-redis-streams-adapter
支援的功能
功能 | socket.io 版本 | 支援 |
---|---|---|
Socket 管理 | 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);
選項
名稱 | 說明 | 預設值 |
---|---|---|
streamName | Redis 串流的名稱。 | socket.io |
maxLen | 串流的最大大小。會使用近乎精確的修剪 (~)。 | 10_000 |
readCount | 每次 XREAD 呼叫要擷取的元素數量。 | 100 |
sessionKeyPrefix | 在啟用連線狀態復原功能時,用於儲存 Socket.IO 會話的金鑰前綴。 | sio:session |
heartbeatInterval | 兩次心跳之間的毫秒數。 | 5_000 |
heartbeatTimeout | 在沒有心跳之前,視為節點已關閉的毫秒數。 | 10_000 |
常見問題
使用 Redis Streams 適配器時,我是否仍需要啟用黏著式工作階段?
是。未執行此操作將導致 HTTP 400 回應(您抵達的伺服器不知道 Socket.IO 工作階段)。
更多資訊可在此處找到 here。
當 Redis 伺服器停機時會發生什麼事?
與傳統的 Redis 適配器 不同,此適配器將適當處理與 Redis 伺服器的任何暫時斷線,並在不遺失任何封包的情況下繼續串流。
最新版本
版本 | 發行日期 | 版本說明 | 差異 |
---|---|---|---|
0.2.1 | 2024 年 3 月 | 連結 | 0.2.0...0.2.1 |
0.2.0 | 2024 年 2 月 | 連結 | 0.1.0...0.2.0 |
0.1.0 | 2023 年 4 月 | 連結 |