Nest.js 使用 Redis 缓存数据

本文档详细介绍了如何在Nest.js应用中集成并使用Redis进行数据缓存,包括安装依赖、配置服务模块,以及在usersModule中的具体使用方法,旨在帮助开发者避免常见问题。

菜鸟总是要踩很多坑,记录坑让其他菜鸟少踩。

一、安装依赖

npm install cache-manager --save
npm install cache-manager-redis-store --save
npm install @types/cache-manager -D

二、redis-cache.service.ts 

import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';

@Injectable()
export class RedisCacheService {
  constructor(
    @Inject(CACHE_MANAGER)
    private cacheManager: Cache
  ) {
  }

  cacheSet(key: string, value: string, ttl: number) {
    this.cacheManager.set(key, value, { ttl: ttl }, (err: any) => {
      if (err) {
        throw err;
      }
    })
  }

  async cacheGet(key: any): Promise<any> {
    return this.cacheManager.get(key);
  }

}

 三、redis-cache.module.ts

import { Module, CacheModule } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';
import { RedisCacheService } from './redis-cache.service';

@Module({
  imports: [
    CacheModule.register({
      store: redisStore,
      host: 'localhost',
      port: 6379,
      auth_pass: "XXXXXX",
      db: 3 // 目标库
    }),
  ],
  controllers: [],
  providers: [RedisCacheService],
  exports: [RedisCacheService],
})
export class RedisCacheModule { }

四、在其他module中使用redis,如usersModule

4.1 users.module.ts

import { Module } from '@nestjs/common';
import { UserService } from './users.service';
import { UserController } from './users.controller';
import { userProviders } from './users.providers';
import { RedisCacheModule } from '../redis/redis-cache.module';

@Module({
  imports: [
    RedisCacheModule,
  ],
  controllers: [UserController],
  providers: [...userProviders, UserService],
  exports: [UserService],
})
export class UserModule { }

4.2 users.provider.ts 

import { Connection } from 'typeorm';
import { User } from './entities/user.entity';

export const userProviders = [
  {
    provide: 'USERS_REPOSITORY',
    useFactory: (connections: Connection) => connections.getRepository(User)
    inject: ['DATABASE_CONNECTION'],
  },
];

 关于typeorm和数据库连接的内容跟本文内容无关就不写了。

 4.3 users.controller.ts

import { Controller, Get } from "@nestjs/common";
import { UserService } from "./users.service";

@Controller("User")
export class UserController {
  constructor(
    private readonly userService: UserService,
  ) { }

  @Get("get/:id")
  findOne(@Param("id") id: string) {
    return this.userService.findOne(id);
  }

}

4.4 users.service.ts

import { Injectable, Inject } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { RedisCacheService } from '../redis/redis-cache.service';

@Injectable()
export class UserService {
  constructor(
    @Inject("USERS_REPOSITORY")
    private readonly userRepository: Repository<User>,
    private readonly redisCacheService: RedisCacheService,
  ) { }

  async findOne(id: string): Promise<any> {
    const result = await this.userRepository
        .createQueryBuilder("user")
        .where({ id: id })
        .getOne();

    // 写入redis记录,ttl缓存期设置为30天
    this.redisCacheService.cacheSet("userId_" + id, JSON.stringify(result), 60 * 60 * 24 * 30)
    return result
  }

}

4.5 redis取值操作 

const cacheData = await this.redisCacheService.cacheGet("userId_" + id)
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值