const { createClient } = require("redis"); //创建全局redis客户端实例 let client; //初始化redis客户端 const redisClient = async () => { if (client) return; //如果客户端已初始化,则不再重复初始化 client = await createClient() .on("error", err => { console.log('redis链接失败', err) }) .connect(); } //存入数组或者对象,并可选的设置过期时间 //@param key 键名 //@param value 要存储的值 //@param ttl 可选,以秒为单位的过期时间,默认不设置 const setKey = async (key, value, ttl=null) => { if (!client) await redisClient(); //确保客户端已经初始化 value = JSON.stringify(value); //将对象转换为JSON字符串 await client.set(key, value); //如果提供了过期时间,则设置 if (ttl !== null) { await client.expire(key, ttl); } } //读取数组或者对象 //@param key 键名 //@param {promise} 解析后的JSON对象或数组 const getKey = async (key) => { if (!client) await redisClient(); //确保客户端已经初始化 const value = await client.get(key);//将获取到的JSON字符串转换为对象 return value ? JSON.parse(value) : null; //如果value为空,返回null而不是抛出错误 } //清除缓存数据 //@param key 键名 //@param {promise} const delKey = async (key) => { if (!client) await redisClient(); //确保客户端已经初始化 await client.del(key); } module.exports = { redisClient, setKey, getKey, delKey };