使用 Lambda 和互斥锁(Mutex)解决此问题,具体实现代码如下:
var mutex = new Mutex();
exports.handler = async function(event, context) {
// 尝试锁定互斥锁
if (!mutex.tryLock()) {
console.log('Another execution is already processing the queue.');
return;
}
try {
// 处理队列消息
await processSQSMessages();
} finally {
// 释放互斥锁
mutex.unlock();
}
};
class Mutex {
constructor() {
this.locked = false;
this.waiting = [];
}
tryLock() {
if (!this.locked) {
this.locked = true;
return true;
}
return false;
}
async lock() {
// 添加等待锁的进程
this.waiting.push(new Promise(resolve => resolve()));
// 等待许可
await this.waiting[this.waiting.length - 1];
}
unlock() {
// 解除锁
this.locked = false;
if (this.waiting.length > 0) {
// 来自等待列表的进程许可
const nextResolve = this.waiting.shift();
nextResolve();
}
}
}