NestJS+Redis实现页面级缓存

前一篇文章讲述了NestJS对缓存服务器Redis的支持,用包装(简化)过的接口直接操作Redis。
这里再介绍一下如何通过NestJS实现页面级缓存, 类似asp.net中的output cache。 NestJS真的是拉近了前后端的差距,后端主流框架有的,NestJS几乎都具备。

基于上一篇的示例代码,做如下修改
src -> app.module.ts 此处注入缓存拦截器

import { Module, CacheModule, CacheInterceptor } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';

providers: [
  {
    provide: APP_INTERCEPTOR,
    useClass: CacheInterceptor,
  },
  ViewService,
],

src -> app.controller.ts 在对应的控制器上使用缓存

import {
  Controller,
  Get,
  Res,
  Req,
  Inject,
  CACHE_MANAGER,
  UseInterceptors,
  CacheInterceptor,
  CacheKey,
  CacheTTL,
} from '@nestjs/common';

@UseInterceptors(CacheInterceptor)
export class AppController {
  /*此处省略其它代码*/

  @Get('api-cache')
  @CacheKey('api-cache-demo')
  @CacheTTL(30)
  public getByCache() {
    console.log('call api at ', Date.now());
    return 'Hello world!';
  }
}

访问该接口(api-cache),会看到返回的响应结果被存储在Redis中,并且在TTL到期前都会返回Redis中的内容。

posted @ 2021-08-24 12:01  老胡Andy  阅读(382)  评论(0编辑  收藏  举报