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);
}
}