1. 安装与连接
npm install ioredis
const Redis = require('ioredis');
// 连接 Redis(默认 localhost:6379)
const redis = new Redis();
// 指定配置
const redis = new Redis({
host: 'localhost',
port: 6379,
password: '123456',
db: 0, // 数据库编号(默认 0~15)
retryStrategy: (times) => {
// 断线重连策略
return Math.min(times * 50, 2000); // 最多等 2 秒
},
});
// 连接字符串方式
const redis = new Redis('redis://:password@localhost:6379/0');
// 测试连接
redis.ping().then(res => {
console.log('Redis 连接', res === 'PONG' ? '✅' : '❌');
});
大约 4 分钟
