运行前必备
执行
npm install hiredis redis命令,安装 node-redis。说明:
示例代码
const { createClient } = require('redis');/** 以下参数分别填写您的 Redis 实例内网 IP、端口号、实例 ID 和密码 */const host = "192.xx.xx.2";const port = "6379";const instanceid = "c53xx52f-55dc-4c22-a941-630xxx88";const pwd = "12as6zb";// 创建 Redis 客户端(新版 API)const client = createClient({// 使用 URL 格式包含认证信息url: `redis://${encodeURIComponent(instanceid)}:${encodeURIComponent(pwd)}@${host}:${port}`,// 或者使用分离参数(两种方式任选其一)/*socket: {host: host,port: parseInt(port) // 确保端口是数字类型},username: instanceid, // Redis 6.0+ ACL 用户名password: pwd,*/// 其他配置pingInterval: 60000, // 保持连接活跃disableOfflineQueue: true // 离线时不缓存命令});// Redis 连接错误处理(新版事件名不变)client.on('error', (err) => {console.error('Redis connection error:', err);});// 连接 Redis 并执行操作(async () => {try {// 显式建立连接(新版要求)await client.connect();console.log('Redis connected successfully');/** 接下来可以开始操作 Redis 实例 */// 设置 Key(新版 API)const setResult = await client.set("redis", "tencent");console.log(`set key redis ${setResult}, value is tencent`);// 获取 Key(新版 API)const value = await client.get("redis");console.log(`get key redis is: ${value}`);} catch (err) {console.error('Redis operation error:', err);} finally {// 程序结束关闭客户端(新版使用 quit 或 disconnect)await client.quit(); // 或 client.disconnect()console.log('Redis connection closed');}})();
运行结果
说明:
Redis connected successfullyset key redis OK, value is tencentget key redis is: tencentRedis connection closed