Redis实现缓存 NestJS+Redis实现缓存步骤详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Redis实现缓存 NestJS+Redis实现缓存步骤详解

老胡Andy   2021-08-24 我要评论
想了解NestJS+Redis实现缓存步骤详解的相关内容吗,老胡Andy在本文为您仔细讲解Redis实现缓存的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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,验证结果:

参考:
https://www.learmoreseekmore.com/2020/12/nestjs-redis-cache.html

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们