以下是一个简单的 Redis 工具类示例,使用 Node.js 和 Redis 客户端库 ioredis。

const Redis = require('ioredis');

class RedisUtil {
  constructor() {
    this.redis = new Redis(); // 创建 Redis 客户端实例
  }

  async get(key) {
    const value = await this.redis.get(key);
    return value ? JSON.parse(value) : null;
  }

  async set(key, value, expire = 0) {
    const stringValue = JSON.stringify(value);
    if (expire === 0) {
      await this.redis.set(key, stringValue);
    } else {
      await this.redis.set(key, stringValue, 'EX', expire);
    }
  }

  async del(key) {
    await this.redis.del(key);
  }

  async expire(key, seconds) {
    await this.redis.expire(key, seconds);
  }

  async incr(key) {
    await this.redis.incr(key);
  }

  async decr(key) {
    await this.redis.decr(key);
  }

  async keys(pattern) {
    return await this.redis.keys(pattern);
  }

  async flush() {
    await this.redis.flushdb();
  }
}

module.exports = RedisUtil;

这个 Redis 工具类提供了常见的 Redis 操作方法,包括获取、设置、删除、设置过期时间、自增、自减、查询 keys、清空等。其中默认使用 JSON 序列化和反序列化存储数据,也可以根据需要自行修改。

使用示例:

const RedisUtil = require('./RedisUtil');

const redis = new RedisUtil();

(async () => {
  await redis.set('name', 'Tom');
  const name = await redis.get('name');
  console.log(name); // Tom

  await redis.incr('count');
  const count = await redis.get('count');
  console.log(count); // 1

  await redis.expire('name', 60); // 设置 name 的过期时间为 60 秒

  await redis.del('name');
  await redis.del('count');

  const keys = await redis.keys('*');
  console.log(keys); // []

  await redis.flush();
})();
用node js写一下redis工具类

原文地址: https://www.cveoy.top/t/topic/9V1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录