NestJS的緩存模塊天生支持Redis等緩存機制。以下通過一個示例,說明如何在NestJS中操作Redis。步驟如下:
先安裝運行Redis服務,步驟參見鏈接
新建nestjs項目:
nest new [項目名稱]
安裝cache相關依賴
1
2
3
|
npm install cache-manager npm install -D @types /cache-manager npm install cache-manager-redis-store --save |
注冊Redis Store
打開src->app.module.ts,這里假設已經在本地安裝啟動了Redis服務
1
2
3
4
5
6
7
8
9
10
|
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緩存服務
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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
到此這篇關于NestJS+Redis實現緩存的文章就介紹到這了,更多相關Redis實現緩存內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/Andy1982/p/15178639.html