This commit is contained in:
Ivan
2021-03-05 18:12:34 +08:00
parent 7913184174
commit 8901c49bb3
2 changed files with 53 additions and 24 deletions

View File

@ -29,33 +29,41 @@ export class PipelineTasksService {
const task = await this.repository.save(this.repository.create(dto));
task.pipeline = pipeline;
const [lckKey, tasksKey] = this.getRedisTokens(pipeline);
const tasksKey = this.getRedisTokens(pipeline)[1];
const redis = this.redis.getClient();
await redis.lpush(tasksKey, JSON.stringify(task)).finally(() => {
return redis.decr(lckKey);
});
await redis.lpush(tasksKey, JSON.stringify(task));
await this.doNextTask(pipeline);
}
async doNextTask(pipeline: Pipeline) {
const [lckKey, tasksKey] = this.getRedisTokens(pipeline);
const redis = this.redis.getClient();
await redis.set(lckKey, 0, 'EX', 10, 'NX');
await new Promise(async (resolve, reject) => {
for (let i = 0; i < 5; i++) {
if ((await redis.incr(lckKey)) === 1) {
resolve(undefined);
return;
const unLck = await new Promise<() => Promise<void>>(
async (resolve, reject) => {
const lckValue = Date.now().toString();
for (let i = 0; i < 5; i++) {
if (
await redis
.set(lckKey, 0, 'EX', lckValue, 'NX')
.then(() => true)
.catch(() => false)
) {
resolve(async () => {
if ((await redis.get(lckKey)) === lckValue) {
await redis.del(lckKey);
}
});
return;
}
await new Promise((resolve) => setTimeout(resolve, 2000));
}
await redis.decr(lckKey);
await new Promise((resolve) => setTimeout(resolve, 2000));
}
reject(new LockFailedException(lckKey));
});
reject(new LockFailedException(lckKey));
},
);
const task = JSON.parse(
(await redis.rpop(tasksKey).finally(() => redis.decr(lckKey))) ?? 'null',
(await redis.rpop(tasksKey).finally(() => unLck())) ?? 'null',
);
if (task) {
await this.queue.add(task);