NestJS Enterprise Backend APIs · 课时

缓存策略(Redis)

使用 Redis 实现各种缓存策略,以减少数据库负载并缩短 API 响应时间。

第 1 / 6 课11 个步骤

缓存策略(Redis) 是 CoddyKit 上的免费 NestJS Enterprise Backend APIs 课时。 这是第 1 节课,共 6 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 NestJS Enterprise Backend APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 NestJS Enterprise Backend APIs 课程共包含 6 节课。

本课时的部分内容尚未翻译,以英文显示。

Boosting API Performance with Caching

Welcome to Caching Strategies with Redis! In this lesson, we'll explore how to drastically improve your NestJS API's performance and responsiveness.

Caching is a technique where frequently accessed data is stored temporarily in a faster-access memory layer. This helps avoid repeated, expensive operations like database queries or complex computations.

Why Caching Matters

Imagine an API endpoint that fetches popular products. Every time a user requests this data, your server might perform a database query, which can be slow and resource-intensive.

  • Reduced Latency: Users get data faster.
  • Lower Database Load: Your database works less, preventing bottlenecks.
  • Improved Scalability: Your application can handle more users without slowing down.

Caching acts as a buffer, serving data quickly from memory instead of always hitting the primary data source.

Meet Redis: Your In-Memory Cache

Redis (Remote Dictionary Server) is a popular open-source, in-memory data structure store. It's often used as a database, cache, and message broker.

  • Speed: Redis stores data in RAM, making read/write operations incredibly fast.
  • Versatility: It supports various data structures like strings, hashes, lists, sets, and more.
  • Persistence: While primarily in-memory, Redis can persist data to disk for durability.

For caching, Redis's speed and simple key-value model make it an ideal choice.

Redis Basics: Key-Value Operations

Redis stores data as simple key-value pairs. You assign a unique key to a piece of data, then use that key to retrieve it later. Here's how it looks conceptually using the Redis CLI:

# Connect to Redis CLI
redis-cli

# Store a value with a key
SET myapi:users:123 '{"name":"Alice"}'

# Retrieve the value using its key
GET myapi:users:123

# Set a value with an expiration time (10 seconds)
SETEX myapi:temp:data 10 'Expires Soon'

NestJS CacheModule Setup

NestJS provides a flexible CacheModule to integrate various caching solutions. To use Redis, we'll install @nestjs/cache-manager and cache-manager-redis-store.

First, install the packages:

npm install @nestjs/cache-manager cache-manager-redis-store cache-manager

Then, configure your AppModule to use Redis:

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

@Module({
  imports: [
    CacheModule.register({
      store: redisStore,
      host: 'localhost',
      port: 6379,
      ttl: 300 // default time-to-live in seconds
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

Automatic Caching with CacheInterceptor

For simple GET endpoints, NestJS offers the CacheInterceptor. This interceptor automatically caches the response of a method and serves it from the cache on subsequent requests.

You can apply it globally or to specific controllers/methods using decorators:

import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor, CacheKey, CacheTTL } from '@nestjs/cache-manager';

@Controller('products')
@UseInterceptors(CacheInterceptor) // Apply to all methods in this controller
export class ProductsController {

  @Get()
  @CacheKey('all_products') // Unique key for this cache entry
  @CacheTTL(60) // Cache for 60 seconds (overrides module default)
  async findAll() {
    // In a real app, this would fetch from a database
    console.log('Fetching all products from DB...');
    return [{ id: 1, name: 'Laptop' }, { id: 2, name: 'Mouse' }];
  }
}

Understanding CacheKey and CacheTTL

When using CacheInterceptor, two key decorators help you control caching:

  • @CacheKey('your_key_name'): This decorator defines the unique key under which the response data will be stored in Redis. If not provided, NestJS generates one based on the request path.
  • @CacheTTL(seconds): This sets the Time-To-Live for the cached entry in seconds. After this duration, the cached data expires and will be re-fetched from the original source. If omitted, it uses the default ttl from CacheModule.register().

These allow you to fine-tune how long specific data remains cached.

Manual Caching with CacheManager

Sometimes, you need more control than what CacheInterceptor offers, for example, caching parts of a response or invalidating cache entries programmatically.

You can inject the CacheManager service and use its methods directly:

import { Controller, Get, Post, Inject, Param } from '@nestjs/common';
import { Cache } from 'cache-manager';
import { CACHE_MANAGER } from '@nestjs/cache-manager';

@Controller('users')
export class UsersController {
  constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}

  @Get(':id')
  async findOne(@Param('id') id: string) {
    const cacheKey = `user_${id}`;
    const cachedUser = await this.cacheManager.get(cacheKey);

    if (cachedUser) {
      console.log('Serving from cache!');
      return cachedUser;
    }

    // Simulate fetching from DB
    const user = { id, name: `User ${id}`, email: `user${id}@example.com` };
    await this.cacheManager.set(cacheKey, user, 600); // Cache for 10 mins

    console.log('Serving from DB and caching...');
    return user;
  }

  @Post('clear-all')
  async clearAllCache() {
    await this.cacheManager.reset(); // Clear all cache entries
    return 'Cache cleared!';
  }
}

Cache Invalidation Strategies

A critical aspect of caching is ensuring data freshness. Stale data can lead to incorrect information being served.

  • Time-To-Live (TTL): The simplest strategy, data expires automatically after a set time.
  • Cache-Aside: Application code explicitly fetches from cache, then DB if not found, and updates cache.
  • Write-Through: Data is written to cache and then to the database simultaneously.
  • Write-Back: Data is written to cache, then asynchronously written to the database.
  • Event-Driven Invalidation: When data changes in the database, an event is triggered to invalidate or update the corresponding cache entry.

Choosing the right strategy depends on your application's consistency requirements.

Quick Check: Caching Benefits

Consider a NestJS API endpoint that frequently fetches a list of popular products from a database. This database call is slow due to complex joins and large data volumes.

Caching with Redis: Recap

Great job! You've learned the fundamentals of caching with Redis in NestJS:

  • Caching significantly boosts API performance, reduces database load, and improves scalability.
  • Redis is an excellent choice for an in-memory cache due to its speed and versatility.
  • NestJS's CacheModule simplifies Redis integration using cache-manager-redis-store.
  • You can use the @CacheInterceptor with @CacheKey and @CacheTTL for automatic caching on controller methods.
  • For more control, inject CACHE_MANAGER to manually interact with Redis.
  • Understanding cache invalidation strategies is crucial for maintaining data freshness.

Start implementing caching to make your NestJS applications blazing fast!

免费开始

用 AI 导师学习 TypeScript — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
20
课程
76

常见问题解答

「缓存策略(Redis)」课时是免费的吗?

是的 — 「缓存策略(Redis)」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 NestJS Enterprise Backend APIs 课程的其余内容,请升级到 CoddyKit PRO。 NestJS Enterprise Backend APIs 课程共包含 6 节课。

「缓存策略(Redis)」这节课中我会学到什么?

使用 Redis 实现各种缓存策略,以减少数据库负载并缩短 API 响应时间。 你通过在浏览器中直接运行的动手代码来练习 NestJS Enterprise Backend APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 NestJS Enterprise Backend APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 NestJS Enterprise Backend APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 6 节。

「缓存策略(Redis)」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 NestJS Enterprise Backend APIs 课中编写并运行代码吗?

能。每节 NestJS Enterprise Backend APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 缓存策略(Redis)
  2. 数据库性能监控
  3. 负载均衡与代理
  4. 查询优化策略
  5. 无服务器部署
  6. 扩展您的 Supabase 项目
← 返回 NestJS Enterprise Backend APIs