Redis
Overview
@modularityjs/redis provides a shared ioredis client used by all Redis-backed drivers (cache-redis, lock-redis, queue-redis). It manages the connection lifecycle — connecting during boot and disconnecting on shutdown.
Setup
import { RedisModule } from '@modularityjs/redis';
const modules = [
RedisModule.forRoot({
host: 'localhost',
port: 6379,
}),
// ... Redis drivers
];Configuration
| Option | Default | Description |
|---|---|---|
host | 'localhost' | Redis server hostname |
port | 6379 | Redis server port |
password | - | Authentication password |
db | 0 | Database index |
keyPrefix | 'modularityjs:' | Prefix for all keys (used by drivers, not ioredis) |
lazyConnect | false | Defer connection until first command |
commandTimeoutMs | - | Per-command timeout (ioredis commandTimeout) |
maxRetriesPerRequest | - | ioredis per-request retry cap |
Key Prefixing
All Redis drivers build keys using the pattern:
{RedisConfig.keyPrefix}{driver namespace}{key}For example, with default config:
- Cache key
user:1becomesmodularityjs:cache:user:1 - Lock key
payment:123becomesmodularityjs:lock:payment:123 - Queue stream
ordersbecomesmodularityjs:queue:stream:orders
The prefix is not passed to ioredis's keyPrefix option (which breaks Lua scripts). Instead, each driver builds the full key manually for consistency across all Redis commands including eval.
Lifecycle
onInit— connects to Redis. If the connection fails, boot fails immediately.onShutdown— gracefully disconnects viaQUIT.
Direct Access
Inject RedisService for custom Redis operations beyond what the framework drivers provide:
import { Inject, Injectable } from '@modularityjs/di';
import { RedisService } from '@modularityjs/redis';
@Injectable()
class LeaderboardService {
constructor(@Inject(RedisService) private readonly redis: RedisService) {}
async addScore(userId: string, score: number): Promise<void> {
const client = this.redis.getClient();
await client.zadd('leaderboard', score, userId);
}
async getTopPlayers(count: number): Promise<string[]> {
const client = this.redis.getClient();
return client.zrevrange('leaderboard', 0, count - 1);
}
}getClient() returns the raw ioredis Redis instance. The global keyPrefix from RedisConfig is not applied automatically to direct client calls -- build keys manually when needed.
Environment Configuration
RedisModule does not register a ConfigSchemaPool entry and does not read from ConfigService. To configure Redis from environment variables, the consumer must read process.env (or query ConfigService against its own schema) and pass values to RedisModule.forRoot({...}):
RedisModule.forRoot({
host: process.env.REDIS_HOST ?? 'localhost',
port: Number(process.env.REDIS_PORT ?? 6379),
password: process.env.REDIS_PASSWORD,
});