如何在nodejs中处理对API的并发访问

时间:2017-09-13 09:23:53

标签: node.js mongodb socket.io

我目前正面临一个问题。如果我错了,请纠正我。在我的项目中,我有一个拥有mongoDB数据库的NodeJS服务器。连接到它的Android应用程序。

有4个安卓设备连接到它,当服务器发布列表时,它通过Socket.IO向所有Android设备发送一个emit调用。 android收到emit调用的那一刻,它调用API来获取已发布的列表。这里请求调用(4个请求)同时到达服务器。

这就是设备发生意外分配的原因。在某种意义上意外的是,有一些参数应根据这些参数对设备进行分配。当只有一个设备在线时,这种情况可以很好地工作,但是当并发请求从多个设备到达时,有时会出现相关问题。

是否可以一次处理一个并发请求?

欢迎讨论/建议。 执行流程在这里

        flowController.on('START', function () {
      // Uploading and storing the binary data as excel file 
    });

    flowController.on('1', function () {
      // Validation to check if file contain required sheet with name and all and convert the file into JSON format
    });

    flowController.on('2', function () {
      // Replacing the keys from the JSON to match the required keys 
    });

    flowController.on('3', function () {
      // Massive validation of records & seperating the records as per the activity
    });

    // Activity 1  
    flowController.on('4', function () {
      // Insert records of Activity 1  
    });

    // Activity 2  
    flowController.on('5', function () {
      // Insert records of Activity 2
    });

    // Activity 3  
    flowController.on('6', function () {
      // Insert records of Activity 3
    });

    // Activity 3  
    flowController.on('END', function () {
      // End
    });

1 个答案:

答案 0 :(得分:1)

如果您想一次处理一个请求,可以实现一个队列。

const queue = [];
const processingQueue = false;

socketServer.on('connection', (connection) => {

  connection.on('SOME_EVENT', (data, callback) => {
    queue.push({data: data, callback: callback});
  });

});

function processQueue() {
    async.whilst(() => queue.length, (callback) => {
        var request = queue.shift()
        // process request
        callback();
    },
    (err, n) => {
        setTimeout(processQueue, 1);
    });
}
processQueue();

但是,如果你共享一些代码,可能会有更好的解决方案来解决这个问题。

相关问题