从零开始搭建nestjs项目-配置redis服务

177 阅读1分钟

服务器需要先安装redis的相关服务,推荐使用Another Redis Desktop Manager可视化客户端去测试一下redis配置是否正常。

相关包

pnpm i ioredis

封装redis服务

使用nest g s redis创建redis.service.ts

import { Injectable } from '@nestjs/common';
import { Redis } from 'ioredis';

@Injectable()
export class RedisService {
    private readonly redisClient: Redis;
    private defaultTime = 60 * 10;//默认有效时间,单位秒

    constructor() {
        this.redisClient = new Redis({
            host: 'host',
            port: 6379,
        });
        
        //使用db0
        this.redisClient.select(0)
    }


    setValue(key: string, value: string, seconds?: number) {
        return this.redisClient.set(key, value, 'EX', seconds || this.defaultTime);
    }

    getValue(key: string) {
        return this.redisClient.get(key);
    }

    deleteValue(key: string) {
        return this.redisClient.del(key);
    }

    deleteAllValue() {
        return this.redisClient.flushall();
    }

    // 根据正则表达式获取keys
    getKeysByPattern(pattern:string){
        return this.redisClient.keys(pattern)
    }
}

结束

版本

  1. nodejs:20.9.0
  2. npm:10.1.0
  3. nestjs:10.0.0