简体   繁体   English

如何使用node js维护http请求的顺序?

[英]how to maintain the order of http requests using node js?

I have a bunch of data that I want to send to a server through http.我有一堆数据要通过 http 发送到服务器。 However in the server side I need to process the data in the same order as they were sent(eg if the order of sending is elem1, elem2 and elem3, I would like to process elem1 first, then elem2 and then elem3).但是在服务器端,我需要按照发送的顺序处理数据(例如,如果发送的顺序是 elem1、elem2 和 elem3,我想先处理 elem1,然后是 elem2,然后是 elem3)。 Since in http, there is no grantee that the order will be maintained I need some way to maintain the order.由于在 http 中,没有被授予者可以维护订单,因此我需要某种方式来维护订单。 Currently I am keeping the data in a queue and I send one element and await for the response.目前,我将数据保存在队列中,然后发送一个元素并等待响应。 Once the response reaches me I send the next element.一旦响应到达我,我发送下一个元素。

while (!queue.isEmpty()) {
    let data = queue.dequeue();
    await sendDataToServer(data);
    }

I am not very sure if this will actually work in a production environment and what will be the impact on the performance.我不太确定这是否真的能在生产环境中工作,以及对性能有什么影响。 Any sort of help is much appreciated.任何形式的帮助都非常感谢。 Thank you谢谢

Sorry, I don't have enough reputation to comment, thus I am posting this as an answer.抱歉,我没有足够的声誉发表评论,因此我将其发布为答案。

Firstly, your code will work as intended.首先,您的代码将按预期工作。

However, since the server has to receive them in order, the performance won't be good.但是,由于服务器必须按顺序接收它们,因此性能不会很好。 If you can change the server, I suggest you implement it like this:如果您可以更改服务器,我建议您像这样实现它:

  • Add an ID to each data item.为每个数据项添加一个 ID。
  • Send all the data items, no need to ensure order.发送所有数据项,无需保证顺序。
  • Create a buffer on the server, the buffer will be able to contain all the data items.在服务器上创建一个缓冲区,这个缓冲区就能包含所有的数据项。
  • The server receives the items and puts them into the buffer in the right position.服务器接收项目并将它们放入缓冲区的正确位置。

Example code:示例代码:

Client (see Promise.all )客户端(参见Promise.all

let i = 0;
let promises = [];
await sendDataLengthToServer(queue.length());
while (!queue.isEmpty()) {
    let data = queue.dequeue();
    data.id = i;
    // no need to wait for a request to finish
    promises.push(sendDataToServer(data));
}
await Promise.all(promises);

Server (pseudo-code)服务器(伪代码)

length = receiveDataLengthFromClient()
buffer = new Array(length)

int received = 0
onDataReceivedFromClient(data, {
    received = received + 1
    buffer[data.id] = data
    if (received == length) {
        // the buffer contains the data in the right order
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM