0
# @midwayjs/redis
1
2
@midwayjs/redis is a Redis component for the Midway.js Node.js framework that provides comprehensive Redis database integration capabilities. It serves as a service factory wrapper around the ioredis library, offering support for single Redis instances, Redis Sentinel high-availability setups, and Redis Cluster configurations with automatic client lifecycle management.
3
4
## Package Information
5
6
- **Package Name**: @midwayjs/redis
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @midwayjs/redis`
10
- **Dependencies**: ioredis@5.4.2
11
12
## Core Imports
13
14
```typescript
15
import { RedisService, RedisServiceFactory, Configuration } from "@midwayjs/redis";
16
```
17
18
For accessing the original ioredis class:
19
20
```typescript
21
import { Redis } from "@midwayjs/redis";
22
```
23
24
## Basic Usage
25
26
```typescript
27
import { RedisService } from "@midwayjs/redis";
28
import { Inject } from "@midwayjs/core";
29
30
// In a Midway.js service or controller
31
export class UserService {
32
@Inject()
33
redisService: RedisService;
34
35
async cacheUser(id: string, userData: any) {
36
// Use like standard ioredis - all Redis methods available
37
await this.redisService.set(`user:${id}`, JSON.stringify(userData));
38
await this.redisService.expire(`user:${id}`, 3600);
39
}
40
41
async getUser(id: string) {
42
const cached = await this.redisService.get(`user:${id}`);
43
return cached ? JSON.parse(cached) : null;
44
}
45
}
46
```
47
48
## Architecture
49
50
@midwayjs/redis is built around several key components:
51
52
- **Service Factory Pattern**: `RedisServiceFactory` manages multiple Redis client instances with configuration-driven setup
53
- **Service Wrapper**: `RedisService` provides the default Redis client with full ioredis API delegation
54
- **Lifecycle Management**: `RedisConfiguration` handles application startup, shutdown, and health checks
55
- **Multi-Client Support**: Support for multiple named Redis connections (single, cluster, sentinel)
56
- **Health Monitoring**: Built-in health checks for monitoring Redis connection status
57
58
## Capabilities
59
60
### Service Factory
61
62
Core service factory for creating and managing Redis client instances with support for single, cluster, and sentinel configurations.
63
64
```typescript { .api }
65
class RedisServiceFactory extends ServiceFactory<Redis> {
66
protected redisConfig: ServiceFactoryConfigOption<RedisConfigOptions>;
67
protected logger: ILogger;
68
69
protected async createClient(config: RedisConfigOptions): Promise<Redis>;
70
getName(): string;
71
protected async destroyClient(redisInstance: Redis): Promise<void>;
72
}
73
```
74
75
[Service Factory](./service-factory.md)
76
77
### Redis Service
78
79
Main service wrapper that provides access to Redis operations through dependency injection, delegating all ioredis methods.
80
81
```typescript { .api }
82
class RedisService implements Redis {
83
private serviceFactory: RedisServiceFactory;
84
private instance: Redis;
85
86
defineCommand(
87
name: string,
88
definition: {
89
lua: string;
90
numberOfKeys?: number;
91
readOnly?: boolean;
92
}
93
): void;
94
}
95
96
interface RedisService extends Redis {}
97
```
98
99
[Redis Service](./redis-service.md)
100
101
### Configuration Management
102
103
Lifecycle and health check management for Redis components within the Midway.js framework.
104
105
```typescript { .api }
106
class RedisConfiguration implements ILifeCycle {
107
async onReady(container: IMidwayContainer): Promise<void>;
108
async onStop(container: IMidwayContainer): Promise<void>;
109
async onHealthCheck(container: IMidwayContainer): Promise<HealthResult>;
110
}
111
```
112
113
[Configuration](./configuration.md)
114
115
## Types
116
117
```typescript { .api }
118
import { ServiceFactoryConfigOption } from '@midwayjs/core';
119
import { ClusterNode, ClusterOptions } from 'ioredis';
120
121
type RedisConfigOptions =
122
| Redis.RedisOptions
123
| ({
124
cluster?: boolean;
125
nodes?: ClusterNode[];
126
} & ClusterOptions);
127
128
interface HealthResult {
129
status: boolean;
130
reason: string;
131
}
132
133
interface MidwayCommonError extends Error {
134
name: 'MidwayCommonError';
135
}
136
```