Windows环境下Node连接WSL中Redis无反馈问题求助
解决Windows Node.js连接WSL Redis无反馈问题
核心原因分析
你的代码没触发连接成功/错误事件,大概率是两个问题:
- node-redis版本不兼容:v4+版本API有变更,旧写法不会主动发起连接,也不再使用
connect事件 - WSL与Windows网络隔离:Redis默认绑定WSL的localhost,Windows的localhost无法直接访问
分步解决
1. 检查并适配node-redis版本
运行命令查看当前版本:
npm list redis
如果是v4+版本(最常见情况)
修改代码,必须显式调用connect(),且监听ready事件(替代旧版的connect),同时指定WSL的Redis地址:
const redis = require("redis"); // 替换成你的WSL IP地址,比如172.17.0.2 const redisClient = redis.createClient({ url: "redis://172.17.0.2:6379" }); redisClient.on("error", (err) => { console.error("Error connecting to Redis:", err); }); // v4版本用ready事件替代connect redisClient.on("ready", () => { console.log("Connected to Redis"); }); // 必须主动调用connect发起连接 redisClient.connect().catch(err => console.error("Connect failed:", err)); module.exports = redisClient;
如果是v3及以下版本
不需要显式connect,但必须指定WSL的IP作为host:
const redis = require("redis"); const redisClient = redis.createClient({ host: "172.17.0.2", // 替换成你的WSL IP port: 6379 }); redisClient.on("error", (err) => { console.error("Error connecting to Redis:", err); }); redisClient.on("connect", () => { console.log("Connected to Redis"); }); module.exports = redisClient;
2. 配置WSL的Redis允许外部访问
在WSL终端执行以下操作:
- 编辑Redis配置文件(路径可能是
/etc/redis/redis.conf或/etc/redis/6379.conf):sudo nano /etc/redis/redis.conf - 找到
bind 127.0.0.1,注释掉并改成bind 0.0.0.0(允许所有IP访问) - 找到
protected-mode yes,改成protected-mode no(测试环境临时关闭,生产环境请设置密码) - 重启Redis服务:
sudo systemctl restart redis-server
3. 获取WSL的IP地址
在WSL终端运行:
hostname -I
输出的第一个IP就是WSL的内网地址(比如172.17.0.2),替换到代码中。
4. 验证网络连通性
在Windows命令提示符中测试:
telnet 172.17.0.2 6379
如果能连通说明网络没问题,否则检查Windows防火墙是否放行6379端口,或者WSL的Redis是否正常运行。
内容的提问来源于stack exchange,提问作者Jia Huang
相关产品推荐
相关产品推荐

