简体   繁体   English

节点http.createServer如何缓冲传入的请求

[英]Node http.createServer how to buffer incoming requests

I'm building a small node server that generates PDF files (using Nightmare.js). 我正在构建一个生成PDF文件的小型节点服务器(使用Nightmare.js)。 Each request calls createPage to generate one pdf. 每个请求都调用createPage生成一个pdf。

The incoming request tend to all come around the same time, overloading the PC this is running on. 传入请求趋向于全部同时出现,从而使正在运行的PC过载。

I need to buffer the incoming requests to delay execution of some requests till some of the current requests have completed. 我需要缓冲传入的请求,以延迟某些请求的执行,直到某些当前请求完成为止。 How do I do this? 我该怎么做呢?

function createPage(o, final) {
    //generate pdf files
}

http.createServer(function (request, response) {
    var body = [];
    request.on('data', function (chunk) { 
        body.push(chunk);
    }).on('end', function () {
        body = Buffer.concat(body).toString();
        var json = JSON.parse(body);

        createPage(json, function (status) {
            if (status === true) {
                response.writeHead(200, { 'Content-Length': 0 });
                console.log('status good');
            } else {
                response.writeHead(500, { 'Content-Type': 'text/html' });
                response.write(' ' + status);
            }
            response.end('\nEnd of Request \n');
       });
   });
}).listen(8007);

If I understand correctly, you want to continually accept http requests but throttle the rate at which createPage is invoked. 如果我理解正确,则希望继续接受http请求,但要限制createPage的调用速度。 If so, you probably need to consider a slightly different design. 如果是这样,您可能需要考虑稍微不同的设计。 In this current design, every next client will have to wait longer than the previous one to find out if their request has succeeded or failed. 在当前的设计中,每个下一个客户端将不得不比上一个客户端等待更长的时间,以查明他们的请求是成功还是失败。

Approach 1: use a queue (rabbitmq, aws sqs, zeromq, kafka, etc). 方法1:使用队列(rabbitmq,aws sqs,zeromq,kafka等)。 Here's the basic workflow: 这是基本的工作流程:

  1. receive the request 收到请求
  2. generate a unique id 产生一个唯一的ID
  3. put a message on the queue that includes the data and the unique id 将包含数据和唯一ID的消息放入队列
  4. return the unique id to the client 返回唯一的ID给客户端
  5. the client periodically checks for the completion of the task using the unique id 客户端使用唯一ID定期检查任务是否完成

Approach 2: Use a queue with message duplexing. 方法2:使用带有消息双工的队列。

  1. receive the request 收到请求
  2. generate a correlation id and relate it to the http transaction 生成相关ID并将其与http事务相关
  3. send message on queue to worker with correlation id 将队列中的消息发送给具有相关ID的工作人员
  4. when worker completes, it sends the response back with the correlation id 当工作人员完成时,它将响应和相关ID发送回去
  5. server uses correlation id to find the http transaction and send the appropriate response to the client 服务器使用相关性ID查找http事务,并将适当的响应发送给客户端

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

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