# Redis Client

The Redis client is the core class for connecting to standalone Redis servers or Sentinel-managed deployments. It provides comprehensive Redis command support with full TypeScript typing and robust connection management.

## Capabilities

### Redis Class

Main client class for Redis connections supporting various connection patterns and configuration options.

```typescript { .api }
class Redis extends EventEmitter {
  constructor();
  constructor(port: number);
  constructor(path: string);
  constructor(options: RedisOptions);
  constructor(port: number, options: RedisOptions);
  constructor(port: number, host: string);
  constructor(port: number, host: string, options: RedisOptions);
  constructor(path: string, options: RedisOptions);
  
  // Connection management
  connect(callback?: Callback<void>): Promise<void>;
  disconnect(reconnect?: boolean): void;
  quit(callback?: Callback<"OK">): Promise<"OK">;
  duplicate(override?: Partial<RedisOptions>): Redis;
  
  // Properties
  readonly options: RedisOptions;
  readonly status: RedisStatus;
  readonly mode: ConnectionMode;
  readonly autoPipelineQueueSize: number;
  
  // Command execution
  sendCommand(command: Command, stream?: WriteableStream): void;
  call(command: string, ...args: any[]): Promise<unknown>;
}

type RedisStatus = "wait" | "reconnecting" | "connecting" | "connect" | "ready" | "close" | "end";
type ConnectionMode = "normal" | "subscriber" | "monitor";
```

**Usage Examples:**

```typescript
import Redis from "ioredis";

// Basic connection
const redis = new Redis(); // localhost:6379

// Connection with options
const redis2 = new Redis({
  host: "redis.example.com",
  port: 6380,
  password: "secret",
  db: 1,
  retryStrategy: (times) => Math.min(times * 50, 2000)
});

// Unix socket connection
const redis3 = new Redis("/tmp/redis.sock");

// Duplicate connection with overrides
const duplicate = redis.duplicate({ db: 2 });
```

### Factory Method

Node.js Redis compatibility factory method for creating Redis instances.

```typescript { .api }
static createClient(...args: any[]): Redis;
```

```typescript
// Node.js redis compatibility
const redis = Redis.createClient();
const redis2 = Redis.createClient({ url: "redis://localhost:6379" });
```

### Connection Events

The Redis client emits various events for connection lifecycle management.

```typescript { .api }
// Connection events
on(event: 'connect', listener: () => void): this;
on(event: 'ready', listener: () => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'close', listener: () => void): this;
on(event: 'reconnecting', listener: (ms: number) => void): this;
on(event: 'end', listener: () => void): this;

// Pub/Sub events
on(event: 'message', listener: (channel: string, message: string) => void): this;
on(event: 'pmessage', listener: (pattern: string, channel: string, message: string) => void): this;
on(event: 'messageBuffer', listener: (channel: Buffer, message: Buffer) => void): this;
on(event: 'pmessageBuffer', listener: (pattern: Buffer, channel: Buffer, message: Buffer) => void): this;
```

**Usage Examples:**

```typescript
const redis = new Redis();

redis.on('connect', () => {
  console.log('Connected to Redis');
});

redis.on('ready', () => {
  console.log('Redis is ready to receive commands');
});

redis.on('error', (err) => {
  console.error('Redis error:', err);
});

redis.on('reconnecting', (ms) => {
  console.log(`Reconnecting in ${ms}ms`);
});
```

### Monitor Mode

Monitor mode allows inspection of all commands processed by the Redis server.

```typescript { .api }
monitor(callback?: Callback<Redis>): Promise<Redis>;
```

```typescript
// Enter monitor mode
const monitor = await redis.monitor();

monitor.on('monitor', (time, args, source, database) => {
  console.log(`${time}: COMMAND ${args.join(' ')} (from ${source} on db ${database})`);
});
```

## Connection Management

### Connection Lifecycle

The Redis client provides precise control over connection establishment and termination.

```typescript { .api }
// Establish connection
connect(callback?: Callback<void>): Promise<void>;

// Immediate disconnection (may lose data)
disconnect(reconnect?: boolean): void;

// Graceful shutdown (waits for pending commands)
quit(callback?: Callback<"OK">): Promise<"OK">;
```

**Usage Examples:**

```typescript
const redis = new Redis({ lazyConnect: true });

// Manual connection
await redis.connect();

// Graceful shutdown
await redis.quit();

// Force disconnection
redis.disconnect();
```

### Connection Duplication

Create new Redis instances sharing configuration but with independent connections.

```typescript { .api }
duplicate(override?: Partial<RedisOptions>): Redis;
```

```typescript
const redis = new Redis({ host: "redis.example.com" });

// Duplicate with same config
const dup1 = redis.duplicate();

// Duplicate with overrides
const dup2 = redis.duplicate({ 
  db: 2,
  password: "different-password" 
});
```

## Types

```typescript { .api }
type Callback<T> = (err?: Error | null, result?: T) => void;

interface WriteableStream {
  writable: boolean;
  write(buffer: any, cb?: Function): boolean;
}
```