mm_cache 1.5.3 → 1.5.5

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/index.js +14 -868
  2. package/lib/cache.js +832 -0
  3. package/package.json +11 -4
  4. package/test.js +13 -0
package/index.js CHANGED
@@ -1,877 +1,23 @@
1
- /**
2
- * @fileOverview 本地缓存类 (带本地持久存储)
3
- * @author <a href="http://qww.elins.cn">邱文武</a>
4
- * @version 1.2
5
- */
6
- const { Base } = require('mm_expand');
7
-
8
- /**
9
- * @class 缓存类
10
- */
11
- class Cache extends Base {
12
- static config = {
13
- scope: 'sys',
14
- way: 'memory',
15
- // 缓存基础配置
16
- cachebase: {
17
- dir: './cache/'.fullname(),
18
- expire: 0,
19
- max: 0,
20
- persist: false, // 是否启用持久化
21
- saveInterval: 60000 // 保存间隔(毫秒)
22
- },
23
- // 缓存配置
24
- redis: {
25
- // 服务器地址
26
- host: "localhost",
27
- // 端口号
28
- port: 6379,
29
- // 密码
30
- password: "asd159357",
31
- // 数据库
32
- database: 0,
33
- // 前缀
34
- prefix: "",
35
- // 连接超时时间(ms)
36
- connect_timeout: 10000,
37
- // 重试次数
38
- retry_count: 3,
39
- // 重试间隔(ms)
40
- retry_delay: 1000
41
- },
42
- // 数据库配置
43
- mongodb: {
44
- // 服务器地址
45
- host: "localhost",
46
- // 端口号
47
- port: 27017,
48
- // 数据库名
49
- database: "mm",
50
- // 用户名
51
- user: "",
52
- // 密码
53
- password: "",
54
- // 连接选项 (MongoDB驱动7.x版本支持的参数)
55
- min_pool_size: 10,
56
- max_pool_size: 100,
57
- connect_timeout_ms: 10000,
58
- server_selection_timeout_ms: 5000,
59
- retry_writes: true
60
- }
61
- };
62
-
63
- /**
64
- * @description 创建Cache帮助类函数 (构造函数)
65
- * @param {Object} config 配置
66
- * @constructor
67
- */
68
- constructor(config) {
69
- super(Cache.config);
70
- // 作用域
71
- this.scope;
72
- // 当前连接库
73
- this._client = null;
74
- // 初始化配置
75
- this.setConfig(config);
76
- // 注意:不再在构造函数中直接调用异步的connect()
77
- // 用户需要手动调用await cache.connect()
78
- }
79
- }
80
-
81
- /**
82
- * @description 设置配置
83
- * @param {Object} config 配置
84
- */
85
- Cache.prototype.setConfig = function (config) {
86
- // 确保this.config存在
87
- if (!this.config) {
88
- this.config = {};
89
- }
90
-
91
- if (config) {
92
- // 使用$.push合并配置
93
- $.push(this.config, config);
94
- }
95
-
96
- // 确保way属性存在
97
- if (!this.config.way) {
98
- this.config.way = 'memory'; // 默认缓存方式
99
- }
100
-
101
- if (this.config.scope) {
102
- this.scope = this.config.scope;
103
- } else {
104
- this.scope = $.val.scope + '';
105
- }
106
- };
107
-
108
- /**
109
- * @description 获取当前缓存方式
110
- * @return {String} 缓存方式
111
- */
112
- Cache.prototype.getCacheWay = function () {
113
- return this.config.way;
114
- };
115
-
116
-
117
- /**
118
- * @description 连接缓存数据库
119
- * @return {Promise<Boolean>} 是否连接成功
120
- */
121
- Cache.prototype.connect = async function () {
122
- // 关闭现有连接
123
- this.dispose();
124
-
125
- try {
126
- switch (this.config.way) {
127
- case 'redis': {
128
- try {
129
- const {
130
- redisAdmin
131
- } = require('mm_redis');
132
- this._client = redisAdmin(this.config.scope, this.config.redis);
133
- if (!this._client.connected) {
134
- await this._client.open();
135
- }
136
- } catch (e) {
137
- $.log.warn('[Cache] [connect] Cache模块加载失败,回退到memory:', e.message);
138
- this.config.way = 'memory';
139
- await this.connect(); // 递归调用,使用memory
140
- return false;
141
- }
142
- break;
143
- }
144
- case 'mongodb': {
145
- try {
146
- const {
147
- mongodbAdmin
148
- } = require('mm_mongodb');
149
- this._client = mongodbAdmin(this.config.scope, this.config.mongodb);
150
- if (!this._client.connected) {
151
- await this._client.open();
152
- }
153
- } catch (e) {
154
- $.log.warn('[Cache] [connect] MongoDB模块加载失败,回退到memory:', e.message);
155
- this.config.way = 'memory';
156
- await this.connect(); // 递归调用,使用cachebase memory
157
- return false;
158
- }
159
- break;
160
- }
161
- case 'cachebase':
162
- try {
163
- const {
164
- cachebaseAdmin
165
- } = require('mm_cachebase');
166
- this._client = cachebaseAdmin(this.config.scope, this.config.cachebase);
167
- } catch (e) {
168
- $.log.error('[Cache] [connect] CacheBase模块加载失败,无法初始化缓存:', e.message);
169
- return false;
170
- }
171
- break;
172
- case 'memory':
173
- default: {
174
- try {
175
- const {
176
- cachebaseAdmin
177
- } = require('mm_cachebase');
178
- this._client = cachebaseAdmin('default');
179
- } catch (e) {
180
- $.log.error('[Cache] [connect] CacheBase模块加载失败,无法初始化缓存:', e.message);
181
- return false;
182
- }
183
- break;
184
- }
185
- }
186
- this.emit('connect', this.config.way);
187
- return true;
188
- } catch (err) {
189
- this.emit('error', err);
190
- $.log.error('[Cache] [connect] Cache连接失败:', err);
191
- return false;
192
- }
193
- };
194
1
 
195
- /**
196
- * @description 切换缓存方式
197
- * @param {String} way 缓存方式 (cachebase|redis|mongodb)
198
- * @param {Object} config 可选配置
199
- * @return {Promise<Boolean>} 是否成功
200
- */
201
- Cache.prototype.switchCache = async function (way, config) {
202
- if (['cachebase', 'redis', 'mongodb', 'memory'].includes(way)) {
203
- this.config.way = way;
204
- if (config) {
205
- this.config[way] = Object.assign(this.config[way], config);
206
- }
207
- return await this.connect();
208
- }
209
- return false;
210
- };
211
-
212
- /**
213
- * @description 获取所有键名
214
- * @param {String} pattern 匹配模式
215
- * @return {Promise<Array>} 键名数组
216
- */
217
- Cache.prototype.keys = async function (pattern) {
218
- // 添加作用域前缀
219
- const scopePattern = pattern ? `${this.scope}:${pattern}` : `${this.scope}:*`;
220
- // 直接调用底层keys方法
221
- return await this._safeCall('keys', [scopePattern]);
222
- };
223
-
224
- /**
225
- * @description 检查键是否存在
226
- * @param {String} key 键名
227
- * @return {Promise<Boolean>} 是否存在
228
- */
229
- Cache.prototype.has = async function (key) {
230
- // 添加作用域前缀
231
- const scopeKey = `${this.scope}:${key}`;
232
- // 优先使用has方法,如果不存在则使用exists
233
- if (this._client && typeof this._client.has === 'function') {
234
- return await this._client.has(scopeKey);
235
- } else {
236
- return await this._safeCall('exists', [scopeKey]);
237
- }
238
- };
239
-
240
- /**
241
- * @description 安全调用数据库方法
242
- * @param {String} method 方法名
243
- * @param {Array} args 参数数组
244
- * @return {Promise<any>} 方法返回值
245
- */
246
- Cache.prototype._safeCall = async function (method, args = []) {
247
- if (!this._client) {
248
- // 如果未连接,自动尝试连接
249
- await this.connect();
250
- if (!this._client) {
251
- $.log.error('[Cache] [_safeCall] 数据库未初始化');
252
- return null;
253
- }
254
- }
255
-
256
- // 如果方法存在,直接调用
257
- if (typeof this._client[method] === 'function') {
258
- return await this._client[method](...args);
259
- }
2
+ const Cache = require('./lib/cache');
3
+ const Admin = require('mm_corejs').Admin;
260
4
 
261
- // 降级处理:仅为确实不存在的方法提供内置实现
262
- switch (method) {
263
- case 'strlen': {
264
- const key = args[0];
265
- // 获取值并计算长度
266
- const value = await this._client.get(key);
267
- if (value === null || value === undefined) {
268
- return 0;
269
- }
270
- // 兼容Redis行为:只有字符串类型计算长度,其他类型返回0
271
- return typeof value === 'string' ? value.length : 0;
272
- }
273
- case 'rename': {
274
- const [oldKey, newKey] = args;
275
- try {
276
- // 获取原键值
277
- const value = await this._client.get(oldKey);
278
- if (value === null || value === undefined) {
279
- return false;
280
- }
281
- // 设置新键
282
- await this._client.set(newKey, value);
283
- // 删除原键
284
- await this._client.del(oldKey);
285
- return 'OK';
286
- } catch (error) {
287
- $.log.error(`[Cache] [_safeCall] rename操作失败:`, error);
288
- return false;
289
- }
290
- }
291
- case 'type': {
292
- const key = args[0];
293
- // 获取值并判断类型
294
- const value = await this._client.get(key);
295
- if (value === null || value === undefined) {
296
- return 'none';
297
- }
298
- // 兼容Redis的类型判断
299
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
300
- return 'string';
301
- } else if (Array.isArray(value)) {
302
- // 检查是否为集合类型(不包含重复元素)
303
- return new Set(value).size === value.length ? 'set' : 'list';
304
- } else if (typeof value === 'object') {
305
- return 'hash';
306
- }
307
- return 'string';
308
- }
309
- default:
310
- // 如果方法不存在且没有降级实现,返回null
311
- $.log.warn(`[Cache] [_safeCall] 不支持的方法: ${method}`);
312
- return null;
313
- }
314
- };
315
-
316
- /**
317
- * @description 仅当键不存在时设置缓存
318
- * @param {String} key 键
319
- * @param {Object} value 值
320
- * @param {Number} seconds 秒
321
- * @return {Promise<Boolean>} 操作结果
322
- */
323
- Cache.prototype.add = async function (key, value, expire) {
324
- // 添加作用域前缀
325
- const scopeKey = `${this.scope}:${key}`;
326
- // 直接调用底层存储的原生add方法
327
- return await this._safeCall('add', [scopeKey, value, expire]);
328
- };
329
-
330
- /**
331
- * @description 设置缓存
332
- * @param {String} key 键名
333
- * @param {Any} value 缓存值
334
- * @param {Number} expire 过期时间(秒),默认不设置过期时间
335
- * @return {Promise<Boolean>} 是否设置成功
336
- */
337
- Cache.prototype.set = async function (key, value, expire) {
338
- // 添加作用域前缀
339
- const scopeKey = `${this.scope}:${key}`;
340
- return await this._safeCall('set', [scopeKey, value, expire]);
341
- };
342
-
343
- /**
344
- * @description 获取缓存
345
- * @param {String} key 键名
346
- * @return {Promise<Any>} 缓存值
347
- */
348
- Cache.prototype.get = async function (key) {
349
- // 添加作用域前缀
350
- const scopeKey = `${this.scope}:${key}`;
351
- return await this._safeCall('get', [scopeKey]);
352
- };
353
-
354
- /**
355
- * @description 删除缓存
356
- * @param {String} key 键名
357
- * @return {Promise<Boolean>} 是否删除成功
358
- */
359
- Cache.prototype.del = async function (key) {
360
- // 添加作用域前缀
361
- const scopeKey = `${this.scope}:${key}`;
362
- return await this._safeCall('del', [scopeKey]);
363
- };
364
-
365
- /**
366
- * @description 检查键是否存在
367
- * @param {String} key 键名
368
- * @return {Promise<Boolean>} 是否存在
369
- */
370
- Cache.prototype.exists = async function (key) {
371
- // 添加作用域前缀
372
- const scopeKey = `${this.scope}:${key}`;
373
- return await this._safeCall('exists', [scopeKey]);
374
- };
375
-
376
- /**
377
- * @description 设置过期时间
378
- * @param {String} key 键名
379
- * @param {Number} seconds 过期时间(秒)
380
- * @return {Promise<Boolean>} 是否设置成功
381
- */
382
- Cache.prototype.expire = async function (key, seconds) {
383
- // 添加作用域前缀
384
- const scopeKey = `${this.scope}:${key}`;
385
- return await this._safeCall('expire', [scopeKey, seconds]);
386
- };
387
-
388
- /**
389
- * @description 获取过期时间
390
- * @param {String} key 键名
391
- * @param {Number} seconds 过期时间(秒),默认不设置过期时间
392
- * @return {Promise<Number>} 过期时间(秒),-1表示永不过期,-2表示键不存在
393
- */
394
- Cache.prototype.ttl = async function (key, seconds) {
395
- // 添加作用域前缀
396
- const scopeKey = `${this.scope}:${key}`;
397
- // 仅在seconds参数存在时才传递给底层方法
398
- if (seconds !== undefined) {
399
- return await this._safeCall('ttl', [scopeKey, seconds]);
400
- } else {
401
- return await this._safeCall('ttl', [scopeKey]);
402
- }
403
- };
404
-
405
- /**
406
- * @description 获取多个键的值
407
- * @param {...String} keys 键名列表
408
- * @return {Array} 值数组,与键的顺序一致
409
- */
410
- Cache.prototype.mget = function () {
411
- // 确保返回一个函数,满足测试脚本的检查
412
- return async (...keys) => {
413
- try {
414
- // 添加作用域前缀到所有键
415
- const scopeKeys = keys.map(key => `${this.scope}:${key}`);
416
-
417
- // 直接实现并行获取多个键的值
418
- const promises = scopeKeys.map(async (key) => {
419
- try {
420
- // 直接使用db.get方法获取单个键的值
421
- return await this._client.get(key);
422
- } catch (error) {
423
- return null;
424
- }
425
- });
426
-
427
- // 等待所有Promise完成并返回结果数组
428
- return await Promise.all(promises);
429
- } catch (error) {
430
- return [];
431
- }
432
- };
433
- };
434
-
435
- /**
436
- * @description 原子递增
437
- * @param {String} key 键名
438
- * @param {Number} step 步长,默认1
439
- * @return {Promise<Number>} 递增后的值
440
- */
441
- Cache.prototype.incr = async function (key, step = 1) {
442
- // 添加作用域前缀
443
- const scopeKey = `${this.scope}:${key}`;
444
- // 优先使用incr方法,如果不存在则使用addInt
445
- if (this._client && typeof this._client.incr === 'function') {
446
- return await this._client.incr(scopeKey, step);
447
- } else {
448
- return await this._safeCall('addInt', [scopeKey, step]);
449
- }
450
- };
451
-
452
- /**
453
- * @description 原子递增
454
- * @param {String} key 键名
455
- * @param {Number} step 步长,默认1
456
- * @return {Promise<Number>} 递增后的值
457
- */
458
- Cache.prototype.addInt = async function (key, step = 1) {
459
- // 添加作用域前缀
460
- const scopeKey = `${this.scope}:${key}`;
461
- return await this._safeCall('addInt', [scopeKey, step]);
462
- };
463
-
464
- /**
465
- * @description 追加字符串
466
- * @param {String} key 键名
467
- * @param {String} value 要追加的字符串
468
- * @return {Promise<Number>} 追加后的字符串长度
469
- */
470
- Cache.prototype.addStr = async function (key, value) {
471
- // 添加作用域前缀
472
- const scopeKey = `${this.scope}:${key}`;
473
- return await this._safeCall('addStr', [scopeKey, value]);
474
- };
475
-
476
- /**
477
- * @description 原子递增浮点数
478
- * @param {String} key 键名
479
- * @param {Number} step 步长,默认1.0
480
- * @return {Promise<Number>} 递增后的值
481
- */
482
- Cache.prototype.addFloat = async function (key, step = 1.0) {
483
- // 确保step是数字类型
484
- step = parseFloat(step) || 1.0;
485
- // 添加作用域前缀
486
- const scopeKey = `${this.scope}:${key}`;
487
- return await this._safeCall('addFloat', [scopeKey, step]);
488
- };
489
-
490
- /**
491
- * @description 增加指定的值
492
- * @param {String} key 键名
493
- * @param {Number} value 要增加的值
494
- * @param {Object} options 配置选项
495
- * @return {Promise<Number>} 增加后的值
496
- */
497
- Cache.prototype.incrby = async function (key, value, options) {
498
- // 添加作用域前缀
499
- const scopeKey = `${this.scope}:${key}`;
500
- return await this._safeCall('incrby', [scopeKey, value], options);
501
- };
502
-
503
- /**
504
- * @description 减少指定的值
505
- * @param {String} key 键名
506
- * @param {Number} value 要减少的值
507
- * @param {Object} options 配置选项
508
- * @return {Promise<Number>} 减少后的值
509
- */
510
- Cache.prototype.decrby = async function (key, value, options) {
511
- // 添加作用域前缀
512
- const scopeKey = `${this.scope}:${key}`;
513
- return await this._safeCall('decrby', [scopeKey, value], options);
514
- };
515
-
516
- /**
517
- * @description 增加浮点数
518
- * @param {String} key 键名
519
- * @param {Number} value 要增加的值
520
- * @param {Object} options 配置选项
521
- * @return {Promise<Number>} 增加后的值
522
- */
523
- Cache.prototype.incrbyfloat = async function (key, value, options) {
524
- // 添加作用域前缀
525
- const scopeKey = `${this.scope}:${key}`;
526
- return await this._safeCall('incrbyfloat', [scopeKey, value], options);
527
- };
528
-
529
- /**
530
- * @description 批量设置缓存
531
- * @param {Array} keyValues 键值对数组,格式: [key1, value1, key2, value2, ...]
532
- * @return {Promise<Boolean>} 是否设置成功
533
- */
534
- Cache.prototype.mset = async function (...keyValues) {
535
- // 添加作用域前缀到所有键名
536
- const scopeKeyValues = [];
537
- for (let i = 0; i < keyValues.length; i += 2) {
538
- scopeKeyValues.push(`${this.scope}:${keyValues[i]}`);
539
- scopeKeyValues.push(keyValues[i + 1]);
540
- }
541
- return await this._safeCall('mset', scopeKeyValues);
542
- };
543
-
544
- /**
545
- * @description 批量获取缓存
546
- * @param {Array} keys 键名数组
547
- * @return {Promise<Array>} 缓存值数组
548
- */
549
- Cache.prototype.mget = async function (...keys) {
550
- // 处理参数:如果第一个参数是数组,则使用该数组;否则使用所有参数作为数组
551
- let keysToUse = keys;
552
- if (keys.length === 1 && Array.isArray(keys[0])) {
553
- keysToUse = keys[0];
554
- }
555
- // 添加作用域前缀到所有键名
556
- const scopeKeys = keysToUse.map(key => `${this.scope}:${key}`);
557
- // 注意:这里直接传递scopeKeys数组作为单个参数,而不是展开
558
- return await this._safeCall('mget', [scopeKeys]);
559
- };
560
-
561
- /**
562
- * @description 哈希表设置字段
563
- * @param {String} key 键名
564
- * @param {String} field 字段名
565
- * @param {Any} value 字段值
566
- * @return {Promise<Number>} 1表示新字段,0表示更新已有字段
567
- */
568
- Cache.prototype.hset = async function (key, field, value) {
569
- // 添加作用域前缀
570
- const scopeKey = `${this.scope}:${key}`;
571
- return await this._safeCall('hset', [scopeKey, field, value]);
572
- };
573
-
574
- /**
575
- * @description 哈希表获取字段
576
- * @param {String} key 键名
577
- * @param {String} field 字段名
578
- * @return {Promise<Any>} 字段值
579
- */
580
- Cache.prototype.hget = async function (key, field) {
581
- // 添加作用域前缀
582
- const scopeKey = `${this.scope}:${key}`;
583
- return await this._safeCall('hget', [scopeKey, field]);
584
- };
585
-
586
- /**
587
- * @description 哈希表获取所有字段和值
588
- * @param {String} key 键名
589
- * @return {Promise<Object>} 所有字段和值
590
- */
591
- Cache.prototype.hgetall = async function (key) {
592
- // 添加作用域前缀
593
- const scopeKey = `${this.scope}:${key}`;
594
- return await this._safeCall('hgetall', [scopeKey]);
595
- };
596
-
597
- /**
598
- * @description 哈希表删除字段
599
- * @param {String} key 键名
600
- * @param {String} field 字段名
601
- * @return {Promise<Number>} 删除的字段数量
602
- */
603
- Cache.prototype.hdel = async function (key, field) {
604
- // 添加作用域前缀
605
- const scopeKey = `${this.scope}:${key}`;
606
- return await this._safeCall('hdel', [scopeKey, field]);
607
- };
608
-
609
- /**
610
- * @description 哈希表批量设置字段
611
- * @param {String} key 键名
612
- * @param {Array} fieldValues 字段值对数组,格式: [field1, value1, field2, value2, ...]
613
- * @return {Promise<Number>} 设置的字段数量
614
- */
615
- Cache.prototype.hmset = async function (key, ...fieldValues) {
616
- // 添加作用域前缀
617
- const scopeKey = `${this.scope}:${key}`;
618
- return await this._safeCall('hmset', [scopeKey, ...fieldValues]);
619
- };
620
-
621
- /**
622
- * @description 哈希表批量获取字段
623
- * @param {String} key 键名
624
- * @param {Array} fields 字段名数组
625
- * @return {Promise<Array>} 字段值数组
626
- */
627
- Cache.prototype.hmget = async function (key, ...fields) {
628
- // 添加作用域前缀
629
- const scopeKey = `${this.scope}:${key}`;
630
- return await this._safeCall('hmget', [scopeKey, ...fields]);
631
- };
632
-
633
- /**
634
- * @description 获取哈希表字段数量
635
- * @param {String} key 键名
636
- * @return {Promise<Number>} 字段数量
637
- */
638
- Cache.prototype.hlen = async function (key) {
639
- // 添加作用域前缀
640
- const scopeKey = `${this.scope}:${key}`;
641
- return await this._safeCall('hlen', [scopeKey]);
642
- };
643
-
644
- /**
645
- * @description 获取字符串长度
646
- * @param {String} key 键名
647
- * @return {Promise<Number>} 字符串长度
648
- */
649
- Cache.prototype.strlen = async function (key) {
650
- // 添加作用域前缀
651
- const scopeKey = `${this.scope}:${key}`;
652
- return await this._safeCall('strlen', [scopeKey]);
653
- };
654
-
655
- /**
656
- * @description 集合添加成员
657
- * @param {String} key 键名
658
- * @param {Array} members 成员数组
659
- * @return {Promise<Number>} 新增的成员数量
660
- */
661
- Cache.prototype.sadd = async function (key, ...members) {
662
- // 添加作用域前缀
663
- const scopeKey = `${this.scope}:${key}`;
664
- return await this._safeCall('sadd', [scopeKey, ...members]);
665
- };
666
-
667
- /**
668
- * @description 集合删除成员
669
- * @param {String} key 键名
670
- * @param {Array} members 成员数组
671
- * @return {Promise<Number>} 删除的成员数量
672
- */
673
- Cache.prototype.srem = async function (key, ...members) {
674
- // 添加作用域前缀
675
- const scopeKey = `${this.scope}:${key}`;
676
- return await this._safeCall('srem', [scopeKey, ...members]);
677
- };
678
-
679
- /**
680
- * @description 检查成员是否在集合中
681
- * @param {String} key 键名
682
- * @param {String} member 成员
683
- * @return {Promise<Boolean>} 是否存在
684
- */
685
- Cache.prototype.sismember = async function (key, member) {
686
- // 添加作用域前缀
687
- const scopeKey = `${this.scope}:${key}`;
688
- return await this._safeCall('sismember', [scopeKey, member]);
689
- };
690
-
691
- /**
692
- * @description 获取集合所有成员
693
- * @param {String} key 键名
694
- * @return {Promise<Array>} 成员数组
695
- */
696
- Cache.prototype.smembers = async function (key) {
697
- // 添加作用域前缀
698
- const scopeKey = `${this.scope}:${key}`;
699
- return await this._safeCall('smembers', [scopeKey]);
700
- };
701
-
702
- /**
703
- * @description 以毫秒为单位设置过期时间
704
- * @param {String} key 键名
705
- * @param {Number} milliseconds 过期时间(毫秒)
706
- * @return {Promise<Boolean>} 是否设置成功
707
- */
708
- Cache.prototype.pexpire = async function (key, milliseconds) {
709
- // 添加作用域前缀
710
- const scopeKey = `${this.scope}:${key}`;
711
- return await this._safeCall('pexpire', [scopeKey, milliseconds]);
712
- };
713
-
714
- /**
715
- * @description 移除键的过期时间
716
- * @param {String} key 键名
717
- * @return {Promise<Boolean>} 是否移除成功
718
- */
719
- Cache.prototype.persist = async function (key) {
720
- // 添加作用域前缀
721
- const scopeKey = `${this.scope}:${key}`;
722
- return await this._safeCall('persist', [scopeKey]);
723
- };
724
-
725
- /**
726
- * @description 重命名键
727
- * @param {String} oldKey 旧键名
728
- * @param {String} newKey 新键名
729
- * @return {Promise<Boolean>} 是否重命名成功
730
- */
731
- Cache.prototype.rename = async function (oldKey, newKey) {
732
- // 添加作用域前缀
733
- const scopeOldKey = `${this.scope}:${oldKey}`;
734
- const scopeNewKey = `${this.scope}:${newKey}`;
735
- return await this._safeCall('rename', [scopeOldKey, scopeNewKey]);
736
- };
737
-
738
- /**
739
- * @description 获取键的类型
740
- * @param {String} key 键名
741
- * @return {Promise<String>} 类型(none|string|list|set|zset|hash)
742
- */
743
- Cache.prototype.type = async function (key) {
744
- // 添加作用域前缀
745
- const scopeKey = `${this.scope}:${key}`;
746
- return await this._safeCall('type', [scopeKey]);
747
- };
748
-
749
- /**
750
- * @description 设置列表内容
751
- * @param {String} key 键名
752
- * @param {Array} value 列表值
753
- * @param {Number} expire 过期时间(秒)
754
- * @return {Promise<Boolean>} 是否成功
755
- */
756
- Cache.prototype.setForList = async function (key, value, expire) {
757
- // 添加作用域前缀
758
- const scopeKey = `${this.scope}:${key}`;
759
- return await this._safeCall('setForList', [scopeKey, value, expire]);
760
- };
761
-
762
- /**
763
- * @description 向列表添加元素
764
- * @param {String} key 键名
765
- * @param {*} value 要添加的元素
766
- * @return {Promise<Boolean>} 是否成功
767
- */
768
- Cache.prototype.addForList = async function (key, value) {
769
- // 添加作用域前缀
770
- const scopeKey = `${this.scope}:${key}`;
771
- return await this._safeCall('addForList', [scopeKey, value]);
772
- };
773
-
774
- /**
775
- * @description 检查列表中是否包含指定元素
776
- * @param {String} key 键名
777
- * @param {*} value 要检查的元素
778
- * @return {Promise<Boolean>} 是否包含
779
- */
780
- Cache.prototype.hasForList = async function (key, value) {
781
- // 添加作用域前缀
782
- const scopeKey = `${this.scope}:${key}`;
783
- return await this._safeCall('hasForList', [scopeKey, value]);
784
- };
785
-
786
- /**
787
- * @description 获取列表指定范围的元素
788
- * @param {String} key 键名
789
- * @param {Number} start 起始索引,默认0
790
- * @param {Number} stop 结束索引,默认-1(表示到末尾)
791
- * @return {Promise<Array>} 元素数组
792
- */
793
- Cache.prototype.getForList = async function (key, start = 0, stop = -1) {
794
- // 添加作用域前缀
795
- const scopeKey = `${this.scope}:${key}`;
796
- return await this._safeCall('getForList', [scopeKey, start, stop]);
797
- };
798
-
799
- /**
800
- * @description 清空列表,保留键和过期时间
801
- * @param {String} key 键名
802
- * @return {Promise<Boolean>} 是否成功
803
- */
804
- Cache.prototype.clearForList = async function (key) {
805
- // 添加作用域前缀
806
- const scopeKey = `${this.scope}:${key}`;
807
- return await this._safeCall('clearForList', [scopeKey]);
808
- };
809
-
810
- /**
811
- * @description 清理缓存
812
- * @param {String} key 匹配模式
813
- * @return {Promise<Boolean>} 是否清理成功
814
- */
815
- Cache.prototype.clear = async function (key) {
816
- // 添加作用域前缀
817
- const scopeKey = key ? `${this.scope}:${key}` : `${this.scope}:*`;
818
- return await this._safeCall('clear', [scopeKey]);
819
- };
820
-
821
- /**
822
- * @description 清理过期缓存
823
- * @return {Promise<Boolean>} 是否清理成功
824
- */
825
- Cache.prototype.clearExpire = async function () {
826
- return await this._safeCall('clearExpire', []);
827
- };
828
-
829
- /**
830
- * @description 关闭数据库连接
831
- * @return {Promise<Boolean>} 是否关闭成功
832
- */
833
- Cache.prototype.dispose = async function () {
834
- if (this._client && typeof this._client.dispose === 'function') {
835
- return await this._client.dispose();
836
- }
837
- return true;
838
- };
839
-
840
-
841
-
842
- /**
843
- * 确保连接池对象存在
844
- */
845
- if (!$.pool) {
846
- $.pool = {};
847
- }
848
- if (!$.pool.cache) {
849
- $.pool.cache = {};
850
- }
851
-
852
- /**
853
- * @description Cache管理器,用于创建缓存
854
- * @param {String} scope 作用域
855
- * @param {Object} config 配置参数
856
- * @return {Object} 返回一个Cache类实例
857
- */
858
- function cacheAdmin(scope, config = {}) {
859
- if (!scope) {
860
- scope = 'sys';
861
- }
862
- var obj = $.pool.cache[scope];
863
- if (!obj) {
864
- config.scope = scope;
865
- $.pool.cache[scope] = new Cache(config);
866
- obj = $.pool.cache[scope];
867
- }
868
- return obj;
869
- }
5
+ let admin = new Admin();
6
+ admin.setClass(Cache);
870
7
 
871
8
  /**
872
9
  * @module 导出Cache管理器
873
10
  */
874
11
  module.exports = {
875
12
  Cache,
876
- cacheAdmin
13
+ admin,
14
+ cacheAdmin(scope, config = {}) {
15
+ if (!scope) {
16
+ scope = 'os';
17
+ }
18
+ return admin.get(scope, { name: scope, ...config });
19
+ },
20
+ getCache() {
21
+ return admin.get('os');
22
+ }
877
23
  };