NestJS 11.0.11 Redis缓存配置问题:缓存未写入Redis服务器
Solution for Redis Cache Not Storing Data in NestJS 11
1. Install Required Dependencies
Ensure you have the correct packages installed for NestJS 11 and cache-manager v5:
npm install @nestjs/cache-manager cache-manager cache-manager-redis-store
2. Correct CacheModule Configuration
Your current setup has two critical issues: using the plural stores property instead of singular store, and not invoking the redisStore function with connection options. Update your configuration to:
import { redisStore } from 'cache-manager-redis-store'; // ... CacheModule.registerAsync({ isGlobal: true, inject: [ConfigService], useFactory: async (configService: ConfigService) => ({ store: await redisStore({ host: configService.get<string>('REDIS_HOST'), port: configService.get<number>('REDIS_PORT'), // Add password here if your Redis instance requires authentication // password: configService.get<string>('REDIS_PASSWORD'), }), ttl: 60, // Default TTL in seconds }), }),
3. Adjust CacheService Usage
Update your service to match cache-manager v5's syntax for TTL (pass as an options object):
import { Inject, Injectable } from '@nestjs/common'; import { Cache, CACHE_MANAGER } from '@nestjs/cache-manager'; @Injectable() export class CacheService { constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {} async setCache(key: string, value: any, ttl?: number): Promise<void> { await this.cacheManager.set(key, value, ttl ? { ttl } : undefined); } async getCache(key: string): Promise<string | null> { return await this.cacheManager.get(key); } }
4. Validate the Setup
After applying changes:
- Restart your NestJS application
- Call the
setCachemethod with a test key-value pair - Verify the data exists in Redis using
redis-cli:
redis-cli GET your-test-key
Additional Checks
- Confirm your Docker Redis container is accessible (ensure it’s on the same network as your app or the port is published)
- Log
REDIS_HOSTandREDIS_PORTin theuseFactoryto validate environment variables are loaded correctly
内容的提问来源于stack exchange,提问作者Jimin
相关产品推荐
相关产品推荐

