Redis客户端触发ClientClosedError,无法设置值求助
解决 Redis ClientClosedError 问题
问题根源
- 未显式连接 Redis 客户端:Redis v4+ 版本中,
createClient()不会自动建立连接,必须手动调用connect()方法初始化连接。 - 直接存储非字符串数据:Redis 仅支持存储字符串或二进制数据,直接传入对象会导致数据格式错误或丢失。
- 未等待异步操作完成:调用
set方法时未使用await,无法确保操作执行顺序或捕获潜在错误。
修正后的 Redis.ts 代码
import { createClient } from "redis"; class RedisClient { client; constructor() { this.client = createClient(); // 监听连接状态和错误事件 this.client.on("connect", () => console.log("Redis Client 已连接") ); this.client.on("error", (err) => console.error("Redis Client 错误:", err) ); // 显式发起连接请求 this.client.connect().catch(err => console.error("Redis 连接失败:", err)); } set = async (key: string, value: any) => { // 将非字符串数据序列化为 JSON 字符串 const stringValue = typeof value === 'string' ? value : JSON.stringify(value); await this.client.set(key, stringValue); }; get = async (key: string) => { const value = await this.client.get(key); if (!value) return null; // 尝试反序列化 JSON 数据,兼容纯字符串存储 try { return JSON.parse(value); } catch { return value; } }; disconnect = async () => { await this.client.disconnect(); }; } export const Redis = new RedisClient();
修正后的 VController.ts 代码
import { Redis } from "../utilities/Redis"; import { Request, Response, NextFunction } from "express"; class VController { index = async (req: Request, res: Response, next: NextFunction) => { try { await Redis.set('user', {name: "somename"}); console.log("数据已成功存储到 Redis"); // 后续业务代码... res.status(200).send("操作完成"); } catch (err) { console.error("Redis 操作失败:", err); next(err); } }; }
额外注意事项
- 确保本地 Redis 服务正在运行(默认端口 6379),若 Redis 配置了密码或非默认端口,需在
createClient()中传入对应参数,例如:createClient({ password: 'your-password', port: 6380 })。 - 所有异步 Redis 操作都应包裹在
try/catch中,避免未处理的 Promise 异常导致服务崩溃。
内容的提问来源于stack exchange,提问作者Manish J
相关产品推荐
相关产品推荐

