0
# Regular Redis Adapter
1
2
Standard Redis adapter implementation for Socket.IO servers using traditional Redis pub/sub channels. Provides broadcasting, socket management, and inter-server communication capabilities.
3
4
## Capabilities
5
6
### Create Adapter
7
8
Creates a Redis adapter factory function that can be used to configure Socket.IO servers.
9
10
```typescript { .api }
11
/**
12
* Creates a Redis adapter factory function
13
* @param pubClient - Redis client used to publish messages
14
* @param subClient - Redis client used to receive messages (put in subscribed state)
15
* @param opts - Optional configuration options
16
* @returns Function that creates RedisAdapter instances for namespaces
17
*/
18
function createAdapter(
19
pubClient: any,
20
subClient: any,
21
opts?: Partial<RedisAdapterOptions>
22
): (nsp: any) => RedisAdapter;
23
```
24
25
**Usage Examples:**
26
27
```typescript
28
import { createClient } from "redis";
29
import { Server } from "socket.io";
30
import { createAdapter } from "@socket.io/redis-adapter";
31
32
// With redis package
33
const pubClient = createClient({ url: "redis://localhost:6379" });
34
const subClient = pubClient.duplicate();
35
36
await Promise.all([
37
pubClient.connect(),
38
subClient.connect()
39
]);
40
41
const io = new Server({
42
adapter: createAdapter(pubClient, subClient, {
43
key: "my-app",
44
requestsTimeout: 10000
45
})
46
});
47
48
// With ioredis package
49
import { Redis } from "ioredis";
50
51
const pubClient = new Redis();
52
const subClient = pubClient.duplicate();
53
54
const io = new Server({
55
adapter: createAdapter(pubClient, subClient)
56
});
57
```
58
59
### RedisAdapter Class
60
61
Main adapter implementation that extends the base Socket.IO adapter with Redis functionality.
62
63
```typescript { .api }
64
/**
65
* Redis adapter class providing multi-server broadcasting capabilities
66
*/
67
class RedisAdapter extends Adapter {
68
readonly uid: string;
69
readonly requestsTimeout: number;
70
readonly publishOnSpecificResponseChannel: boolean;
71
readonly parser: Parser;
72
73
/**
74
* Create a new RedisAdapter instance
75
* @param nsp - Socket.IO namespace
76
* @param pubClient - Redis client for publishing
77
* @param subClient - Redis client for subscribing
78
* @param opts - Configuration options
79
*/
80
constructor(
81
nsp: any,
82
pubClient: any,
83
subClient: any,
84
opts?: Partial<RedisAdapterOptions>
85
);
86
}
87
```
88
89
### Broadcasting Methods
90
91
Methods for broadcasting packets to other Socket.IO servers.
92
93
```typescript { .api }
94
/**
95
* Broadcasts a packet to other servers
96
* @param packet - Packet to emit
97
* @param opts - Broadcasting options including rooms and flags
98
*/
99
broadcast(packet: any, opts: BroadcastOptions): void;
100
101
/**
102
* Broadcasts a packet with acknowledgement support
103
* @param packet - Packet to emit
104
* @param opts - Broadcasting options
105
* @param clientCountCallback - Called with total client count expecting acknowledgements
106
* @param ack - Called for each acknowledgement received
107
*/
108
broadcastWithAck(
109
packet: any,
110
opts: BroadcastOptions,
111
clientCountCallback: (clientCount: number) => void,
112
ack: (...args: any[]) => void
113
): void;
114
```
115
116
**Usage Examples:**
117
118
```typescript
119
// Basic broadcasting (handled automatically by Socket.IO)
120
io.emit("notification", { message: "Hello all servers!" });
121
122
// Broadcasting to specific rooms
123
io.to("room1").emit("message", "Hello room1!");
124
125
// Broadcasting with acknowledgements
126
io.timeout(5000).emit("ping", (err, responses) => {
127
if (err) {
128
console.error("Some clients did not acknowledge:", err);
129
} else {
130
console.log("All clients acknowledged:", responses);
131
}
132
});
133
```
134
135
### Room and Socket Management
136
137
Methods for managing rooms and sockets across multiple servers.
138
139
```typescript { .api }
140
/**
141
* Gets all rooms across all servers
142
* @returns Promise resolving to set of all room names
143
*/
144
allRooms(): Promise<Set<Room>>;
145
146
/**
147
* Fetches socket information from all servers
148
* @param opts - Options specifying which sockets to fetch
149
* @returns Promise resolving to array of socket information
150
*/
151
fetchSockets(opts: BroadcastOptions): Promise<any[]>;
152
153
/**
154
* Adds sockets to rooms across all servers
155
* @param opts - Options specifying which sockets to affect
156
* @param rooms - Array of room names to join
157
*/
158
addSockets(opts: BroadcastOptions, rooms: Room[]): void;
159
160
/**
161
* Removes sockets from rooms across all servers
162
* @param opts - Options specifying which sockets to affect
163
* @param rooms - Array of room names to leave
164
*/
165
delSockets(opts: BroadcastOptions, rooms: Room[]): void;
166
167
/**
168
* Disconnects sockets across all servers
169
* @param opts - Options specifying which sockets to disconnect
170
* @param close - Whether to close the underlying connection
171
*/
172
disconnectSockets(opts: BroadcastOptions, close: boolean): void;
173
```
174
175
**Usage Examples:**
176
177
```typescript
178
// Get all rooms across servers
179
const allRooms = await io.adapter.allRooms();
180
console.log("All rooms:", [...allRooms]);
181
182
// Fetch all sockets in a room across servers
183
const sockets = await io.in("room1").fetchSockets();
184
console.log(`Found ${sockets.length} sockets in room1`);
185
186
// Make all sockets in room1 join room2
187
io.in("room1").socketsJoin("room2");
188
189
// Disconnect all sockets in a room
190
io.in("room1").disconnectSockets();
191
```
192
193
### Server Communication
194
195
Methods for communication between Socket.IO server instances.
196
197
```typescript { .api }
198
/**
199
* Emits an event to all other Socket.IO server instances
200
* @param packet - Array containing event name and arguments
201
*/
202
serverSideEmit(packet: any[]): void;
203
204
/**
205
* Gets the count of connected Socket.IO servers
206
* @returns Promise resolving to number of servers
207
*/
208
serverCount(): Promise<number>;
209
```
210
211
**Usage Examples:**
212
213
```typescript
214
// Emit to other servers without acknowledgement
215
io.serverSideEmit("hello", "world", 123);
216
217
// Emit to other servers with acknowledgement
218
io.serverSideEmit("ping", (err, responses) => {
219
if (err) {
220
console.error("Error:", err);
221
} else {
222
console.log("Responses from other servers:", responses);
223
}
224
});
225
226
// Get server count
227
const count = await io.engine.generateId =
228
const serverCount = await io.adapter.serverCount();
229
console.log(`Connected servers: ${serverCount}`);
230
```
231
232
### Lifecycle Management
233
234
Methods for managing the adapter lifecycle.
235
236
```typescript { .api }
237
/**
238
* Closes the adapter and cleans up Redis subscriptions
239
*/
240
close(): Promise<void> | void;
241
```
242
243
## Configuration Options
244
245
```typescript { .api }
246
interface RedisAdapterOptions {
247
/**
248
* The prefix for Redis Pub/Sub channels
249
* @default "socket.io"
250
*/
251
key: string;
252
253
/**
254
* Timeout for waiting for responses to requests (in milliseconds)
255
* @default 5000
256
*/
257
requestsTimeout: number;
258
259
/**
260
* Whether to publish responses to specific channels per requesting node
261
* @default false
262
*/
263
publishOnSpecificResponseChannel: boolean;
264
265
/**
266
* Message parser for encoding/decoding Redis messages
267
* @default notepack.io (MessagePack)
268
*/
269
parser: Parser;
270
}
271
```
272
273
## Supported Redis Clients
274
275
The adapter supports multiple Redis client libraries:
276
277
### redis Package (v3 and v4+)
278
279
```typescript
280
// Standalone Redis
281
import { createClient } from "redis";
282
const pubClient = createClient({ url: "redis://localhost:6379" });
283
const subClient = pubClient.duplicate();
284
285
// Redis Cluster
286
import { createCluster } from "redis";
287
const pubClient = createCluster({
288
rootNodes: [
289
{ url: "redis://localhost:7000" },
290
{ url: "redis://localhost:7001" },
291
{ url: "redis://localhost:7002" }
292
]
293
});
294
const subClient = pubClient.duplicate();
295
```
296
297
### ioredis Package
298
299
```typescript
300
// Standalone Redis
301
import { Redis } from "ioredis";
302
const pubClient = new Redis();
303
const subClient = pubClient.duplicate();
304
305
// Redis Cluster
306
import { Cluster } from "ioredis";
307
const pubClient = new Cluster([
308
{ host: "localhost", port: 7000 },
309
{ host: "localhost", port: 7001 },
310
{ host: "localhost", port: 7002 }
311
]);
312
const subClient = pubClient.duplicate();
313
```
314
315
## Types
316
317
The following types are imported from the `socket.io-adapter` package:
318
319
```typescript { .api }
320
// From socket.io-adapter
321
type Room = string | number;
322
323
interface BroadcastOptions {
324
rooms: Set<Room>;
325
except?: Set<Room>;
326
flags?: {
327
local?: boolean;
328
broadcast?: boolean;
329
binary?: boolean;
330
timeout?: number;
331
};
332
}
333
```