什么是 WebSocket Room?NestJS 如何实现房间的加入、离开和消息分发?
解读
国内面试官问“WebSocket Room”时,通常不是想听概念复述,而是想看候选人能否把“房间”这一业务抽象落地到 NestJS 的 Gateway 体系里,并解决以下三个痛点:
- 连接与房间的生命周期如何绑定;
- 多节点(K8s 多 Pod)场景下房间状态怎么同步;
- 异常断线、重复加入、并发读写怎样兜底。
回答必须体现“装饰器驱动 + IoC 容器”的 Nest 特色,同时给出可横向扩展的代码级方案,否则会被认为“只是套了层 Socket.io 壳子”。
知识点
@WebSocketGateway()与IoAdapter的继承关系,Gateway 本质是 Socket.io 实例的封装器。- 房间(Room)在 Socket.io 内部是
Adapter.rooms:Map<Room, Set<SocketId>>,Nest 通过socket.join/leave操作该 Map。 - 默认
MemoryAdapter无持久化,生产需替换为RedisAdapter或nats-adapter,否则多节点房间状态不一致。 - 生命周期钩子:
OnGatewayConnection/Disconnect/Init用于资源申请与释放;OnEvent装饰器用于监听客户端事件。 - 异常过滤:在 Gateway 层用
WsExceptionsFilter捕获业务异常,防止进程崩溃。 - 并发安全:利用
Redis Redlock或INCR原子操作解决“超卖”问题,例如房间人数限制。 - 可观测性:通过
Counter与Histogram把ws_room_join_total、ws_room_msg_duration_seconds打入 Prometheus,满足国内金融/电商合规审计。
答案
“WebSocket Room”是 Socket.io 对“广播域”的抽象,一个房间即一组 SocketId 的集合,服务器向房间广播时只会推送给集合内的连接。NestJS 通过 Gateway 模式把房间操作封装成装饰器级别的 API,核心实现分五步:
- 定义 Gateway 并挂载 Redis 适配器
@WebSocketGateway({ cors: { origin: '*' }, adapter: new RedisIoAdapter(app) })
export class ChatGateway
implements OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server: Server;
async handleConnection(client: AuthenticatedSocket) {
// 把用户 ID 挂到 socket,方便后续按业务维度路由
client.uid = await this.authService.verify(client.handshake.auth.token);
}
}
- 加入房间(支持幂等与分布式锁)
@SubscribeMessage('join')
async joinRoom(
@MessageBody() dto: JoinDto,
@ConnectedSocket() client: AuthenticatedSocket,
) {
const lock = await this.redlock.lock(`room:${dto.roomId}:lock`, 200);
try {
const count = await this.redis.scard(`room:${dto.roomId}`);
if (count >= 500) throw new WsException('房间已满');
await client.join(dto.roomId);
await this.redis.sadd(`room:${dto.roomId}`, client.uid);
this.server.to(dto.roomId).emit('sys', `${client.uid} 进入房间`);
} finally {
await lock.release();
}
}
- 离开房间(保证资源释放)
@SubscribeMessage('leave')
async leaveRoom(
@MessageBody() dto: LeaveDto,
@ConnectedSocket() client: AuthenticatedSocket,
) {
await client.leave(dto.roomId);
await this.redis.srem(`room:${dto.roomId}`, client.uid);
this.server.to(dto.roomId).emit('sys', `${client.uid} 离开房间`);
}
- 消息分发(按房间广播 + ACK 机制)
@SubscribeMessage('chat')
async handleChat(
@MessageBody() dto: ChatDto,
@ConnectedSocket() client: AuthenticatedSocket,
) {
const ts = Date.now();
const payload = { from: client.uid, body: dto.body, ts };
// 保证客户端收到消息后再回执
return new Promise((resolve) => {
this.server.to(dto.roomId).timeout(5000).emit('chat', payload, (err, responses) => {
if (err) return resolve({ code: 1, msg: '部分客户端未确认' });
resolve({ code: 0, msg: 'ok' });
});
});
}
- 断线兜底(OnGatewayDisconnect)
async handleDisconnect(client: AuthenticatedSocket) {
const rooms = Array.from(client.rooms.values()).filter(r => r !== client.id);
await Promise.all(rooms.map(r => this.redis.srem(`room:${r}`, client.uid)));
rooms.forEach(r => this.server.to(r).emit('sys', `${client.uid} 离线`));
}
通过以上五步,NestJS 把“房间”做成可水平扩展、可观测、可回滚的企业级能力,满足国内高并发直播、在线课堂、金融行情推送等场景。
拓展思考
- 如果房间需要持久化历史消息,可把消息写入 TiDB 或 RocketMQ,再通过 WebSocket 推流补偿,实现“离线重放”。
- 对于万人大房间,可采用“房间分片 + 本地广播”混合模式:Gateway 层按一致性哈希把大房间拆成 N 个分片,每个分片内部用本地广播,跨分片用 Redis Gossip,降低 Redis 压力。
- 在 Serverless 场景(阿里云 FC 或腾讯云 SCF),连接无法常驻,需把房间状态下沉到 Redis 并配合事件网关(EventBridge)做“连接漂移”,保证冷启动后客户端能快速重新绑定原房间。
- 安全合规:国内 GDPR 等保 2.0 要求记录用户进出日志,可在 Gateway 层统一打 AuditLog,并通过 MDC 把 traceId 注入日志,方便与前端埋点串联。