feat: implement Redis-backed Socket.io adapter and user presence service for cross-instance communication
This commit is contained in:
42
src/common/adapters/redis-io.adapter.ts
Normal file
42
src/common/adapters/redis-io.adapter.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { IoAdapter } from '@nestjs/platform-socket.io';
|
||||
import { INestApplicationContext, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { ServerOptions } from 'socket.io';
|
||||
import { createAdapter } from '@socket.io/redis-adapter';
|
||||
import Redis from 'ioredis';
|
||||
|
||||
export class RedisIoAdapter extends IoAdapter {
|
||||
private readonly logger = new Logger(RedisIoAdapter.name);
|
||||
private adapterConstructor: ReturnType<typeof createAdapter>;
|
||||
|
||||
constructor(
|
||||
app: INestApplicationContext,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
super(app);
|
||||
}
|
||||
|
||||
async connectToRedis(): Promise<void> {
|
||||
const host = this.configService.get<string>('redis.host', 'localhost');
|
||||
const port = this.configService.get<number>('redis.port', 6379);
|
||||
const password = this.configService.get<string>('redis.password') || undefined;
|
||||
const db = this.configService.get<number>('redis.db', 0);
|
||||
|
||||
const pubClient = new Redis({ host, port, password, db });
|
||||
const subClient = new Redis({ host, port, password, db });
|
||||
|
||||
await Promise.all([
|
||||
new Promise<void>((resolve) => pubClient.on('connect', resolve)),
|
||||
new Promise<void>((resolve) => subClient.on('connect', resolve)),
|
||||
]);
|
||||
|
||||
this.adapterConstructor = createAdapter(pubClient, subClient);
|
||||
this.logger.log(`Redis adapter connected to ${host}:${port}`);
|
||||
}
|
||||
|
||||
createIOServer(port: number, options?: ServerOptions) {
|
||||
const server = super.createIOServer(port, options);
|
||||
server.adapter(this.adapterConstructor);
|
||||
return server;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user