CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-midwayjs--redis

Redis component for Midway.js framework providing comprehensive Redis database integration with support for single instances, clusters, and sentinel configurations

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

service-factory.mddocs/

Service Factory

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.

Capabilities

RedisServiceFactory Class

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>;
}

Client Creation

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:

  • If config.cluster === true: Creates Redis Cluster client
  • If config.sentinels exists: Creates Redis Sentinel client
  • Otherwise: Creates single Redis instance client

Usage 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');
  }
}

Service Name

Returns the service identifier used by Midway's service factory system.

/**
 * Returns the service name identifier
 * @returns Service name 'redis'
 */
getName(): string;

Client Destruction

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>;

Priority Management

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;

Configuration Examples

Single Redis Instance

// config/config.default.ts
export default {
  redis: {
    client: {
      host: 'localhost',
      port: 6379,
      password: 'your-password',
      db: 0,
      family: 4,
      connectTimeout: 10000,
      lazyConnect: true,
    }
  }
};

Redis Cluster

// 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
      }
    }
  }
};

Redis Sentinel

// 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',
    }
  }
};

Multi-Client Configuration

// 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)
    }
  }
};

Error Handling

The service factory includes comprehensive validation and error handling:

  • Configuration Validation: Assertions ensure required host/port for single instances
  • Cluster Validation: Validates that nodes array is provided and populated for cluster mode
  • Sentinel Validation: Ensures sentinels array and master name are configured
  • Connection Monitoring: Listens for connect/error events during client initialization
  • Graceful Shutdown: Handles client destruction with proper error logging

Configuration Validation Details

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`);
});

Inherited Methods

As a ServiceFactory subclass, RedisServiceFactory inherits standard factory methods:

  • get(clientName?: string): Get a client instance by name
  • has(clientName: string): Check if a client exists
  • getClients(): Get all client instances
  • stop(): Stop all clients during shutdown

docs

configuration.md

index.md

redis-service.md

service-factory.md

tile.json