mm_redis 2.0.7 → 2.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +102 -39
  2. package/README_EN.md +433 -0
  3. package/index.js +430 -490
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -1,23 +1,28 @@
1
1
  # mm_redis
2
2
 
3
- mm_redis是一个高效的Redis客户端封装库,提供了全面的Redis功能支持,包括连接池管理、数据类型操作、错误处理和批量操作优化。
4
-
5
- [![npm version](https://badge.fury.io/js/mm_redis.svg)](https://badge.fury.io/js/mm_redis)
3
+ [![npm version](https://badge.fury.io/js/mm_redis.svg)](https://www.npmjs.com/package/mm_redis)
6
4
  [![npm downloads](https://img.shields.io/npm/dm/mm_redis.svg)](https://www.npmjs.com/package/mm_redis)
5
+ [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)
6
+
7
+ > 一个高效的Redis客户端封装库,提供完整的连接池管理、数据类型操作和批量操作优化
7
8
 
8
9
  ## 版本信息
9
10
 
10
- - **当前版本**: 2.0.5
11
+ - **最新版本**: 2.0.0
11
12
  - **更新日期**: 2025-10-20
12
13
  - **作者**: qww
13
14
  - **NPM**: [https://www.npmjs.com/package/mm_redis](https://www.npmjs.com/package/mm_redis)
14
15
  - **GitHub**: [https://gitee.com/qiuwenwu91/mm_redis](https://gitee.com/qiuwenwu91/mm_redis)
16
+ - **Node.js**: >= 14.0.0
15
17
 
16
18
  ## 功能特性
17
19
 
20
+ ### 🚀 核心功能
18
21
  - **完整的连接池管理**:优化并发性能,支持连接复用和自动回收
19
22
  - **Pipeline批量操作**:支持Redis Pipeline机制,大幅提升批量操作效率
20
23
  - **全面的数据类型支持**:覆盖String、List、Hash、Set、Sorted Set等所有主要Redis数据类型
24
+
25
+ ### 🔧 高级特性
21
26
  - **智能连接管理**:自动重连机制,使用指数退避策略,确保连接稳定可靠
22
27
  - **健壮的错误处理**:全面的错误处理机制和详细的日志记录,便于问题排查
23
28
  - **便捷的数据序列化**:自动JSON序列化/反序列化,无需手动转换数据格式
@@ -27,55 +32,113 @@ mm_redis是一个高效的Redis客户端封装库,提供了全面的Redis功
27
32
 
28
33
  ## 安装
29
34
 
35
+ ### npm
36
+ ```bash
37
+ npm install mm_redis
38
+ ```
39
+
40
+ ### yarn
41
+ ```bash
42
+ yarn add mm_redis
43
+ ```
44
+
45
+ ### pnpm
30
46
  ```bash
31
- npm install mm_redis --save
47
+ pnpm add mm_redis
32
48
  ```
33
49
 
34
- ## Node.js版本要求
50
+ ## 快速开始
51
+
52
+ ```javascript
53
+ const { Redis } = require('mm_redis');
54
+
55
+ // 创建Redis实例
56
+ const redis = new Redis({
57
+ host: 'localhost',
58
+ port: 6379,
59
+ password: 'your_password',
60
+ db: 0
61
+ });
62
+
63
+ // 连接Redis
64
+ await redis.connect();
65
+
66
+ // 设置缓存
67
+ await redis.set('user:1', { name: '张三', age: 25 });
68
+
69
+ // 获取缓存
70
+ const user = await redis.get('user:1');
71
+ console.log(user); // { name: '张三', age: 25 }
35
72
 
36
- - **最低支持版本**:Node.js 14.0.0
37
- - **推荐版本**:Node.js 16.0.0及以上
73
+ // 错误处理
74
+ try {
75
+ await redis.set('key', 'value');
76
+ } catch (err) {
77
+ console.error('Redis操作失败:', err);
78
+ }
79
+ ```
38
80
 
39
81
  ## 配置引入方式
40
82
 
41
- mm_redis支持多种配置引入方式:
83
+ mm_redis支持多种配置引入方式,满足不同场景的需求:
42
84
 
43
- 1. **对象配置(推荐)**:直接传入配置对象
85
+ ### 1. 对象配置(推荐)
44
86
  ```javascript
45
- const Redis = require('mm_redis');
46
- const redis = new Redis('default');
47
- redis.setConfig({
48
- // 服务器地址
49
- host: "localhost",
50
- // 端口号
87
+ const { Redis } = require('mm_redis');
88
+
89
+ // 直接传入配置对象
90
+ const redis = new Redis({
91
+ host: 'localhost',
51
92
  port: 6379,
52
- // 密码
53
- password: "",
54
- // 数据库
55
- database: 0,
56
- // 前缀
57
- prefix: "app:",
58
- // 连接超时时间(ms)
59
- connect_timeout: 10000,
60
- // 重试次数
61
- retry_count: 3,
62
- // 重试间隔(ms)
63
- retry_delay: 1000,
64
- // 连接池配置
65
- pool: {
66
- max_clients: 10, // 最大连接数
67
- min_idle: 2, // 最小空闲连接数
68
- max_idle: 5, // 最大空闲连接数
69
- idle_timeout: 30000 // 空闲超时时间(ms)
70
- }
93
+ password: 'your_password',
94
+ db: 0,
95
+ key_prefix: 'app:',
96
+ max_clients: 10,
97
+ connect_timeout: 5000
71
98
  });
72
99
  ```
73
100
 
74
- 2. **文件配置**:传入配置文件路径
101
+ ### 2. 文件配置
102
+ ```javascript
103
+ // config/redis.json
104
+ {
105
+ "host": "localhost",
106
+ "port": 6379,
107
+ "password": "your_password",
108
+ "db": 0,
109
+ "key_prefix": "app:",
110
+ "max_clients": 10,
111
+ "connect_timeout": 5000
112
+ }
113
+
114
+ // 使用配置
115
+ const { Redis } = require('mm_redis');
116
+ const config = require('./config/redis.json');
117
+ const redis = new Redis(config);
118
+ ```
119
+
120
+ ### 3. 环境变量配置
75
121
  ```javascript
76
- const Redis = require('mm_redis');
77
- const redis = new Redis('default');
78
- redis.setConfig('./config.json');
122
+ // 环境变量
123
+ REDIS_HOST=localhost
124
+ REDIS_PORT=6379
125
+ REDIS_PASSWORD=your_password
126
+ REDIS_DB=0
127
+ REDIS_KEY_PREFIX=app:
128
+ REDIS_MAX_CLIENTS=10
129
+ REDIS_CONNECT_TIMEOUT=5000
130
+
131
+ // 使用环境变量
132
+ const { Redis } = require('mm_redis');
133
+ const redis = new Redis({
134
+ host: process.env.REDIS_HOST,
135
+ port: parseInt(process.env.REDIS_PORT),
136
+ password: process.env.REDIS_PASSWORD,
137
+ db: parseInt(process.env.REDIS_DB),
138
+ key_prefix: process.env.REDIS_KEY_PREFIX,
139
+ max_clients: parseInt(process.env.REDIS_MAX_CLIENTS),
140
+ connect_timeout: parseInt(process.env.REDIS_CONNECT_TIMEOUT)
141
+ });
79
142
  ```
80
143
  ## 变更日志
81
144
 
package/README_EN.md ADDED
@@ -0,0 +1,433 @@
1
+ # mm_redis
2
+
3
+ [![npm version](https://badge.fury.io/js/mm_redis.svg)](https://www.npmjs.com/package/mm_redis)
4
+ [![npm downloads](https://img.shields.io/npm/dm/mm_redis.svg)](https://www.npmjs.com/package/mm_redis)
5
+ [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)
6
+
7
+ A high-performance Redis client wrapper library that provides comprehensive Redis functionality support, including connection pool management, data type operations, error handling, and batch operation optimization.
8
+
9
+ ## Version Information
10
+
11
+ - **Latest Version**: 2.0.0
12
+ - **Update Date**: 2025-10-20
13
+ - **Author**: qww
14
+ - **NPM**: [https://www.npmjs.com/package/mm_redis](https://www.npmjs.com/package/mm_redis)
15
+ - **GitHub**: [https://gitee.com/qiuwenwu91/mm_redis](https://gitee.com/qiuwenwu91/mm_redis)
16
+ - **Node.js**: >= 14.0.0
17
+
18
+ ## Features
19
+
20
+ ### 🚀 Core Features
21
+ - **Complete Connection Pool Management**: Optimized concurrent performance with connection reuse and automatic recycling
22
+ - **Pipeline Batch Operations**: Support for Redis Pipeline mechanism, significantly improving batch operation efficiency
23
+ - **Comprehensive Data Type Support**: Covers all major Redis data types including String, List, Hash, Set, Sorted Set
24
+
25
+ ### 🔧 Advanced Features
26
+ - **Smart Connection Management**: Automatic reconnection with exponential backoff strategy for reliable connections
27
+ - **Robust Error Handling**: Comprehensive error handling mechanism with detailed logging
28
+ - **Automatic Data Serialization**: Automatic JSON serialization/deserialization without manual conversion
29
+ - **Key Space Isolation**: Support for key prefix management for multi-business scenario data isolation
30
+ - **Flexible Event System**: Unified event mechanism supporting pre/post operation event listening and interception
31
+ - **Rich Numeric Operations**: Support for atomic increment/decrement operations, suitable for counter scenarios
32
+
33
+ ## Installation
34
+
35
+ ### Using npm
36
+ ```bash
37
+ npm install mm_redis --save
38
+ ```
39
+
40
+ ### Using yarn
41
+ ```bash
42
+ yarn add mm_redis
43
+ ```
44
+
45
+ ### Using pnpm
46
+ ```bash
47
+ pnpm add mm_redis
48
+ ```
49
+
50
+ ## Node.js Version Requirements
51
+
52
+ - **Minimum Supported Version**: Node.js 14.0.0
53
+ - **Recommended Version**: Node.js 16.0.0 and above
54
+
55
+ ## Quick Start
56
+
57
+ ### Basic Usage
58
+ ```javascript
59
+ const Redis = require('mm_redis');
60
+
61
+ // Create Redis instance
62
+ const redis = new Redis('default');
63
+
64
+ async function example() {
65
+ try {
66
+ // Connect to Redis
67
+ await redis.open();
68
+
69
+ // Set cache with expiration
70
+ await redis.set('user:1', { name: 'John', age: 25 }, 3600);
71
+
72
+ // Get cache
73
+ const user = await redis.get('user:1');
74
+ console.log('User info:', user);
75
+
76
+ // Close connection
77
+ await redis.close();
78
+ } catch (error) {
79
+ console.error('Operation failed:', error);
80
+ }
81
+ }
82
+
83
+ example();
84
+ ```
85
+
86
+ ## Configuration
87
+
88
+ mm_redis supports multiple configuration loading methods:
89
+
90
+ ### Object Configuration (Recommended)
91
+ ```javascript
92
+ const Redis = require('mm_redis');
93
+ const redis = new Redis('default');
94
+
95
+ redis.setConfig({
96
+ host: "localhost",
97
+ port: 6379,
98
+ password: "",
99
+ database: 0,
100
+ prefix: "app:",
101
+ connect_timeout: 10000,
102
+ retry_count: 3,
103
+ retry_delay: 1000,
104
+ pool: {
105
+ max_clients: 10,
106
+ min_idle: 2,
107
+ max_idle: 5,
108
+ idle_timeout: 30000
109
+ }
110
+ });
111
+ ```
112
+
113
+ ### File Configuration
114
+ ```javascript
115
+ const Redis = require('mm_redis');
116
+ const redis = new Redis('default');
117
+
118
+ redis.setConfig('./config.json');
119
+ ```
120
+
121
+ Configuration file example (`config.json`):
122
+ ```json
123
+ {
124
+ "host": "localhost",
125
+ "port": 6379,
126
+ "password": "",
127
+ "database": 0,
128
+ "prefix": "app:",
129
+ "connect_timeout": 10000,
130
+ "retry_count": 3,
131
+ "retry_delay": 1000,
132
+ "pool": {
133
+ "max_clients": 10,
134
+ "min_idle": 2,
135
+ "max_idle": 5,
136
+ "idle_timeout": 30000
137
+ }
138
+ }
139
+ ```
140
+
141
+ ### Environment Variables
142
+ ```javascript
143
+ const Redis = require('mm_redis');
144
+ const redis = new Redis('default');
145
+
146
+ redis.setConfig({
147
+ host: process.env.REDIS_HOST || 'localhost',
148
+ port: parseInt(process.env.REDIS_PORT) || 6379,
149
+ password: process.env.REDIS_PASSWORD || '',
150
+ database: parseInt(process.env.REDIS_DB) || 0
151
+ });
152
+ ```
153
+
154
+ ## Change Log
155
+
156
+ ### v2.0.0 (2025-10-14)
157
+ - Removed list_push method, unified to use addForList method for list operations
158
+ - Updated documentation, replaced all list_push references with addForList
159
+ - Updated API list and usage examples in documentation
160
+ - Optimized connection pool configuration management, unified configuration to this.config.pool
161
+ - Added connection pool configuration parameters: min_idle, max_idle, idle_timeout
162
+
163
+ ### v1.9.8 (2024-12-22)
164
+ - Updated documentation, improved content required for npm publishing
165
+ - Added GitHub repository link to documentation
166
+ - Optimized feature description, enhanced document readability
167
+ - Added Node.js version requirement description
168
+
169
+ ### v1.9.5 (2024-12-21)
170
+ - Fixed compatibility issues with hmset and hgetall methods to ensure compatibility with Redis client v5
171
+ - Removed deprecated hexists, hkeys and hvals methods, optimized API design
172
+ - Optimized implementation of mget and mset methods to ensure full compatibility with Redis v5 API
173
+ - Updated test scripts, removed calls to deprecated methods
174
+ - Updated compatibility table to ensure documentation matches actual API
175
+ - Fixed errors in native Redis API calls, improved code stability
176
+ - Optimized connection pool management, fixed potential memory leak issues
177
+
178
+ ### v1.9.4 (2024-12-20)
179
+ - Optimized configuration loading methods, supporting both object configuration and file path configuration
180
+ - Improved implementation of setConfig method, using Object.assign instead of original merge method
181
+ - Fixed warning messages related to connection pool
182
+ - Enhanced error handling mechanism
183
+
184
+ ### v1.9.0 (2024-11-20)
185
+ - Initial version release
186
+ - Support for complete connection pool management
187
+ - Implementation of Pipeline batch operations
188
+ - Support for all major Redis data type operations
189
+
190
+ ## Usage Examples
191
+
192
+ ### Basic Operations
193
+ ```javascript
194
+ // Connect to Redis
195
+ await redis.open();
196
+
197
+ // Set cache
198
+ await redis.set('user:1', { name: 'John', age: 25 }, 3600);
199
+
200
+ // Get cache
201
+ const user = await redis.get('user:1');
202
+ console.log('User info:', user);
203
+
204
+ // Check if key exists
205
+ const exists = await redis.has('user:1');
206
+
207
+ // Delete cache
208
+ await redis.del('user:1');
209
+
210
+ // Close connection
211
+ await redis.close();
212
+ ```
213
+
214
+ ### List Operations
215
+ ```javascript
216
+ // Set list
217
+ await redis.setForList('users', ['user1', 'user2', 'user3']);
218
+
219
+ // Add element to list
220
+ await redis.addForList('users', 'user4');
221
+
222
+ // Get list
223
+ const users = await redis.getForList('users');
224
+ console.log('User list:', users);
225
+
226
+ // Get partial list elements
227
+ const partialUsers = await redis.getForList('users', 0, 2);
228
+
229
+ // Clear list
230
+ await redis.clearForList('users');
231
+ ```
232
+
233
+ ### Hash Operations
234
+ ```javascript
235
+ // Set hash field
236
+ await redis.hset('user:profile:1', 'name', 'John');
237
+ await redis.hset('user:profile:1', 'age', 25);
238
+
239
+ // Batch set hash fields
240
+ await redis.hmset('user:profile:1', {
241
+ 'email': 'john@example.com',
242
+ 'phone': '1234567890'
243
+ });
244
+
245
+ // Get hash field
246
+ const name = await redis.hget('user:profile:1', 'name');
247
+
248
+ // Get all hash fields and values
249
+ const profile = await redis.hgetall('user:profile:1');
250
+ console.log('User profile:', profile);
251
+
252
+ // Get hash field count
253
+ const fieldCount = await redis.hlen('user:profile:1');
254
+
255
+ // Delete hash fields
256
+ await redis.hdel('user:profile:1', ['email', 'phone']);
257
+ ```
258
+
259
+ ### Batch Operations
260
+ ```javascript
261
+ // Batch get
262
+ const data = await redis.mget(['user:1', 'user:2', 'user:3']);
263
+ console.log('Batch get result:', data);
264
+
265
+ // Batch set
266
+ await redis.mset({
267
+ 'user:4': { name: 'Jane', age: 30 },
268
+ 'user:5': { name: 'Bob', age: 35 }
269
+ }, 3600);
270
+ ```
271
+
272
+ ### Pipeline Optimization
273
+ ```javascript
274
+ // Create Pipeline
275
+ const pipeline = redis.pipeline();
276
+
277
+ // Add multiple commands
278
+ pipeline.set('counter:1', 100);
279
+ pipeline.ttl('counter:1', 3600);
280
+ pipeline.hset('stats:today', 'visits', 500);
281
+ pipeline.hset('stats:today', 'users', 100);
282
+
283
+ // Execute all commands
284
+ const results = await pipeline.exec();
285
+ console.log('Pipeline execution result:', results);
286
+ ```
287
+
288
+ ### Publish/Subscribe
289
+ ```javascript
290
+ // Subscribe to channel
291
+ await redis.subscribe('notifications', async (message) => {
292
+ console.log('Received notification:', message);
293
+ // Process received message
294
+ });
295
+
296
+ // Publish message
297
+ const receivedCount = await redis.publish('notifications', JSON.stringify({
298
+ type: 'info',
299
+ content: 'System update successful'
300
+ }));
301
+
302
+ console.log(`Message published, ${receivedCount} clients received`);
303
+
304
+ // Unsubscribe
305
+ await redis.unsubscribe('notifications');
306
+ ```
307
+
308
+ ## API Documentation
309
+
310
+ ### Connection Management
311
+ - `setConfig(config)`: Set Redis configuration
312
+ - `open()`: Connect to Redis
313
+ - `close()`: Close connection
314
+ - `isConnected()`: Check connection status
315
+
316
+ ### String Operations
317
+ - `set(key, value, seconds)`: Set cache
318
+ - `get(key)`: Get cache
319
+ - `has(key)`: Check if key exists
320
+ - `del(key)`: Delete cache
321
+ - `add(key, value, seconds)`: Set cache only if key doesn't exist
322
+ - `ttl(key, seconds)`: Set or get expiration time
323
+ - `addInt(key, num)`: Increment integer value
324
+ - `addFloat(key, num)`: Increment float value
325
+ - `addStr(key, str)`: Append string
326
+ - `getrange(key, start, end)`: Get substring
327
+ - `setrange(key, index, value)`: Set substring
328
+
329
+ ### List Operations
330
+ - `setForList(key, value, seconds)`: Set list
331
+ - `addForList(key, value)`: Add element to list
332
+ - `getForList(key, start, end)`: Get list
333
+ - `hasForList(key, value)`: Check if element exists in list
334
+ - `clearForList(key, value)`: Clear list or reset list
335
+
336
+ ### Hash Operations
337
+ - `hset(key, field, value)`: Set hash field
338
+ - `hmset(key, obj)`: Batch set hash fields
339
+ - `hget(key, field)`: Get hash field value
340
+ - `hgetall(key)`: Get all hash fields and values
341
+ - `hdel(key, fields)`: Delete hash fields
342
+ - `hlen(key)`: Get hash field count
343
+
344
+ ### Batch Operations
345
+ - `mget(keys)`: Batch get cache
346
+ - `mset(obj, seconds)`: Batch set cache
347
+ - `pipeline()`: Create Pipeline object for batch operation optimization
348
+
349
+ ### Set Operations
350
+ - `sadd(key, members)`: Add members to set
351
+ - `srem(key, members)`: Remove members from set
352
+ - `sismember(key, member)`: Check if member is in set
353
+ - `smembers(key)`: Get all members in set
354
+ - `scard(key)`: Get member count in set
355
+ - `sinter(keys)`: Get intersection of multiple sets
356
+ - `sunion(keys)`: Get union of multiple sets
357
+ - `sdiff(keys)`: Get difference of multiple sets
358
+
359
+ ### Sorted Set Operations
360
+ - `zadd(key, score, member)`: Add member to sorted set
361
+ - `zrem(key, members)`: Remove members from sorted set
362
+ - `zscore(key, member)`: Get member score in sorted set
363
+ - `zrank(key, member)`: Get member rank in sorted set
364
+ - `zrange(key, start, stop, withScores)`: Get members in specified range
365
+ - `zcard(key)`: Get member count in sorted set
366
+ - `zincrby(key, increment, member)`: Increment member score in sorted set
367
+
368
+ ### Numeric Operations
369
+ - `incr(key)`: Increment key value by 1
370
+ - `decr(key)`: Decrement key value by 1
371
+ - `incrby(key, increment)`: Increment key value by specified integer
372
+ - `decrby(key, decrement)`: Decrement key value by specified integer
373
+ - `expire(key, seconds)`: Set key expiration time
374
+
375
+ ## Connection Pool Management
376
+
377
+ This module has built-in efficient connection pool management that automatically handles connection creation, recycling, and reuse. Connection pool configuration can be set during initialization:
378
+
379
+ ```javascript
380
+ {
381
+ "pool": {
382
+ "max_clients": 10, // Maximum connections
383
+ "min_idle": 2, // Minimum idle connections
384
+ "max_idle": 5, // Maximum idle connections
385
+ "idle_timeout": 30000 // Idle timeout (ms)
386
+ }
387
+ }
388
+ ```
389
+
390
+ ## Error Handling
391
+
392
+ All methods include comprehensive error handling mechanisms and provide detailed log output. When errors occur, error information is automatically recorded and fallback solutions are provided when possible.
393
+
394
+ ## Best Practices
395
+
396
+ 1. **Use Connection Pool**: For high-concurrency applications, connection pool configuration is crucial. Reasonably set maximum connections and idle connections.
397
+ 2. **Use Pipeline**: For batch operations, using Pipeline can significantly improve performance.
398
+ 3. **Set Expiration Time Reasonably**: Avoid unlimited growth of data in Redis.
399
+ 4. **Use Key Prefix**: Isolate business through key prefix to avoid key conflicts.
400
+ 5. **Close Connections Timely**: Call close() method to close all connections when application ends.
401
+ 6. **Leverage Event System**: Use event system for logging, data validation, and operation interception.
402
+
403
+ ## Contributing
404
+
405
+ We welcome community contributions! If you're interested in contributing to the mm_redis project, please follow these steps:
406
+
407
+ 1. Fork this repository
408
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
409
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
410
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
411
+ 5. Open a Pull Request
412
+
413
+ Please ensure your code follows the project's coding standards and passes all tests.
414
+
415
+ ## License
416
+
417
+ This project is licensed under the ISC License - see the [LICENSE](LICENSE) file for details.
418
+
419
+ ## Issue Reporting
420
+
421
+ If you encounter any problems or have any suggestions during use, please provide feedback through the following methods:
422
+
423
+ - **GitHub Issues**: [https://gitee.com/qiuwenwu91/mm_redis/issues](https://gitee.com/qiuwenwu91/mm_redis/issues)
424
+ - **NPM**: [https://www.npmjs.com/package/mm_redis](https://www.npmjs.com/package/mm_redis)
425
+
426
+ ## Acknowledgments
427
+
428
+ Thanks to all developers and users who have contributed to this project!
429
+
430
+ ## Related Links
431
+
432
+ - **Redis Official Documentation**: [https://redis.io/documentation](https://redis.io/documentation)
433
+ - **Node Redis Client**: [https://github.com/redis/node-redis](https://github.com/redis/node-redis)