缓存(Redis)
原创2026/3/5小于 1 分钟
安装
npm i --save ioredis
npm i --save @liaoliaots/nestjs-redis配置
import { Module } from '@nestjs/common'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { RedisModule } from '@liaoliaots/nestjs-redis'
@Module({
imports: [
RedisModule.forRoot({
config: {
host: '47.92.214.203',
port: 6379,
db: 1,
},
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}使用
app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) { }
@Get("set")
set() {
return this.appService.set();
}
@Get("get")
get() {
return this.appService.get();
}
}app.service.ts
import { Injectable } from '@nestjs/common';
import { RedisService } from '@liaoliaots/nestjs-redis';
import Redis from 'ioredis';
@Injectable()
export class AppService {
private readonly redis: Redis;
constructor(
private readonly redisService: RedisService,
) {
this.redis = this.redisService.getClient();
}
async set() {
const info = await this.redis.setex("k1", 60, "v1")
return info
}
async get() {
const info = await this.redis.get("k1")
return info
}
}至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。