怎么用NestJS+Redis实现缓存

2024-03-14,

这篇文章主要介绍“怎么用NestJS+Redis实现缓存”,在日常操作中,相信很多人在怎么用NestJS+Redis实现缓存问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么用NestJS+Redis实现缓存”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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,验证结果:

到此,关于“怎么用NestJS+Redis实现缓存”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注本站网站,小编会继续努力为大家带来更多实用的文章!

《怎么用NestJS+Redis实现缓存.doc》

下载本文的Word格式文档,以方便收藏与打印。