节点http-proxy最less连接代理

我想使用节点http代理创build一个“最less连接”代理。 换句话说,它select一个当前具有最less连接的后端。 代理有一个“结束”事件,但它不会传递给你任何信息,所以我不知道如何增加/减less我的每个后端计数器的当前并发请求数。

我想你可以等待已经发送给客户的响应。

例如:

var backends = [ { host : 'backend1', port: 80, active : 0 }, { host : 'backend2', port: 80, active : 0 }, { host : 'backend3', port: 80, active : 0 }, { host : 'backend4', port: 80, active : 0 }, ]; httpProxy.createServer(function (req, res, proxy) { var buffer = httpProxy.buffer(req); // Pick the backend with the least active requests (naive implementation). var backend = backends.sort(function(a, b) { return a.active - b.active; })[0]; // Add a new active request. backend.active++; // Proxy the request. proxy.proxyRequest(req, res, { host : backend.host, port : backend.port, buffer : buffer }); // When the response is finished, decrease the count. res.on('finish', function() { backend.active--; }); }).listen(8000);