or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdindex.mdredis-service.mdservice-factory.md

configuration.mddocs/

0

# Configuration

1

2

The RedisConfiguration class manages the lifecycle of Redis components within the Midway.js framework, handling initialization, cleanup, and health monitoring for Redis services.

3

4

## Capabilities

5

6

### RedisConfiguration Class

7

8

Lifecycle management class implementing Midway's ILifeCycle interface.

9

10

```typescript { .api }

11

/**

12

* Configuration class for Redis component lifecycle management

13

* Handles initialization, shutdown, and health checks

14

*/

15

class RedisConfiguration implements ILifeCycle {

16

async onReady(container: IMidwayContainer): Promise<void>;

17

async onStop(container: IMidwayContainer): Promise<void>;

18

async onHealthCheck(container: IMidwayContainer): Promise<HealthResult>;

19

}

20

```

21

22

### Application Ready Handler

23

24

Initializes the Redis service factory when the application is ready.

25

26

```typescript { .api }

27

/**

28

* Called when the Midway application is ready

29

* Initializes the RedisServiceFactory

30

* @param container - Midway IoC container

31

*/

32

async onReady(container: IMidwayContainer): Promise<void>;

33

```

34

35

### Application Stop Handler

36

37

Gracefully shuts down all Redis connections when the application stops.

38

39

```typescript { .api }

40

/**

41

* Called when the Midway application is stopping

42

* Gracefully shuts down all Redis clients

43

* @param container - Midway IoC container

44

*/

45

async onStop(container: IMidwayContainer): Promise<void>;

46

```

47

48

### Health Check Handler

49

50

Monitors the health status of all Redis client connections.

51

52

```typescript { .api }

53

/**

54

* Performs health check on all Redis clients

55

* Excludes low-priority clients from health check evaluation

56

* @param container - Midway IoC container

57

* @returns Health check result with status and reason

58

*/

59

async onHealthCheck(container: IMidwayContainer): Promise<HealthResult>;

60

61

interface HealthResult {

62

status: boolean;

63

reason: string;

64

}

65

```

66

67

## Configuration Setup

68

69

### Basic Configuration

70

71

The configuration is automatically loaded through Midway's configuration system:

72

73

```typescript

74

// config/config.default.ts

75

import { MidwayConfig } from '@midwayjs/core';

76

77

export default {

78

redis: {

79

// Single client configuration

80

client: {

81

host: 'localhost',

82

port: 6379,

83

password: 'your-password',

84

db: 0,

85

},

86

// Client priority configuration for health checks

87

priority: {

88

default: 'High' // Include in health check evaluation

89

}

90

}

91

} as MidwayConfig;

92

```

93

94

### Import Configuration

95

96

The RedisConfiguration includes default configuration imports:

97

98

```typescript

99

@Configuration({

100

namespace: 'redis',

101

importConfigs: [

102

{

103

default: {

104

redis: {},

105

},

106

},

107

],

108

})

109

export class RedisConfiguration {

110

// Configuration implementation

111

}

112

```

113

114

## Health Monitoring

115

116

### Health Check Logic

117

118

The health check evaluates Redis client status:

119

120

1. **Client Status Check**: Verifies each client's connection status is 'ready'

121

2. **Priority Filtering**: Excludes low-priority clients from health evaluation using `isLowPriority()` method

122

3. **Result Generation**: Returns overall health status and failure reason

123

124

**Priority Configuration:**

125

- Clients marked as `'Low'` priority are excluded from causing health check failures

126

- Only clients with `'High'` priority (or undefined) can fail health checks

127

- Low-priority clients can be used for caching or other non-critical operations

128

129

**Usage Examples:**

130

131

```typescript

132

import { RedisConfiguration } from "@midwayjs/redis";

133

import { IMidwayContainer } from "@midwayjs/core";

134

135

// Manual health check (typically called by framework)

136

async function checkRedisHealth(container: IMidwayContainer) {

137

const config = new RedisConfiguration();

138

const health = await config.onHealthCheck(container);

139

140

console.log('Redis Health:', health.status);

141

if (!health.status) {

142

console.log('Failure Reason:', health.reason);

143

}

144

}

145

```

146

147

### Health Check Response

148

149

```typescript

150

// Healthy response

151

{

152

status: true,

153

reason: ''

154

}

155

156

// Unhealthy response

157

{

158

status: false,

159

reason: 'redis client "cache" is not ready'

160

}

161

```

162

163

## Lifecycle Integration

164

165

### Framework Integration

166

167

The configuration integrates with Midway's application lifecycle:

168

169

```typescript

170

// Automatic integration - no manual setup required

171

import { Configuration } from '@midwayjs/core';

172

import { RedisConfiguration } from '@midwayjs/redis';

173

174

@Configuration({

175

imports: [RedisConfiguration],

176

})

177

export class MainConfiguration {

178

// RedisConfiguration lifecycle hooks are automatically called

179

}

180

```

181

182

### Startup Sequence

183

184

1. **Configuration Load**: Midway loads Redis configuration from config files

185

2. **onReady Trigger**: Framework calls `onReady()` during application startup

186

3. **Factory Initialization**: RedisServiceFactory creates and validates client connections

187

4. **Service Availability**: RedisService becomes available for dependency injection

188

189

### Shutdown Sequence

190

191

1. **onStop Trigger**: Framework calls `onStop()` during application shutdown

192

2. **Client Shutdown**: All Redis clients are gracefully closed

193

3. **Resource Cleanup**: Connection pools and resources are properly cleaned up

194

195

## Error Handling

196

197

### Initialization Errors

198

199

```typescript

200

// Configuration validation errors are logged and propagated

201

try {

202

await container.getAsync(RedisServiceFactory);

203

} catch (error) {

204

// Handle Redis initialization failure

205

console.error('Redis initialization failed:', error.message);

206

}

207

```

208

209

### Health Check Errors

210

211

```typescript

212

// Health check failures provide specific client information

213

const health = await config.onHealthCheck(container);

214

if (!health.status) {

215

// Log specific client failure

216

console.error(`Redis health check failed: ${health.reason}`);

217

}

218

```

219

220

### Shutdown Errors

221

222

```typescript

223

// Shutdown errors are logged but don't prevent application termination

224

await config.onStop(container);

225

// Application continues shutdown process even if Redis cleanup fails

226

```

227

228

## Configuration Namespace

229

230

The configuration uses the 'redis' namespace for Midway's configuration system:

231

232

```typescript

233

// Automatic configuration binding

234

declare module '@midwayjs/core/dist/interface' {

235

interface MidwayConfig {

236

redis?: ServiceFactoryConfigOption<RedisConfigOptions>;

237

}

238

}

239

```

240

241

This allows type-safe configuration access throughout the application:

242

243

```typescript

244

import { Config } from '@midwayjs/core';

245

246

export class SomeService {

247

@Config('redis')

248

redisConfig: ServiceFactoryConfigOption<RedisConfigOptions>;

249

}

250

```