You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Restart your NestJS application
  2. Call the setCache method with a test key-value pair
  3. 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_HOST and REDIS_PORT in the useFactory to validate environment variables are loaded correctly

内容的提问来源于stack exchange,提问作者Jimin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 20:52:41