NestJS的緩存模塊天生支持Redis等緩存機制。以下通過一個示例,說明如何在NestJS中操作Redis。步驟如下:
先安裝運行Redis服務,步驟參見鏈接
新建nestjs項目:
nest new [項目名稱]
安裝cache相關依賴
npm install cache-manager
npm install -D @types/cache-manager
npm install cache-manager-redis-store --save
注冊Redis Store
打開src->app.module.ts,這里假設已經在本地安裝啟動了Redis服務
import { Module, CacheModule } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';
imports: [
CacheModule.register({
store: redisStore,
host: 'localhost',
port: 6379,
}),
],
打開src->app.controller.ts, 使用Redis緩存服務
import {
Controller,
Get,
Res,
Req,
Inject,
CACHE_MANAGER,
} from '@nestjs/common';
import { Cache } from 'cache-manager';
fakeString = 'Hello World!';
@Get('cache-test')
async setGetSimpleString() {
const value = await this.cacheManager.get('my-string');
if (value) {
return {
data: value,
loadsFrom: 'redis cache',
};
}
await this.cacheManager.set('my-string', this.fakeString, { ttl: 20 });
return {
data: this.fakeString,
loadsFrom: 'fake database',
};
}
最后,訪問接口,打開Redis客戶端工具RedisNav,驗證結果:
參考:
https://www.learmoreseekmore.com/2020/12/nestjs-redis-cache.html