@taicode/common-server 1.0.11 → 1.0.13
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.
- package/output/index.d.ts +1 -0
- package/output/index.d.ts.map +1 -1
- package/output/index.js +1 -0
- package/output/redis-queue/index.d.ts +6 -4
- package/output/redis-queue/index.d.ts.map +1 -1
- package/output/redis-queue/index.js +4 -2
- package/output/redis-queue/redis-batch-consumer.d.ts +80 -0
- package/output/redis-queue/redis-batch-consumer.d.ts.map +1 -0
- package/output/redis-queue/redis-batch-consumer.js +308 -0
- package/output/redis-queue/redis-batch-consumer.test.d.ts +7 -0
- package/output/redis-queue/redis-batch-consumer.test.d.ts.map +1 -0
- package/output/redis-queue/redis-batch-consumer.test.js +265 -0
- package/output/redis-queue/redis-queue-common.d.ts +73 -0
- package/output/redis-queue/redis-queue-common.d.ts.map +1 -0
- package/output/redis-queue/redis-queue-common.js +302 -0
- package/output/redis-queue/redis-queue-common.test.d.ts +19 -0
- package/output/redis-queue/redis-queue-common.test.d.ts.map +1 -0
- package/output/redis-queue/redis-queue-common.test.js +623 -0
- package/output/redis-queue/redis-queue-consumer.d.ts +81 -0
- package/output/redis-queue/redis-queue-consumer.d.ts.map +1 -0
- package/output/redis-queue/redis-queue-consumer.js +297 -0
- package/output/redis-queue/redis-queue-consumer.test.d.ts +7 -0
- package/output/redis-queue/redis-queue-consumer.test.d.ts.map +1 -0
- package/output/redis-queue/redis-queue-consumer.test.js +242 -0
- package/output/redis-queue/redis-queue-provider.d.ts +56 -0
- package/output/redis-queue/redis-queue-provider.d.ts.map +1 -0
- package/output/redis-queue/redis-queue-provider.js +187 -0
- package/output/redis-queue/redis-queue-provider.test.d.ts +7 -0
- package/output/redis-queue/redis-queue-provider.test.d.ts.map +1 -0
- package/output/redis-queue/redis-queue-provider.test.js +114 -0
- package/output/redis-queue/types.d.ts +77 -19
- package/output/redis-queue/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/output/logger/logger.d.ts +0 -33
- package/output/logger/logger.d.ts.map +0 -1
- package/output/logger/logger.js +0 -65
- package/output/logger/logger.test.d.ts +0 -2
- package/output/logger/logger.test.d.ts.map +0 -1
- package/output/logger/logger.test.js +0 -87
- package/output/redis-queue/batch-redis-queue.d.ts +0 -136
- package/output/redis-queue/batch-redis-queue.d.ts.map +0 -1
- package/output/redis-queue/batch-redis-queue.js +0 -573
- package/output/redis-queue/batch-redis-queue.test.d.ts +0 -2
- package/output/redis-queue/batch-redis-queue.test.d.ts.map +0 -1
- package/output/redis-queue/batch-redis-queue.test.js +0 -243
- package/output/redis-queue/redis-queue.d.ts +0 -129
- package/output/redis-queue/redis-queue.d.ts.map +0 -1
- package/output/redis-queue/redis-queue.js +0 -547
- package/output/redis-queue/redis-queue.test.d.ts +0 -2
- package/output/redis-queue/redis-queue.test.d.ts.map +0 -1
- package/output/redis-queue/redis-queue.test.js +0 -234
package/output/index.d.ts
CHANGED
package/output/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../source/index.ts"],"names":[],"mappings":"AACA,cAAc,UAAU,CAAA"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../source/index.ts"],"names":[],"mappings":"AACA,cAAc,UAAU,CAAA;AACxB,cAAc,eAAe,CAAA"}
|
package/output/index.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
export {
|
|
2
|
-
export {
|
|
3
|
-
export
|
|
4
|
-
export type {
|
|
1
|
+
export { RedisQueueProvider } from './redis-queue-provider';
|
|
2
|
+
export { RedisQueueConsumer } from './redis-queue-consumer';
|
|
3
|
+
export { RedisBatchConsumer } from './redis-batch-consumer';
|
|
4
|
+
export type { RedisQueueProviderConfig, RedisQueueConsumerConfig, BatchConsumerConfig } from './types';
|
|
5
|
+
export type { TaskData } from './types';
|
|
6
|
+
export type { RedisQueueRegistry } from './types';
|
|
5
7
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/redis-queue/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/redis-queue/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAA;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAA;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAA;AAG3D,YAAY,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAGtG,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAGvC,YAAY,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA"}
|
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
export {
|
|
1
|
+
// 核心类导出
|
|
2
|
+
export { RedisQueueProvider } from './redis-queue-provider';
|
|
3
|
+
export { RedisQueueConsumer } from './redis-queue-consumer';
|
|
4
|
+
export { RedisBatchConsumer } from './redis-batch-consumer';
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { RedisQueueCommon } from './redis-queue-common';
|
|
2
|
+
import type { BatchConsumerConfig, QueueStats, RedisQueueRegistry } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* Redis 批量队列消费者
|
|
5
|
+
*
|
|
6
|
+
* 批量消费任务,每次处理多条
|
|
7
|
+
*
|
|
8
|
+
* @template K 队列键名类型
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* interface EmailTask {
|
|
13
|
+
* to: string
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* const consumer = new RedisBatchConsumer<EmailTask>({
|
|
17
|
+
* redisUrl: 'redis://localhost:6379',
|
|
18
|
+
* queueKey: 'email-queue',
|
|
19
|
+
* batchSize: 50,
|
|
20
|
+
* handler: async (dataList) => {
|
|
21
|
+
* await sendEmailsBatch(dataList.map(d => d.to))
|
|
22
|
+
* return catchIt(() => {})
|
|
23
|
+
* }
|
|
24
|
+
* })
|
|
25
|
+
*
|
|
26
|
+
* await consumer.connect() // 自动开始消费
|
|
27
|
+
*
|
|
28
|
+
* // 获取统计信息
|
|
29
|
+
* const stats = await consumer.statistics()
|
|
30
|
+
*
|
|
31
|
+
* // 停止消费
|
|
32
|
+
* consumer.disconnect()
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
export declare class RedisBatchConsumer<K extends keyof RedisQueueRegistry> extends RedisQueueCommon {
|
|
36
|
+
private consumerRunning;
|
|
37
|
+
private consumerInterval;
|
|
38
|
+
private recoveryInterval;
|
|
39
|
+
private processingBatches;
|
|
40
|
+
private readonly config;
|
|
41
|
+
constructor(config: BatchConsumerConfig<K>);
|
|
42
|
+
protected getLogPrefix(): string;
|
|
43
|
+
/**
|
|
44
|
+
* 连接 Redis 并自动启动消费者
|
|
45
|
+
*/
|
|
46
|
+
connect(): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* 断开 Redis 连接并停止消费者
|
|
49
|
+
*/
|
|
50
|
+
disconnect(): void;
|
|
51
|
+
/**
|
|
52
|
+
* 批量处理任务
|
|
53
|
+
*/
|
|
54
|
+
private processBatch;
|
|
55
|
+
/**
|
|
56
|
+
* 启动恢复机制
|
|
57
|
+
*/
|
|
58
|
+
private startRecovery;
|
|
59
|
+
/**
|
|
60
|
+
* 停止恢复机制
|
|
61
|
+
*/
|
|
62
|
+
private stopRecovery;
|
|
63
|
+
/**
|
|
64
|
+
* 启动消费者
|
|
65
|
+
*/
|
|
66
|
+
private startConsumer;
|
|
67
|
+
/**
|
|
68
|
+
* 停止消费者
|
|
69
|
+
*/
|
|
70
|
+
private stopConsumer;
|
|
71
|
+
/**
|
|
72
|
+
* 获取队列统计信息(O(1) 时间复杂度)
|
|
73
|
+
*/
|
|
74
|
+
statistics(): Promise<QueueStats>;
|
|
75
|
+
/**
|
|
76
|
+
* 健康检查
|
|
77
|
+
*/
|
|
78
|
+
health(): Promise<boolean>;
|
|
79
|
+
}
|
|
80
|
+
//# sourceMappingURL=redis-batch-consumer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redis-batch-consumer.d.ts","sourceRoot":"","sources":["../../source/redis-queue/redis-batch-consumer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AACvD,OAAO,KAAK,EAAE,mBAAmB,EAA0B,UAAU,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AAE1G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,qBAAa,kBAAkB,CAAC,CAAC,SAAS,MAAM,kBAAkB,CAAE,SAAQ,gBAAgB;IAC1F,OAAO,CAAC,eAAe,CAAQ;IAC/B,OAAO,CAAC,gBAAgB,CAA8B;IACtD,OAAO,CAAC,gBAAgB,CAA8B;IACtD,OAAO,CAAC,iBAAiB,CAAI;IAE7B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAOtB;gBAEW,MAAM,EAAE,mBAAmB,CAAC,CAAC,CAAC;IA2B1C,SAAS,CAAC,YAAY,IAAI,MAAM;IAIhC;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAO9B;;OAEG;IACH,UAAU,IAAI,IAAI;IAMlB;;OAEG;YACW,YAAY;IA4F1B;;OAEG;IACH,OAAO,CAAC,aAAa;IAoBrB;;OAEG;IACH,OAAO,CAAC,YAAY;IAQpB;;OAEG;IACH,OAAO,CAAC,aAAa;IAyErB;;OAEG;IACH,OAAO,CAAC,YAAY;IASpB;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,UAAU,CAAC;IAevC;;OAEG;IACG,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC;CAMjC"}
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { catchIt } from '@taicode/common-base';
|
|
2
|
+
import { RedisQueueCommon } from './redis-queue-common';
|
|
3
|
+
/**
|
|
4
|
+
* Redis 批量队列消费者
|
|
5
|
+
*
|
|
6
|
+
* 批量消费任务,每次处理多条
|
|
7
|
+
*
|
|
8
|
+
* @template K 队列键名类型
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* interface EmailTask {
|
|
13
|
+
* to: string
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* const consumer = new RedisBatchConsumer<EmailTask>({
|
|
17
|
+
* redisUrl: 'redis://localhost:6379',
|
|
18
|
+
* queueKey: 'email-queue',
|
|
19
|
+
* batchSize: 50,
|
|
20
|
+
* handler: async (dataList) => {
|
|
21
|
+
* await sendEmailsBatch(dataList.map(d => d.to))
|
|
22
|
+
* return catchIt(() => {})
|
|
23
|
+
* }
|
|
24
|
+
* })
|
|
25
|
+
*
|
|
26
|
+
* await consumer.connect() // 自动开始消费
|
|
27
|
+
*
|
|
28
|
+
* // 获取统计信息
|
|
29
|
+
* const stats = await consumer.statistics()
|
|
30
|
+
*
|
|
31
|
+
* // 停止消费
|
|
32
|
+
* consumer.disconnect()
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
export class RedisBatchConsumer extends RedisQueueCommon {
|
|
36
|
+
consumerRunning = false;
|
|
37
|
+
consumerInterval = null;
|
|
38
|
+
recoveryInterval = null;
|
|
39
|
+
processingBatches = 0; // 当前正在处理的批次数
|
|
40
|
+
config;
|
|
41
|
+
constructor(config) {
|
|
42
|
+
// 验证必填参数
|
|
43
|
+
if (!config.handler) {
|
|
44
|
+
throw new Error('[RedisBatchConsumer] handler is required');
|
|
45
|
+
}
|
|
46
|
+
// 调用父类构造函数
|
|
47
|
+
super({
|
|
48
|
+
redisUrl: config.redisUrl,
|
|
49
|
+
redisClient: config.redisClient,
|
|
50
|
+
queueKey: config.queueKey,
|
|
51
|
+
cleanupDelay: config.cleanupDelay ?? 86400,
|
|
52
|
+
});
|
|
53
|
+
this.config = {
|
|
54
|
+
handler: config.handler,
|
|
55
|
+
queueKey: config.queueKey,
|
|
56
|
+
redisUrl: config.redisUrl,
|
|
57
|
+
redisClient: config.redisClient,
|
|
58
|
+
batchSize: config.batchSize ?? 10,
|
|
59
|
+
maxRetries: config.maxRetries ?? 3,
|
|
60
|
+
concurrency: config.concurrency ?? 1,
|
|
61
|
+
consumerInterval: config.consumerInterval ?? 1000,
|
|
62
|
+
processingTimeout: config.processingTimeout ?? 60000, // 60 seconds
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
getLogPrefix() {
|
|
66
|
+
return 'RedisBatchConsumer';
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* 连接 Redis 并自动启动消费者
|
|
70
|
+
*/
|
|
71
|
+
async connect() {
|
|
72
|
+
await super.connect();
|
|
73
|
+
// 连接成功后启动消费者和恢复机制
|
|
74
|
+
this.startConsumer();
|
|
75
|
+
this.startRecovery();
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* 断开 Redis 连接并停止消费者
|
|
79
|
+
*/
|
|
80
|
+
disconnect() {
|
|
81
|
+
this.stopConsumer();
|
|
82
|
+
this.stopRecovery();
|
|
83
|
+
super.disconnect();
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* 批量处理任务
|
|
87
|
+
*/
|
|
88
|
+
async processBatch(taskIds) {
|
|
89
|
+
this.processingBatches++;
|
|
90
|
+
try {
|
|
91
|
+
// 获取所有任务
|
|
92
|
+
const tasks = await Promise.all(taskIds.map(id => this.getTask(id)));
|
|
93
|
+
const validTasks = tasks.filter((task) => task !== null);
|
|
94
|
+
if (validTasks.length === 0) {
|
|
95
|
+
console.warn(`[RedisBatchConsumer] No valid tasks found in batch`);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
// 过滤出有效的待处理任务
|
|
99
|
+
const tasksToProcess = [];
|
|
100
|
+
for (const task of validTasks) {
|
|
101
|
+
// 检查状态
|
|
102
|
+
if (task.status !== 'pending') {
|
|
103
|
+
console.log(`[RedisBatchConsumer] Task ${task.id} has invalid status (${task.status}), marking as failed`);
|
|
104
|
+
await this.applyStatus(task.id, task.status, 'failed');
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
tasksToProcess.push(task);
|
|
108
|
+
}
|
|
109
|
+
if (tasksToProcess.length === 0) {
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
// 任务已在 processing 队列中(由 Lua 脚本完成),只需更新状态和开始时间
|
|
114
|
+
const taskIdList = tasksToProcess.map(t => t.id);
|
|
115
|
+
const now = Date.now();
|
|
116
|
+
await Promise.all(tasksToProcess.map(task => {
|
|
117
|
+
task.status = 'processing';
|
|
118
|
+
task.processingStartTime = now;
|
|
119
|
+
const taskKey = `${this.queueKey}:task:${task.id}`;
|
|
120
|
+
return this.redis.setEx(taskKey, this.cleanupDelay, JSON.stringify(task));
|
|
121
|
+
}));
|
|
122
|
+
// 批量处理所有任务
|
|
123
|
+
const dataList = tasksToProcess.map(t => t.data);
|
|
124
|
+
await this.config.handler(dataList);
|
|
125
|
+
// 批量更新状态为完成
|
|
126
|
+
const updatedCount = await this.applyStatusBatch(taskIdList, 'processing', 'completed');
|
|
127
|
+
console.log(`[RedisBatchConsumer] Batch completed: ${updatedCount} tasks`);
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
console.error(`[RedisBatchConsumer] Batch failed:`, error);
|
|
131
|
+
// 批量重试或失败
|
|
132
|
+
for (const task of tasksToProcess) {
|
|
133
|
+
if (task.retryCount < task.maxRetries) {
|
|
134
|
+
task.retryCount++;
|
|
135
|
+
task.status = 'pending';
|
|
136
|
+
task.processingStartTime = undefined;
|
|
137
|
+
const taskKey = `${this.queueKey}:task:${task.id}`;
|
|
138
|
+
const script = `
|
|
139
|
+
redis.call('SETEX', KEYS[1], ARGV[1], ARGV[2])
|
|
140
|
+
redis.call('LREM', KEYS[2], 0, ARGV[3])
|
|
141
|
+
redis.call('RPUSH', KEYS[3], ARGV[3])
|
|
142
|
+
return 1
|
|
143
|
+
`;
|
|
144
|
+
await this.redis.eval(script, {
|
|
145
|
+
keys: [taskKey, this.processingQueue, this.pendingQueue],
|
|
146
|
+
arguments: [this.cleanupDelay.toString(), JSON.stringify(task), task.id],
|
|
147
|
+
});
|
|
148
|
+
console.log(`[RedisBatchConsumer] Task ${task.id} will retry (${task.retryCount}/${task.maxRetries})`);
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
task.status = 'failed';
|
|
152
|
+
task.processingStartTime = undefined;
|
|
153
|
+
const taskKey = `${this.queueKey}:task:${task.id}`;
|
|
154
|
+
const script = `
|
|
155
|
+
redis.call('SETEX', KEYS[1], ARGV[1], ARGV[2])
|
|
156
|
+
redis.call('LREM', KEYS[2], 0, ARGV[3])
|
|
157
|
+
redis.call('RPUSH', KEYS[3], ARGV[3])
|
|
158
|
+
return 1
|
|
159
|
+
`;
|
|
160
|
+
await this.redis.eval(script, {
|
|
161
|
+
keys: [taskKey, this.processingQueue, this.failedQueue],
|
|
162
|
+
arguments: [this.cleanupDelay.toString(), JSON.stringify(task), task.id],
|
|
163
|
+
});
|
|
164
|
+
console.error(`[RedisBatchConsumer] Task ${task.id} failed after ${task.maxRetries} retries`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
this.processingBatches--;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* 启动恢复机制
|
|
175
|
+
*/
|
|
176
|
+
startRecovery() {
|
|
177
|
+
if (this.recoveryInterval || !this.redis) {
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
// 立即执行一次恢复
|
|
181
|
+
this.recoverStalled(this.config.processingTimeout).catch(error => {
|
|
182
|
+
console.error('[RedisBatchConsumer] Initial recovery error:', error);
|
|
183
|
+
});
|
|
184
|
+
// 定期检查(每 10 秒检查一次)
|
|
185
|
+
this.recoveryInterval = setInterval(() => {
|
|
186
|
+
this.recoverStalled(this.config.processingTimeout).catch(error => {
|
|
187
|
+
console.error('[RedisBatchConsumer] Recovery error:', error);
|
|
188
|
+
});
|
|
189
|
+
}, 10000);
|
|
190
|
+
console.log('[RedisBatchConsumer] Recovery mechanism started');
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* 停止恢复机制
|
|
194
|
+
*/
|
|
195
|
+
stopRecovery() {
|
|
196
|
+
if (this.recoveryInterval) {
|
|
197
|
+
clearInterval(this.recoveryInterval);
|
|
198
|
+
this.recoveryInterval = null;
|
|
199
|
+
console.log('[RedisBatchConsumer] Recovery mechanism stopped');
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* 启动消费者
|
|
204
|
+
*/
|
|
205
|
+
startConsumer() {
|
|
206
|
+
if (this.consumerRunning || !this.redis) {
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
this.consumerRunning = true;
|
|
210
|
+
console.log(`[RedisBatchConsumer] Consumer started with batchSize: ${this.config.batchSize}, concurrency: ${this.config.concurrency}`);
|
|
211
|
+
// Lua 脚本: 批量原子化从 pending 取出任务并移到 processing
|
|
212
|
+
const popAndMoveBatchScript = `
|
|
213
|
+
local pendingQueue = KEYS[1]
|
|
214
|
+
local processingQueue = KEYS[2]
|
|
215
|
+
local queueKeyPrefix = KEYS[3]
|
|
216
|
+
local count = tonumber(ARGV[1])
|
|
217
|
+
local currentTime = tonumber(ARGV[2])
|
|
218
|
+
|
|
219
|
+
local taskIds = {}
|
|
220
|
+
local checkedCount = 0
|
|
221
|
+
local maxCheck = count * 3
|
|
222
|
+
|
|
223
|
+
while #taskIds < count and checkedCount < maxCheck do
|
|
224
|
+
local taskId = redis.call('LPOP', pendingQueue)
|
|
225
|
+
if not taskId then
|
|
226
|
+
break
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
checkedCount = checkedCount + 1
|
|
230
|
+
|
|
231
|
+
local taskKey = queueKeyPrefix .. ':task:' .. taskId
|
|
232
|
+
local taskData = redis.call('GET', taskKey)
|
|
233
|
+
|
|
234
|
+
if taskData then
|
|
235
|
+
local task = cjson.decode(taskData)
|
|
236
|
+
local delayUntil = task.delayUntil
|
|
237
|
+
|
|
238
|
+
if not delayUntil or delayUntil <= currentTime then
|
|
239
|
+
redis.call('RPUSH', processingQueue, taskId)
|
|
240
|
+
table.insert(taskIds, taskId)
|
|
241
|
+
else
|
|
242
|
+
redis.call('RPUSH', pendingQueue, taskId)
|
|
243
|
+
end
|
|
244
|
+
end
|
|
245
|
+
end
|
|
246
|
+
|
|
247
|
+
return taskIds
|
|
248
|
+
`;
|
|
249
|
+
this.consumerInterval = setInterval(async () => {
|
|
250
|
+
try {
|
|
251
|
+
// 检查当前是否有可用的并发槽位
|
|
252
|
+
const availableSlots = this.config.concurrency - this.processingBatches;
|
|
253
|
+
if (availableSlots <= 0) {
|
|
254
|
+
return; // 已达到并发限制
|
|
255
|
+
}
|
|
256
|
+
// 批量取出任务
|
|
257
|
+
const taskIds = await this.redis.eval(popAndMoveBatchScript, {
|
|
258
|
+
keys: [this.pendingQueue, this.processingQueue, this.queueKey],
|
|
259
|
+
arguments: [this.config.batchSize.toString(), Date.now().toString()],
|
|
260
|
+
});
|
|
261
|
+
if (taskIds.length > 0) {
|
|
262
|
+
// 处理这批任务(不等待完成)
|
|
263
|
+
this.processBatch(taskIds).catch(error => {
|
|
264
|
+
console.error(`[RedisBatchConsumer] Unhandled error in processBatch:`, error);
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
console.error('[RedisBatchConsumer] Consumer error:', error);
|
|
270
|
+
}
|
|
271
|
+
}, this.config.consumerInterval);
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* 停止消费者
|
|
275
|
+
*/
|
|
276
|
+
stopConsumer() {
|
|
277
|
+
if (this.consumerInterval) {
|
|
278
|
+
clearInterval(this.consumerInterval);
|
|
279
|
+
this.consumerInterval = null;
|
|
280
|
+
}
|
|
281
|
+
this.consumerRunning = false;
|
|
282
|
+
console.log('[RedisBatchConsumer] Consumer stopped');
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* 获取队列统计信息(O(1) 时间复杂度)
|
|
286
|
+
*/
|
|
287
|
+
async statistics() {
|
|
288
|
+
if (!this.redis) {
|
|
289
|
+
return { pending: 0, processing: 0, completed: 0, failed: 0 };
|
|
290
|
+
}
|
|
291
|
+
const [pending, processing, completed, failed] = await Promise.all([
|
|
292
|
+
this.redis.lLen(this.pendingQueue),
|
|
293
|
+
this.redis.lLen(this.processingQueue),
|
|
294
|
+
this.redis.lLen(this.completedQueue),
|
|
295
|
+
this.redis.lLen(this.failedQueue),
|
|
296
|
+
]);
|
|
297
|
+
return { pending, processing, completed, failed };
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* 健康检查
|
|
301
|
+
*/
|
|
302
|
+
async health() {
|
|
303
|
+
if (!this.redis)
|
|
304
|
+
return false;
|
|
305
|
+
const result = await catchIt(() => this.redis.ping());
|
|
306
|
+
return !result.isError() && result.value === 'PONG';
|
|
307
|
+
}
|
|
308
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redis-batch-consumer.test.d.ts","sourceRoot":"","sources":["../../source/redis-queue/redis-batch-consumer.test.ts"],"names":[],"mappings":"AAOA,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAU,kBAAkB;QAC1B,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;KAClC;CACF"}
|