0
# Service Factory
1
2
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.
3
4
## Capabilities
5
6
### RedisServiceFactory Class
7
8
Core service factory extending Midway's ServiceFactory base class for managing Redis clients.
9
10
```typescript { .api }
11
/**
12
* Service factory for creating and managing Redis client instances
13
* Supports single Redis, Redis Cluster, and Redis Sentinel configurations
14
*/
15
class RedisServiceFactory extends ServiceFactory<Redis> {
16
@Config('redis')
17
protected redisConfig: ServiceFactoryConfigOption<RedisConfigOptions>;
18
19
@Logger('coreLogger')
20
protected logger: ILogger;
21
22
@Init()
23
protected async init(): Promise<void>;
24
25
protected async createClient(config: RedisConfigOptions): Promise<Redis>;
26
getName(): string;
27
protected async destroyClient(redisInstance: Redis): Promise<void>;
28
29
// Inherited from ServiceFactory<Redis>
30
get(clientName?: string): Redis;
31
has(clientName: string): boolean;
32
getClients(): Map<string, Redis>;
33
getDefaultClientName(): string;
34
isLowPriority(clientName: string): boolean;
35
async stop(): Promise<void>;
36
}
37
```
38
39
### Client Creation
40
41
Creates Redis client instances based on configuration type detection.
42
43
```typescript { .api }
44
/**
45
* Creates a Redis client based on configuration
46
* Automatically detects single, cluster, or sentinel setup
47
* @param config - Redis configuration options
48
* @returns Promise resolving to Redis client instance
49
*/
50
protected async createClient(config: RedisConfigOptions): Promise<Redis>;
51
```
52
53
**Configuration Detection Logic:**
54
- If `config.cluster === true`: Creates Redis Cluster client
55
- If `config.sentinels` exists: Creates Redis Sentinel client
56
- Otherwise: Creates single Redis instance client
57
58
**Usage Examples:**
59
60
```typescript
61
import { RedisServiceFactory } from "@midwayjs/redis";
62
import { Inject } from "@midwayjs/core";
63
64
export class DataService {
65
@Inject()
66
redisFactory: RedisServiceFactory;
67
68
async getRedisClient(clientName = 'default') {
69
// Get specific named client
70
return this.redisFactory.get(clientName);
71
}
72
73
async getCacheClient() {
74
// Get named client for caching
75
return this.redisFactory.get('cache');
76
}
77
}
78
```
79
80
### Service Name
81
82
Returns the service identifier used by Midway's service factory system.
83
84
```typescript { .api }
85
/**
86
* Returns the service name identifier
87
* @returns Service name 'redis'
88
*/
89
getName(): string;
90
```
91
92
### Client Destruction
93
94
Safely closes Redis connections during application shutdown.
95
96
```typescript { .api }
97
/**
98
* Safely destroys a Redis client instance
99
* Handles graceful shutdown with quit() when client is ready
100
* @param redisInstance - Redis client to destroy
101
* @returns Promise that resolves when client is closed
102
*/
103
protected async destroyClient(redisInstance: Redis): Promise<void>;
104
```
105
106
### Priority Management
107
108
Checks if a client has low priority for health monitoring exclusion.
109
110
```typescript { .api }
111
/**
112
* Determines if a client is marked as low priority
113
* Low priority clients are excluded from health check failures
114
* @param clientName - Name of the client to check
115
* @returns True if client has low priority
116
*/
117
isLowPriority(clientName: string): boolean;
118
```
119
120
## Configuration Examples
121
122
### Single Redis Instance
123
124
```typescript
125
// config/config.default.ts
126
export default {
127
redis: {
128
client: {
129
host: 'localhost',
130
port: 6379,
131
password: 'your-password',
132
db: 0,
133
family: 4,
134
connectTimeout: 10000,
135
lazyConnect: true,
136
}
137
}
138
};
139
```
140
141
### Redis Cluster
142
143
```typescript
144
// config/config.default.ts
145
export default {
146
redis: {
147
client: {
148
cluster: true,
149
nodes: [
150
{ host: 'redis-node-1', port: 6379 },
151
{ host: 'redis-node-2', port: 6379 },
152
{ host: 'redis-node-3', port: 6379 }
153
],
154
// Cluster-specific options
155
enableOfflineQueue: false,
156
// Redis options applied to all cluster nodes
157
redisOptions: {
158
password: 'your-password',
159
family: 4,
160
connectTimeout: 10000,
161
commandTimeout: 5000,
162
retryDelayOnFailover: 100,
163
maxRetriesPerRequest: 3
164
}
165
}
166
}
167
};
168
```
169
170
### Redis Sentinel
171
172
```typescript
173
// config/config.default.ts
174
export default {
175
redis: {
176
client: {
177
sentinels: [
178
{ host: 'sentinel-1', port: 26379 },
179
{ host: 'sentinel-2', port: 26379 },
180
{ host: 'sentinel-3', port: 26379 }
181
],
182
name: 'mymaster',
183
password: 'your-password',
184
}
185
}
186
};
187
```
188
189
### Multi-Client Configuration
190
191
```typescript
192
// config/config.default.ts
193
export default {
194
redis: {
195
clients: {
196
default: {
197
host: 'localhost',
198
port: 6379,
199
db: 0,
200
},
201
cache: {
202
host: 'cache-server',
203
port: 6379,
204
db: 1,
205
},
206
session: {
207
cluster: true,
208
nodes: [
209
{ host: 'session-node-1', port: 6379 },
210
{ host: 'session-node-2', port: 6379 }
211
]
212
}
213
},
214
// Client priority configuration for health checks
215
priority: {
216
cache: 'Low', // Exclude from health check failures
217
session: 'High' // Include in health check evaluation (default)
218
}
219
}
220
};
221
```
222
223
## Error Handling
224
225
The service factory includes comprehensive validation and error handling:
226
227
- **Configuration Validation**: Assertions ensure required host/port for single instances
228
- **Cluster Validation**: Validates that nodes array is provided and populated for cluster mode
229
- **Sentinel Validation**: Ensures sentinels array and master name are configured
230
- **Connection Monitoring**: Listens for connect/error events during client initialization
231
- **Graceful Shutdown**: Handles client destruction with proper error logging
232
233
### Configuration Validation Details
234
235
The factory performs strict validation on configuration:
236
237
```typescript
238
// Single instance validation
239
assert(config.host && config.port,
240
`[midway:redis] 'host: ${config.host}', 'port: ${config.port}' are required on config`);
241
242
// Cluster validation
243
assert(config.nodes && config.nodes.length !== 0,
244
'[midway:redis] cluster nodes configuration is required when use cluster redis');
245
246
config.nodes.forEach(client => {
247
assert(client.host && client.port,
248
`[midway:redis] 'host: ${client.host}', 'port: ${client.port}' are required on config`);
249
});
250
251
// Sentinel validation
252
assert(config.sentinels && config.sentinels.length !== 0,
253
'[midway:redis] sentinels configuration is required when use redis sentinel');
254
255
config.sentinels.forEach(sentinel => {
256
assert(sentinel.host && sentinel.port,
257
`[midway:redis] 'host: ${sentinel.host}', 'port: ${sentinel.port}' are required on config`);
258
});
259
```
260
261
## Inherited Methods
262
263
As a ServiceFactory subclass, RedisServiceFactory inherits standard factory methods:
264
265
- `get(clientName?: string)`: Get a client instance by name
266
- `has(clientName: string)`: Check if a client exists
267
- `getClients()`: Get all client instances
268
- `stop()`: Stop all clients during shutdown