Nodejs操作redis

下载安装ioredis

npm i ioredis
pnpm add ioredis
yarn add iosredis

 创建 Redis 客户端连接

const Redis = require('ioredis');
// 创建一个普通 Redis 连接
const redis = new Redis({ host: 'localhost', port: 6379 });

// 或者创建一个连接 Redis Sentinel 或 Cluster 的连接
// const redis = new Redis.Cluster([/* sentinel nodes or cluster nodes */]);

// 或者创建一个连接池
const redis = new Redis.Cluster(/* options */, { enableReadyCheck: true, enableOfflineQueue: true });

添加键值对向redis 

// 设置键值对
redis.set('key', 'value', (err, reply) => {
  if (err) throw err;
  console.log(reply); // 输出: 'OK'
});

// 获取键的值
redis.get('key', (err, reply) => {
  if (err) throw err;
  console.log(reply); // 输出: 'value'
});

// 异步/await 语法示例
async function example() {
  await redis.set('asyncKey', 'asyncValue');
  const value = await redis.get('asyncKey');
  console.log(value); // 输出: 'asyncValue'
}
example();

给键值对设置过期时间

(async () => {
    try {
        // 设置键值对,并设置其过期时间为5秒
        await redisClient.set('expireKey', 'expireValue', 'EX', 5);

        // 或者,使用毫秒作为单位设置过期时间
        // await redisClient.set('expireKeyMs', 'expireValueMs', 'PX', 5000);

        // 查看键的剩余生存时间(以秒为单位)
        const ttlInSeconds = await redisClient.ttl('expireKey');
        console.log(`expireKey will expire in ${ttlInSeconds} seconds`);

        // 查看键的剩余生存时间(以毫秒为单位)
        // 注意:Redis本身是以秒为单位计算TTL,这里的毫秒级精度依赖于ioredis的实现
        const ttlInMilliseconds = await redisClient.pttl('expireKey');
        console.log(`expireKey will expire in approximately ${ttlInMilliseconds} milliseconds`);
    } catch (error) {
        console.error('Error setting key expiration:', error);
    }
})();

 关闭redis连接

redis.quit(); // 对于单个连接
// 或
redis.disconnect(); // 对于连接池

 

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bluecook

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值