gpt4 book ai didi

node.js - 如果 800k 记录需要 50 秒,随着服务器变得理想,队列中的所有 http 待处理请求将阻塞 50 秒

转载 作者:可可西里 更新时间:2023-11-01 10:42:44 25 4
gpt4 key购买 nike

如果 800k 记录需要 50 秒,则队列中的所有 http 待处理请求将阻塞 50 秒,因为服务器变得理想。

var http = require("http");
var url = require("url");
var MongoClient = require('mongodb').MongoClient

http.createServer(function(request, response) {

if (url.parse(request.url).pathname == '/search'){

var collection = db.collection('documents');
// suppose it takes 800k record in 40 secs all request would be block until response end
collection.find({}).toArray(function(err, docs) {

console.log("Found the following records");
console.dir(docs);

response.writeHead(200, {"Content-Type": "text/plain"});
response.write(JSON.stringify(docs));
response.end();
});
}
else
{
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(0 + '');
response.end();
}
}).listen(8888);

最佳答案

MongoDB 的原生 nodejs 驱动 supports streaming .它提供了一个可读的流,您可以将其通过管道传递给响应。 (可选)编写转换流以动态转换文档。

 collection.find({}).stream().pipe(myTransform).pipe(response);

这种方法不会等待将所有文档加载到内存中(toArray()),然后再加载它(JSON.stringify())。它将继续将数据从 mongdb 转发到响应,并进行一些缓冲。

关于node.js - 如果 800k 记录需要 50 秒,随着服务器变得理想,队列中的所有 http 待处理请求将阻塞 50 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33863905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com