没有办法限制节点并发数吗?

问题描述 投票:0回答:1

我一直在寻找一种方法来做到这一点:

代替:

await myfunc()

我想要:

limiter = Limiter(50)
await limiter(myfunc)

如果我的函数调用有 50 个待处理,限制器不会将我的函数添加到事件队列,而是会阻塞(让给其他调用者)

通过这种方式,系统会在繁忙时优雅地降级,将资源问题传播给客户端。

我研究过使用信号量和互斥体,但它们不存在,并且它们的库也有同样的问题(无限的承诺......每个等待信号量的调用者都会创建一个稍后发生的新承诺)。

这是我可怕的解决方案:

class ConcurrencyControl {
    constructor(maxConcurrent) {
        this.maxConcurrent = maxConcurrent;
        this.currentCount = 0;
    }

    async acquire() {
        while (this.currentCount >= this.maxConcurrent) {
            await new Promise(resolve => setTimeout(resolve, 10));
        }
        this.currentCount++;
    }

    release() {
        this.currentCount--;
    }

    run(promiseFunction) {
        this.acquire().then(() => {
            promiseFunction().then(() => {
                this.release();
            }, () => {
                this.release();
            });
        });
        return;
    }
}
node.js concurrency queue semaphore
1个回答
0
投票

您可能正在寻找称为漏桶的速率限制策略

这里有一个简洁的 npm 包,它实现了这个技巧

github

const bucket = new Bucket({
    capacity: 60,
});

await Promise.all(items.map(async(item) => {
    await bucket.throttle();
    myfunc(item);
}));
© www.soinside.com 2019 - 2024. All rights reserved.