Skip to content

Nest 中使用 Redis

本文重点解释 ioredis 的安装与使用,以及如何在 Nest 中使用 ioredis。

ioredis

我这里使用的是 yml 配置文件

安装 ioredis 类库

ts
pnpm install ioredis --save

创建一个全局模块 redis

  • 代码
ts
nest g resource redis

修改这个模块

  • (1) 删除控制器 redis.controller.ts

  • (2) 修改 redis.module.ts

ts
import { Module, Global } from "@nestjs/common";
import { RedisService } from "./redis.service";

@Global()
@Module({
  controllers: [],
  providers: [RedisService],
  exports: [RedisService],
})
export class RedisModule {}
  • (3) 修改 redis.service.ts
ts
import { Inject, Injectable } from "@nestjs/common";
import { Redis } from "ioredis";
import { ConfigService } from "@nestjs/config";
@Injectable()
export class RedisService {
  // 定义
  private readonly redis: Redis;
  constructor(private readonly configServiceAll: ConfigService) {
    this.redis = new Redis({
      host: this.configServiceAll.get("redis").host, // 主机
      port: this.configServiceAll.get("redis").port, // 端口
      password: this.configServiceAll.get("redis").password, // 密码
      db: this.configServiceAll.get("redis").db, // 数据库
      family: 4, // IPV4||IPV6
    });
  }
  // 查询
  async get(key: string): Promise<string | null> {
    return await this.redis.get(key);
  }
  // 设置
  async set(key: string, value: any, expiration?: number): Promise<void> {
    if (expiration) {
      await this.redis.set(key, value, "EX", expiration);
    } else {
      await this.redis.set(key, value);
    }
  }
  // 设置列表
  async setList(key: string, list: Array<string>, ttl?: number): Promise<void> {
    for (let i = 0; i < list.length; i++) {
      await this.redis.lpush(key, list[i]);
    }
    if (ttl) {
      await this.redis.expire(key, ttl);
    }
  }
  // 获取列表
  async getList(key: string) {
    return await this.redis.lrange(key, 0, -1);
  }
}

使用

  • 在其他模块下面的 service 中使用
ts
import { Injectable } from "@nestjs/common";

import { RedisService } from "../redis/redis.service";
@Injectable()
export class TestredisService {
  constructor(private readonly redisService: RedisService) {}

  async findAll() {
    // 插入
    await this.redisService.set("name", "张三");
    // 查询
    const name = await this.redisService.get("name");
    console.log(name);
    // 插入过期时间 单位秒
    await this.redisService.set("age", 18, 60);
    return name;
  }
}