@wistle/cache
v1.0.2
Published
Cache management with Redis and LRU fallback for Wistle API using redis and lru-cache.
Downloads
20
Readme
@wistle/cache
Redis with LRU Cache Fallback
This project provides a Redis-based caching system with an LRU (Least Recently Used) cache as a fallback for environments where Redis may not be available. The package allows for cache operations like set
, get
, delete
, and clear
, with an optional Time-to-Live (TTL) functionality for expiring cache entries.
Features
- Redis-backed caching: Leverages Redis for distributed caching with automatic key expiration.
- LRU Cache fallback: Falls back to an in-memory LRU cache in development environments or when Redis is not available.
- Automatic TTL: Supports TTL (Time-to-Live) for expiring cache entries.
- Seamless switching: Automatically switches between Redis and LRU Cache based on environment availability.
- Multiple Cache Instances: Use
CacheProvider
to manage multiple Redis and LRU cache instances.
Installation
npm install @wistle/cache
Configuration
You can configure the cache system using the following options:
- Redis Config: Connection details for Redis (e.g., host, port).
- LRU Config: Options for the LRU cache, such as max cache size.
- Default TTL: The default expiration time for cached entries (in seconds).
Example configuration:
const redisConfig = {
url: 'redis://localhost:6379', // Redis connection URL
};
const lruOptions = {
max: 100, // Maximum number of items in LRU cache
};
const cache = new Cache({
redisOptions: redisConfig,
lruOptions: lruOptions,
defaultTTL: 3600, // 1-hour default TTL
});
await cache.connect(); // For redis
await cache.disconnect();
Usage with CacheProvider
If you need to manage multiple cache instances for different databases or configurations, you can use CacheProvider
.
Example:
import { CacheProvider } from '@wistle/cache';
const Config = {
default: {
redisOptions: {
url: 'redis://localhost:6379', // Redis config for default cache
}
},
sessionCache: {
redisOptions: {
url: 'redis://localhost:6378', // Redis config for default cache
},
lruOptions: {
max: 100, // Maximum number of items in LRU cache
}
}
};
// Initialize cache instances using CacheProvider
await CacheProvider.addConnections(redisConfig, lruOptions);
// Get the 'default' cache instance
const defaultCache = CacheProvider.getConnection();
// Set a value in the default cache
await defaultCache.set('user:1', { name: 'John Doe', age: 30 });
// Get the value from the default cache
const user = await defaultCache.get('user:1');
console.log(user); // { name: 'John Doe', age: 30 }
// Get the 'sessionCache' instance
const sessionCache = CacheProvider.getConnection('sessionCache');
await sessionCache.set('session:123', { token: 'abc123' });
const session = await sessionCache.get('session:123');
console.log(session); // { token: 'abc123' }
// Close all connections
await CacheProvider.closeAllConnections();
Basic Cache Operations
Here’s how you can perform cache operations using the Redis + LRU Cache system:
1. Set a Key-Value Pair in Cache:
await cache.set('user:1', { name: 'John Doe', age: 30 });
2. Get a Value from Cache:
const user = await cache.get('user:1');
console.log(user); // { name: 'John Doe', age: 30 }
3. Check if a Key Exists in Cache:
const exists = await cache.exists('user:1');
console.log(exists); // true
4. Delete a Key from Cache:
await cache.del('user:1');
const userAfterDelete = await cache.get('user:1');
console.log(userAfterDelete); // null
5. Clear All Keys from Cache:
await cache.clearAll();
Redis CLI Commands
If you're using Redis, here are some basic CLI commands you can use to interact with the Redis server.
- Set a key-value pair:
SET key "value"
- Get a key:
GET key
- Delete a key:
DEL key
- Check if a key exists:
EXISTS key
- Set a key with an expiration (TTL):
SET key "value" EX 60 # Expires in 60 seconds
- Flush all data:
FLUSHALL
Running the App
Ensure Redis is running (or configure fallback using LRU cache):
Start Redis server:
redis-server
Run your app:
Example:
node app.js
Example Code
import Cache from '@wistle/cache';
const redisConfig = {
url: 'redis://localhost:6379',
};
const lruOptions = {
max: 100, // Maximum 100 items in cache
};
const cache = new Cache({
redisOptions: null,
lruOptions: lruConfig,
defaultTTL: 3600, // 1-hour default TTL
});
(async () => {
// connect to Redis
await cache.connect();
// Set cache
await cache.set('user:1', { name: 'John Doe', age: 30 });
// Get cache
const user = await cache.get('user:1');
console.log(user); // { name: 'John Doe', age: 30 }
// Check existence
const exists = await cache.exists('user:1');
console.log('Exists:', exists); // true
// Delete cache
await cache.del('user:1');
console.log('User after delete:', await cache.get('user:1')); // null
// Clear cache
await cache.clearAll();
await cache.disconnect();
})();
License
This project is licensed under the MIT License.