javascript node.js asynchronous

javascript - Nodo js socket explicación



node.js asynchronous (2)

Estoy creando una aplicación que realizará aproximadamente un millón de llamadas a un servidor de API remoto. ¿Podré limitar la cantidad de conexiones a, por ejemplo, 10? ¿Si configuro los sockets máximos en 10 lo haré?

Estoy tratando de entender qué hacen estos parámetros:

keepAlive: false, maxSockets: 999, maxFreeSockets: 1

En la función http get del nodo, en el siguiente código:

var inputData = []; for(i=1; i<=5000;i++){ inputData.push(''number'' + i); } var options = { host: "localhost", port: 80, path: "/text.txt", keepAlive: false, maxSockets: 999, maxFreeSockets: 1 } var limit = inputData.length; var counter = 0; function fetchData(number){ return new Promise(function(resolve, reject){ var http = require(''http''); fetch = function(resp){ var body = ''''; resp.on(''data'',function(chunk){ body += chunk; }) resp.on(''end'',function(){ console.log(resp) resolve() }) resp.on(''error'',function(err){ console.log(''error''); }) } var req = http.request(options, fetch); req.end(); }) } Promise.all(inputData.map(number => fetchData(number))).then(function(results) { console.log(''finished''); connection.end(); }) .catch(function(error) { console.log(''there wa an error''); console.log(error); });


Decidí usar la biblioteca asíncrona.

Aquí está mi solución completa para esto:

var async = require(''async'') var http = require(''http''); var inputData = []; for(i=1; i<=2000;i++){ inputData.push(''number'' + i); } var options = { host: "o2.pl", path: "/static/desktop.css?v=0.0.417", port: 80 } function fetchData(number, callback){ return new Promise(function(resolve, reject){ fetch = function(resp){ var body = ''''; resp.on(''data'',function(chunk){ body += chunk; }) process.stdout.write(''.'') callback() resp.on(''error'',function(err){ console.log(''error''); console.log(err); }) } var req = http.request(options, fetch); req.end(); }) } function foo(item, callback){ return callback(false, ''foo''); } async.mapLimit(inputData,100,fetchData,function(err, result){ console.log(''finished''); })

Gracias por tu ayuda.


Realmente no desea disparar 1,000,000 de solicitudes y de alguna manera esperar que maxSockets lo maneje a 100 a la vez. Hay muchas razones por las que esa no es una excelente manera de hacer las cosas. En su lugar, debe usar su propio código que gestiona el número de conexiones en vivo a 100 a la vez.

Hay varias formas de hacerlo:

  1. Escriba su propio código que dispare 100 y luego, cada vez que uno termine, enciende el siguiente.

  2. Use Bluebird''s Promise.map() que tiene una función de concurrencia integrada que administrará cuántos están en vuelo al mismo tiempo.

  3. Use Async''s async.mapLimit() que tiene una función de concurrencia integrada que administrará cuántos están en vuelo al mismo tiempo.

En cuanto a escribir código usted mismo para hacer esto, podría hacer algo como esto;

function fetchAll() { var start = 1; var end = 1000000; var concurrentMax = 100; var concurrentCnt = 0; var cntr = start; return new Promise(function(resolve, reject) { // start up requests until the max concurrent requests are going function run() { while (cntr < end && concurrentCnt < concurrentMax) { ++concurrentCnt; fetchData(cntr++).then(function() { --concurrentCnt; run(); }, function(err) { --concurrentCnt; // decide what to do with error here // to continue processing more requests, call run() here // to stop processing more requests, call reject(err) here }); } if (cntr >= end && concurrentCnt === 0) { // all requests are done here resolve(); } } run(); }); }