Redis Store for node-cache-manager

3.0.1 · active · verified Sun Apr 19

cache-manager-redis-store is a dedicated Redis store for the `node-cache-manager` library, providing a performant and reliable caching layer for Node.js applications. The current stable version is 3.0.1, released in October 2022. It generally follows an irregular release cadence, often aligning with major dependency updates or critical bug fixes. This package differentiates itself from older alternatives like `node-cache-manager-redis` by avoiding the `redis-pool` library, instead offering a simpler wrapper that directly passes configuration to the underlying `redis` client (upgraded to `redis@^4` in v3.0.0). It aims to provide a straightforward integration for Redis caching within the `node-cache-manager` ecosystem, with robust support for both single and multi-store caching setups. The library also provides TypeScript types, enhancing the developer experience for TypeScript projects.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing a Redis store for `cache-manager` v4+, performing basic set/get operations, using the `wrap` method for data fetching, and setting up multi-store caching with both Redis and in-memory caches. It highlights the correct store instantiation for v3.x and promises-based API.

import { caching, multiCaching } from 'cache-manager';
import redisStore from 'cache-manager-redis-store';

// Configure Redis client options (e.g., host, port, password)
const redisOptions = {
  host: process.env.REDIS_HOST ?? 'localhost',
  port: parseInt(process.env.REDIS_PORT ?? '6379', 10),
  password: process.env.REDIS_PASSWORD ?? '', // Use environment variables for sensitive info
  db: 0,
  ttl: 600, // Default TTL in seconds
};

async function initializeAndUseCache() {
  // Create an instance of the Redis store
  const redisCacheStore = redisStore(redisOptions);

  // Initialize a single cache manager with the Redis store instance
  const redisCache = caching({ store: redisCacheStore, ttl: 600 });

  // Listen for Redis connection errors
  // Note: For redis@^4, client events might be handled differently, 
  // often through the client instance returned by `redisCacheStore.getClient()`.
  const redisClient = await redisCacheStore.getClient();
  redisClient.on('error', (error: Error) => {
    console.error('Redis Client Error:', error);
  });

  // Set a value
  await redisCache.set('foo', 'bar', 5); // TTL of 5 seconds
  console.log('Set foo to bar with TTL 5s');

  // Get a value
  const result = await redisCache.get('foo');
  console.log(`Get foo: ${result}`); // Expected: 'bar'

  // Wrap: fetches from cache, or executes function and caches result
  async function getSlowUser(id: number) {
    console.log(`Returning user ${id} from slow database.`);
    return new Promise(resolve => setTimeout(() => resolve({ id, name: `User ${id}` }), 100));
  }

  const userId = 123;
  const userKey = `user_${userId}`;

  const user1 = await redisCache.wrap(userKey, () => getSlowUser(userId), { ttl: 10 });
  console.log('Wrapped user (first call):', user1); // Logs 'Returning user from slow database.'

  const user2 = await redisCache.wrap(userKey, () => getSlowUser(userId), { ttl: 10 });
  console.log('Wrapped user (second call):', user2); // Fetches from cache, no 'slow database' log

  // --- Multi-store caching ---
  const memoryCacheStore = caching({ store: 'memory', max: 100, ttl: 60 });
  const multiCache = multiCaching([memoryCacheStore, redisCache]);

  const multiUserKey = 'multiUser_456';
  const multiUser = await multiCache.wrap(multiUserKey, () => getSlowUser(456), { ttl: 15 });
  console.log('Multi-cache wrapped user (first call):', multiUser);

  // Subsequent calls fetch from the highest priority cache (memoryCacheStore)
  const multiUser2 = await multiCache.wrap(multiUserKey, () => getSlowUser(456), { ttl: 15 });
  console.log('Multi-cache wrapped user (second call):', multiUser2);

  // Clean up
  await redisCache.del('foo');
  await redisCache.del(userKey);
  await multiCache.del(multiUserKey);
  console.log('Cleaned up cache entries.');
}

initializeAndUseCache().catch(console.error);

view raw JSON →