import { Injectable, Inject, Module } from '@nestjs/common'; import { CacheModule, CACHE_MANAGER } from '@nestjs/cache-manager'; import type { Cache } from 'cache-manager'; @Injectable() export class SampleService { constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {} async cacheAndGet() { await this.cacheManager.set('key', 'hello'); return await this.cacheManager.get('key'); } } @Module({ imports: [CacheModule.register()], providers: [SampleService], }) export class AppModule {}
By default, NestJS CacheModule uses an in-memory store. Setting a key and then getting it immediately returns the stored value.
To use Redis with NestJS CacheModule, you must pass the Redis store package (like 'cache-manager-redis-store') as the store option. Other options are incorrect or incomplete.
Memory cache is local to each process. In a clustered environment, each instance has its own memory space, so caches are isolated.
CacheModule.register({ store: require('cache-manager-redis-store'), host: '127.0.0.1', port: 6380 })If Redis is not running or listening on the configured port, connection errors occur. The host and store usage are correct.
Redis is an external cache that supports sharing data across multiple app instances and persists data beyond restarts, unlike the in-memory store.
