文章图标

【学习资料】解锁 Nest.js 缓存的魔法:让你的应用飞起来!

简介图标

开发中,你是否遇到过这些情况: •数据库查询慢得像乌龟? •API 响应时间拖慢用户体验? •热门功能高频调用,服务器压力山大? 如果你点头了,恭喜你进入了缓存优化的世界!Nest.js 的缓存系统可以让你的应用性能从“拖拉机”一跃变成“高铁”。

stars0
favorites1
views80
kss 更新于3月前
广告图标

神奇小广告

一、为什么需要缓存?

开发中,你是否遇到过这些情况:

  • 数据库查询慢得像乌龟?
  • API 响应时间拖慢用户体验?
  • 热门功能高频调用,服务器压力山大?

如果你点头了,恭喜你进入了缓存优化的世界!Nest.js 的缓存系统可以让你的应用性能从“拖拉机”一跃变成“高铁”。



二、Nest.js 缓存概述

Nest.js 提供了开箱即用的缓存模块(CacheModule),基于 Node.js 的内存存储 或集成 Redis 等外部工具。你可以:

  1. 缓存 API 响应,减少重复计算。
  2. 优化数据库查询结果。
  3. 降低高频任务的系统负载。


三、快速上手:简单实现缓存

让我们来写点代码,感受下“缓存”的神奇力量!

1. 安装依赖

npm install @nestjs/common @nestjs/platform-express cache-manager  

2. 初始化缓存模块
AppModule 中引入 CacheModule

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

@Module({
  imports: [
    CacheModule.register({
      ttl: 5, // 缓存时间:5秒
      max: 10, // 最大缓存数量
    }),
  ],
})
export class AppModule {}

3. 缓存控制器响应
通过装饰器 @UseInterceptors 快速实现缓存:

import { Controller, Get, UseInterceptors, CacheInterceptor } from '@nestjs/common';

@Controller('data')
@UseInterceptors(CacheInterceptor) // 启用缓存拦截器
export class DataController {
  @Get()
  fetchData() {
    return { message: '这里是缓存的响应内容!' };
  }
}


四、进阶玩法:Redis 缓存

如果你的应用需要跨实例共享缓存,Redis 是一个完美的选择。只需三步:

1. 安装 Redis 和相关包

npm install cache-manager-redis-store redis  

2. 配置 Redis 缓存

import { CacheModule } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';

@Module({
  imports: [
    CacheModule.register({
      store: redisStore,
      host: 'localhost', // Redis 地址
      port: 6379,        // Redis 端口
    }),
  ],
})
export class AppModule {}

3. 使用缓存服务
利用 CacheService 进行手动缓存:

import { Injectable, CacheService } from '@nestjs/common';

@Injectable()
export class ExampleService {
  constructor(private readonly cacheManager: CacheService) {}

  async getCachedData(key: string) {
    const cached = await this.cacheManager.get(key);
    if (cached) {
      return cached;
    }
    const freshData = { message: '新鲜数据!' };
    await this.cacheManager.set(key, freshData, { ttl: 10 }); // 缓存10秒
    return freshData;
  }
}


五、缓存的最佳实践

  1. 合理设置 TTL(存活时间):避免数据陈旧。
  2. 选择合适的存储工具:如 Redis 支持分布式架构。
  3. 缓存重要而非全部数据:防止内存溢出。
  4. 定期清理缓存:避免“垃圾数据”堆积。


六、总结

Nest.js 的缓存工具既简单又强大,可以有效提升应用性能。当你的 API 响应秒回、数据库压力减轻时,你会明白,缓存真是开发者的“性能救星”!赶快试试吧!

登录后访问

您需要登录后才能访问此功能

请点击下方按钮登录您的账号,以便访问更多功能。

分享创造,拥抱快乐

本文由 kss 创作并发布于 绝对の领域KrzACG

参与讨论
精彩评论正在加载中...
sign-inGo to tasks