Docs: https://docs.nestjs.com/techniques/caching
yarn add @nestjs/mongoose mongoose
yarn add cache-manager
app.module.ts
import { Module, CacheModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose'
import { CatSchema } from './schemas/cat.schema'
@Module({
imports: [
CacheModule.register({
ttl: 5, // 缓存更新时间
max: 10
}),
MongooseModule.forRoot('mongodb://localhost/ajanuw', { useNewUrlParser: true }),
MongooseModule.forFeature([
{ name: 'cats', schema: CatSchema }
])
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
cat.schema.ts
import * as mongoose from 'mongoose';
export const CatSchema = new mongoose.Schema({
name: String,
});
app.service.ts
import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose'
import { InjectModel } from '@nestjs/mongoose'
import { Cat } from './interfaces/cat.interface'
@Injectable()
export class AppService {
constructor(
@InjectModel('cats') private readonly catModel: Model
){}
all(): Promise{
return this.catModel.find().exec()
}
}
cat.interface.ts
import { Document } from 'mongoose'
export interface Cat extends Document {
readonly name: string;
}
app.controller.ts
import { Get, Controller, UseInterceptors, CacheInterceptor } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
@UseInterceptors(CacheInterceptor)
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('all')
all(){
let cats = this.appService.all()
return cats
}
}
存在 Redis当中
yarn add cache-manager-redis-store
app.module.ts
import { Module, CacheModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import * as redisStore from 'cache-manager-redis-store'
import { MongooseModule } from '@nestjs/mongoose'
import { CatSchema } from './schemas/cat.schema'
@Module({
imports: [
CacheModule.register({
store: redisStore,
host: 'localhost',
port: 6379,
ttl: 10, // 缓存更新时间
max: 15,
}),
// CacheModule.register(),
MongooseModule.forRoot('mongodb://localhost/ajanuw', { useNewUrlParser: true }),
MongooseModule.forFeature([
{ name: 'cats', schema: CatSchema }
])
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}