NestJS+Redis實現(xiàn)緩存步驟詳解
NestJS的緩存模塊天生支持Redis等緩存機制。以下通過一個示例,說明如何在NestJS中操作Redis。步驟如下:
先安裝運行Redis服務(wù),步驟參見鏈接
新建nestjs項目:
nest new [項目名稱]
安裝cache相關(guān)依賴
npm install cache-manager npm install -D @types/cache-manager npm install cache-manager-redis-store --save
注冊Redis Store
打開src->app.module.ts,這里假設(shè)已經(jīng)在本地安裝啟動了Redis服務(wù)
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緩存服務(wù)
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,驗證結(jié)果:
參考:
https://www.learmoreseekmore.com/2020/12/nestjs-redis-cache.html
到此這篇關(guān)于NestJS+Redis實現(xiàn)緩存的文章就介紹到這了,更多相關(guān)Redis實現(xiàn)緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
php結(jié)合redis實現(xiàn)高并發(fā)下的搶購、秒殺功能的實例
下面小編就為大家?guī)硪黄猵hp結(jié)合redis實現(xiàn)高并發(fā)下的搶購、秒殺功能的實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12為什么RedisCluster設(shè)計成16384個槽
本文主要介紹了為什么RedisCluster設(shè)計成16384個槽,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09異步redis隊列實現(xiàn) 數(shù)據(jù)入庫的方法
今天小編就為大家分享一篇異步redis隊列實現(xiàn) 數(shù)據(jù)入庫的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10基于Redis位圖實現(xiàn)系統(tǒng)用戶登錄統(tǒng)計
這篇文章主要介紹了基于Redis位圖實現(xiàn)系統(tǒng)用戶登錄統(tǒng)計,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11