如何在NodeJS中锁定(Mutex)? [英] How to lock (Mutex) in NodeJS?

查看:1426
本文介绍了如何在NodeJS中锁定(Mutex)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些外部资源(通过API访问可用清单)只能一次访问一个线程.

There are external resources (accessing available inventories through an API) that can only be accessed one thread at a time.

我的问题是:

  1. NodeJS服务器可同时处理请求,我们可能同时有多个请求试图保留库存.
  2. 如果我同时点击库存API,那么它将返回重复的可用库存
  3. 因此,我需要确保我一次点击了清单API.
  4. 我无法更改清单API(旧版),因此,我必须找到一种同步Node.js服务器的方法.

注意:

  • 只有一台nodejs服务器正在运行一个进程,因此我只需要在该服务器内同步请求即可.
  • 运行在express.js上的低流量服务器

推荐答案

我会使用 async 模块的队列,并将其concurrency参数设置为1.这样,您可以根据需要将尽可能多的任务放入队列中,但它们一次只能运行一个.

I'd use something like the async module's queue and set its concurrency parameter to 1. That way, you can put as many tasks in the queue as you need to run, but they'll only run one at a time.

队列看起来像:

var inventoryQueue = async.queue(function(task, callback) {
    // use the values in "task" to call your inventory API here
    // pass your results to "callback" when you're done
}, 1);

然后,要发出清单API请求,您将执行以下操作:

Then, to make an inventory API request, you'd do something like:

var inventoryRequestData = { /* data you need to make your request; product id, etc. */ };
inventoryQueue.push(inventoryRequestData, function(err, results) {
    // this will be called with your results
});

这篇关于如何在NodeJS中锁定(Mutex)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆