我有一个 Node net.Server
,它在 TCP 套接字上监听遗留系统。收到消息后,它会向另一个 http 服务器发送 http 请求。简化后,它看起来像这样:
var request = require('request-promise');
...
socket.on('readable', function () {
var msg = parse(socket.read());
var postOptions = {
uri: 'http://example.com/go',
method: 'POST',
json: msg,
headers: {
'Content-Type': 'application/json'
}
};
request(postOptions);
})
问题是套接字每秒可读大约 1000 次。然后请求使 http 服务器过载。几乎立即,我们得到了多秒的响应时间。
在运行 Apache 基准测试时,很明显,如果我们将并发请求数限制在 100 左右,http 服务器每秒可以处理超过 1000 个请求,响应时间不到 100 毫秒。
所以我的问题是,使用 request-promise
(通过扩展、request
和 core. http.request
) 库在事件回调中分别触发每个请求时?
请求的documentation说:
Note that if you are sending multiple requests in a loop and creating multiple new pool objects,
maxSockets
will not work as intended. To work around this, either use request.defaults with your pool options or create the pool object with themaxSockets
property outside of the loop.
我很确定这一段告诉了我问题的答案,但我无法理解它。我使用默认设置来限制打开的套接字数量:
var rp = require('request-promise');
var request = rp.defaults({pool: {maxSockets: 50}});
这没用。我目前唯一的想法是手动管理队列,但我希望如果我只知道传统的方法来做这件事,那将是不必要的。
最佳答案
嗯,你需要限制你的请求吗?我有两种解决方法,但让我向您展示我一直使用的一种模式。我经常使用 throttle-exec
和 Promise
为 request
制作包装器。您可以使用 npm install throttle-exec
安装它,并在 native 或第三方使用 Promise。这是我对这个包装器的要点 https://gist.github.com/ans-4175/d7faec67dc6374803bbc
如何使用它?很简单,跟普通请求一样。
var Request = require("./Request")
Request({
url:url_endpoint,
json:param,
method:'POST'
})
.then(function(result){
console.log(result)
})
.catch(reject)
实现后告诉我。无论哪种方式,我都有另一个包装器:)
关于node.js - 限制事件驱动的 Nodejs HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31190437/