You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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终端执行以下操作:

  1. 编辑Redis配置文件(路径可能是/etc/redis/redis.conf或/etc/redis/6379.conf):
    sudo nano /etc/redis/redis.conf
    
  2. 找到bind 127.0.0.1,注释掉并改成bind 0.0.0.0(允许所有IP访问)
  3. 找到protected-mode yes,改成protected-mode no(测试环境临时关闭,生产环境请设置密码)
  4. 重启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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 14:15:09