This guide provides a step-by-step process for integrating Redis caching into a NestJS application using Docker and the @keyv/redis package. Redis is an in-memory key-value store that significantly improves application performance by reducing repeated database queries and external API calls. The @keyv/redis package offers a consistent interface and built-in TypeScript support for integrating Redis with minimal configuration.
1. Setting Up Redis Using Docker (Windows CMD)
Prerequisites
- Ensure Docker Desktop is installed and running on your system.
- Open Command Prompt (CMD).
Step 1: Pull the Redis Image
docker pull redis
Step 2: Run the Redis Container
docker run -d --name redis-server -p 6379:6379 redis
Explanation:
-
-d
: Run container in detached mode (in the background). -
--name redis-server
: Assigns a name to the container. -
-p 6379:6379
: Maps port 6379 of the container to port 6379 on the host machine.
Step 3: Verify the Redis Container is Running
docker ps
Step 4: Access Redis CLI (Optional)
docker exec -it redis-server redis-cli
You can now run Redis commands such as:
set mykey "hello"
get mykey
Step 5: Stop the Redis Container
docker stop redis-server
Step 6: Restart the Redis Container
docker start redis-server
Step 7: View Cache Data in Redis Insight
You can install Redis Insight (GUI tool) to visualize and monitor cached data. It displays keys and their corresponding values stored in Redis.
2. Setting Up Redis In Code
- Installing Required Packages in NestJS Run the following commands to install necessary packages:
npm install @nestjs/cache-manager cache-manager
npm install @keyv/redis
- Configuring Redis Caching in app.module.ts Update your AppModule to register the Redis cache globally using CacheModule:
import { Module } from '@nestjs/common';
import { createKeyv } from '@keyv/redis';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { CacheInterceptor, CacheModule } from '@nestjs/cache-manager';
@Module({
imports: [
CacheModule.registerAsync({
useFactory: async () => ({
stores: [createKeyv('redis://localhost:6379')],
ttl: 60 * 1000,
}),
isGlobal: true,
}),
],
providers: [
{
provide: APP_INTERCEPTOR,
useClass: CacheInterceptor,
},
],
})
export class AppModule {}
Explanation:
-
ttl
: Time-to-live for the cache in milliseconds (60,000 ms = 1 minute). -
isGlobal: true
: Makes caching available across the entire application. -
CacheInterceptor
: Automatically caches controller responses based on route and parameters.
- How Redis Caching Works in NestJS Once caching is configured globally:
- Responses from controller endpoints are cached automatically.
- The key is derived from the route and its parameters.
- The value is the serialized response.
- Redis Insight can be used to verify the stored data.
For example:
KEY: "GET_/users"
VALUE: JSON response of the /users route
- Additional Notes
- Ensure Redis is running before starting your NestJS application.
- For production use, consider securing your Redis server with authentication and SSL.
You can manually manage cache using the
CACHE_MANAGER
injection token from@nestjs/cache-manager
for more granular control.Enabling Caching for a Single API Endpoint
While Redis caching can be enabled globally using the CacheInterceptor, you can also enable it selectively for individual routes using the @UseInterceptors decorator in your controller.
Here’s how to cache a single API endpoint:
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor } from '@nestjs/cache-manager';
@Controller('users')
export class UserController {
@Get()
@UseInterceptors(CacheInterceptor)
findAll() {
// Your service logic
}
}
In the above example:
- Only the
GET /users
route will be cached. - This approach is helpful when you want to cache specific endpoints instead of globally.
Top comments (0)