简体   繁体   中英

How to set maximum http client connections in Node.js

I need to increase the number of outbound http sockets usable by a module I am writing. I know it is possible to do this globally using:

// increase max sockets
http.globalAgent.maxSockets = 1000;

What is the best pattern for authoring a module's maxSocket limit without affecting other modules?

Your best option is to pass an Agent object to every http and https request you are making, with maxSockets configured to your liking. This will have no effect on other modules. See http://nodejs.org/docs/latest/api/http.html#http_http_request_options_callback .

If you are using a framework yourself, rather than relying on the http module directly, it might be difficult and require some patching.

Given that the setting determines how many concurrent connections are available per host, there is no way to set this specifically for individual modules. What you should do however is make sure that you're not reducing the number of concurrent connections from what the user has already specified. For example, if someone sets their maxSockets to 5000, and you set it to 1000 in your module, bad things could happen. I would recommend something like the following

var max = 1000;
if(http.globalAgent.maxSockets < max) {
    http.globalAgent.maxSockets = max;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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