NestJS+Redis實現(xiàn)緩存步驟詳解
NestJS的緩存模塊天生支持Redis等緩存機(jī)制。以下通過一個示例,說明如何在NestJS中操作Redis。步驟如下:
先安裝運(yùn)行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)文章
Redis Subscribe timeout 報錯的問題解決
最近系統(tǒng)偶爾報出org.redisson.client.RedisTimeoutException: Subscribe timeout: (7500ms)的錯誤,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-08-08
Linux下安裝Redis并設(shè)置相關(guān)服務(wù)
這篇文章主要為大家介紹了Linux下安裝Redis并設(shè)置相關(guān)服務(wù),感興趣的小伙伴們可以參考一下2016-01-01
Redis?中ZSET數(shù)據(jù)類型命令使用及對應(yīng)場景總結(jié)(案例詳解)
這篇文章主要介紹了Redis?中ZSET數(shù)據(jù)類型命令使用及對應(yīng)場景總結(jié),本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-01-01

