Redis component for Midway.js framework providing comprehensive Redis database integration with support for single instances, clusters, and sentinel configurations
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
The RedisServiceFactory manages Redis client creation and lifecycle, supporting single Redis instances, Redis Cluster, and Redis Sentinel configurations through the Midway.js service factory pattern.
Core service factory extending Midway's ServiceFactory base class for managing Redis clients.
/**
* Service factory for creating and managing Redis client instances
* Supports single Redis, Redis Cluster, and Redis Sentinel configurations
*/
class RedisServiceFactory extends ServiceFactory<Redis> {
@Config('redis')
protected redisConfig: ServiceFactoryConfigOption<RedisConfigOptions>;
@Logger('coreLogger')
protected logger: ILogger;
@Init()
protected async init(): Promise<void>;
protected async createClient(config: RedisConfigOptions): Promise<Redis>;
getName(): string;
protected async destroyClient(redisInstance: Redis): Promise<void>;
// Inherited from ServiceFactory<Redis>
get(clientName?: string): Redis;
has(clientName: string): boolean;
getClients(): Map<string, Redis>;
getDefaultClientName(): string;
isLowPriority(clientName: string): boolean;
async stop(): Promise<void>;
}Creates Redis client instances based on configuration type detection.
/**
* Creates a Redis client based on configuration
* Automatically detects single, cluster, or sentinel setup
* @param config - Redis configuration options
* @returns Promise resolving to Redis client instance
*/
protected async createClient(config: RedisConfigOptions): Promise<Redis>;Configuration Detection Logic:
config.cluster === true: Creates Redis Cluster clientconfig.sentinels exists: Creates Redis Sentinel clientUsage Examples:
import { RedisServiceFactory } from "@midwayjs/redis";
import { Inject } from "@midwayjs/core";
export class DataService {
@Inject()
redisFactory: RedisServiceFactory;
async getRedisClient(clientName = 'default') {
// Get specific named client
return this.redisFactory.get(clientName);
}
async getCacheClient() {
// Get named client for caching
return this.redisFactory.get('cache');
}
}Returns the service identifier used by Midway's service factory system.
/**
* Returns the service name identifier
* @returns Service name 'redis'
*/
getName(): string;Safely closes Redis connections during application shutdown.
/**
* Safely destroys a Redis client instance
* Handles graceful shutdown with quit() when client is ready
* @param redisInstance - Redis client to destroy
* @returns Promise that resolves when client is closed
*/
protected async destroyClient(redisInstance: Redis): Promise<void>;Checks if a client has low priority for health monitoring exclusion.
/**
* Determines if a client is marked as low priority
* Low priority clients are excluded from health check failures
* @param clientName - Name of the client to check
* @returns True if client has low priority
*/
isLowPriority(clientName: string): boolean;// config/config.default.ts
export default {
redis: {
client: {
host: 'localhost',
port: 6379,
password: 'your-password',
db: 0,
family: 4,
connectTimeout: 10000,
lazyConnect: true,
}
}
};// config/config.default.ts
export default {
redis: {
client: {
cluster: true,
nodes: [
{ host: 'redis-node-1', port: 6379 },
{ host: 'redis-node-2', port: 6379 },
{ host: 'redis-node-3', port: 6379 }
],
// Cluster-specific options
enableOfflineQueue: false,
// Redis options applied to all cluster nodes
redisOptions: {
password: 'your-password',
family: 4,
connectTimeout: 10000,
commandTimeout: 5000,
retryDelayOnFailover: 100,
maxRetriesPerRequest: 3
}
}
}
};// config/config.default.ts
export default {
redis: {
client: {
sentinels: [
{ host: 'sentinel-1', port: 26379 },
{ host: 'sentinel-2', port: 26379 },
{ host: 'sentinel-3', port: 26379 }
],
name: 'mymaster',
password: 'your-password',
}
}
};// config/config.default.ts
export default {
redis: {
clients: {
default: {
host: 'localhost',
port: 6379,
db: 0,
},
cache: {
host: 'cache-server',
port: 6379,
db: 1,
},
session: {
cluster: true,
nodes: [
{ host: 'session-node-1', port: 6379 },
{ host: 'session-node-2', port: 6379 }
]
}
},
// Client priority configuration for health checks
priority: {
cache: 'Low', // Exclude from health check failures
session: 'High' // Include in health check evaluation (default)
}
}
};The service factory includes comprehensive validation and error handling:
The factory performs strict validation on configuration:
// Single instance validation
assert(config.host && config.port,
`[midway:redis] 'host: ${config.host}', 'port: ${config.port}' are required on config`);
// Cluster validation
assert(config.nodes && config.nodes.length !== 0,
'[midway:redis] cluster nodes configuration is required when use cluster redis');
config.nodes.forEach(client => {
assert(client.host && client.port,
`[midway:redis] 'host: ${client.host}', 'port: ${client.port}' are required on config`);
});
// Sentinel validation
assert(config.sentinels && config.sentinels.length !== 0,
'[midway:redis] sentinels configuration is required when use redis sentinel');
config.sentinels.forEach(sentinel => {
assert(sentinel.host && sentinel.port,
`[midway:redis] 'host: ${sentinel.host}', 'port: ${sentinel.port}' are required on config`);
});As a ServiceFactory subclass, RedisServiceFactory inherits standard factory methods:
get(clientName?: string): Get a client instance by namehas(clientName: string): Check if a client existsgetClients(): Get all client instancesstop(): Stop all clients during shutdown