nestjs cache manager 很ioredis配合使用方案

1. 安装依赖

npm i @tirke/node-cache-manager-ioredis cache-manager

2. 创建redis 模块和服务

1. 生成并编辑module

生成module
nest g mo redis
编辑模块
// redis.module.ts
import { Module } from '@nestjs/common';
// import { redisClient } from './redis.client';
import { ioRedisStore, RedisCache } from '@tirke/node-cache-manager-ioredis';
import { caching } from 'cache-manager';
@Module({
  providers: [
    {
      provide: 'REDIS_CLIENT',
      useValue: async () => {
        const redisCache: RedisCache = await caching(ioRedisStore, {
          host: '192.168.50.3', // default value
          port: 6379, // default value
          password: '',
          ttl: 600,
        });

        // listen for redis connection error event
        const cache = redisCache.store;
        cache.client.on('error', (error: unknown) => {
          console.error('Redis error:', error);
        });
      },
    },
  ],
  exports: ['REDIS_CLIENT'],
})
export class RedisModule {}


2.生成并编辑redis service

生成service
nest g s redis
编辑service
// redis.service.ts
import { Injectable } from '@nestjs/common';
import { Inject } from '@nestjs/common';
import { Redis } from 'ioredis';

@Injectable()
export class RedisService {
  constructor(@Inject('REDIS_CLIENT') private readonly client: Redis) {}

  async set(key: string, value: any): Promise<void> {
    await this.client.set(key, value);
  }

  async get(key: string): Promise<string | null> {
    return this.client.get(key);
  }

  async del(key: string): Promise<number> {
    return this.client.del(key);
  }
}

note: 记得删除app.mudule.ts 中的引用

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';

import { ConfigModule } from '@nestjs/config';
// import { RedisModule } from './redis/redis.module';刪除

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: ['.env.development.local', '.env.development', '.env'],
      //If a variable is found in multiple files, the first one takes precedence.
    }),
    MongooseModule.forRoot(process.env.MONGO_URI),
    UserModule,
    AuthModule,
    MemberModule,
   //  RedisModule,刪除
  ],
  controllers: [AppController],
  providers: [AppService,RedisService],
})
export class AppModule {}


  

3. 调用服务

1.使用的模块导入RedisService和模块RedisModule
...
import { RedisService } from 'src/redis/redis.service';
import { RedisModule } from 'src/redis/redis.module';

@Module({
  imports: [
    RedisModule,
   ....
  ],
  providers: [
 	...
    RedisService
  ],
  exports: [AuthService],
  controllers: [AuthController],
})
export class AuthModule {}

2. 调用
import { Injectable } from '@nestjs/common';
import { RedisService } from 'src/redis/redis.service';
@Injectable()
export class AuthService {
  constructor(
    private readonly redisService: RedisService,
  ) {}
  async login(member: MemberLoginDto) {
    ...
    await this.redisService.set(`token:${accessToken}`, memberInfo);
  }
}

NestJS Cache Manager is a module for caching data in NestJS applications. It provides a simple interface for caching data using various caching strategies such as memory, Redis, and others. Redis is one of the caching strategies that NestJS Cache Manager supports. Redis is an in-memory data structure store that can be used as a database, cache, and message broker. It is often used as a cache because of its high performance and scalability. Redis stores data in memory, which makes it faster than traditional disk-based databases. Using Redis as a caching strategy in NestJS Cache Manager is easy. First, you need to install the Redis module: ``` npm install cache-manager-redis-store ``` Next, you need to configure the Redis cache in your NestJS application: ``` import { CacheModule, Module } from '@nestjs/common'; import * as redisStore from 'cache-manager-redis-store'; @Module({ imports: [ CacheModule.register({ store: redisStore, host: 'localhost', port: 6379, }), ], }) export class AppModule {} ``` In this example, we import the CacheModule and configure it to use the Redis store. We set the host and port to connect to the Redis instance. Now, you can use the cache in your NestJS application: ``` import { CacheInterceptor, CacheTTL, Controller, Get, UseInterceptors } from '@nestjs/common'; @Controller('cats') export class CatsController { @Get() @UseInterceptors(CacheInterceptor) @CacheTTL(60) findAll(): string[] { return ['Cat 1', 'Cat 2', 'Cat 3']; } } ``` In this example, we use the CacheInterceptor to cache the response of the findAll() method for 60 seconds. This means that subsequent requests for the same resource will be served from the cache, which improves performance and reduces the load on the server. Overall, using Redis as a caching strategy in NestJS Cache Manager is a great way to improve the performance and scalability of your NestJS application.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值