我想计算每个代理请求的响应时间,由 node-http-proxy 完成,如下所示:
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer();
require('http').createServer(function(req, res) {
// start-time for one request
proxy.web(req, res, { target: 'localhost:80' });
}).listen(3000);
proxy.on('proxyRes', function (res) {
// end-time for one request to calculate the time
console.log('RAW Response from the target', JSON.stringify(res.headers, true, 2));
});
所以我想得到开始时间和结束时间之间的时差。我能够捕获 proxyRes
事件,但如何将代理响应与正确的客户端请求相匹配?
更新:我尝试了以下方法:
var httpProxy = require('http-proxy');
var http = require('http');
var proxy = new httpProxy.createProxyServer({
target: {
host: 'localhost',
port: 80
}
});
var start_time = 0;
var proxyServer = http.createServer(function (req, res) {
start_time = new Date().getTime();
proxy.web(req, res);
res.on('finish', function() {
console.log("The request was proxied in " + (new Date().getTime() - start_time) + "ms");
});
});
proxyServer.listen(3000);
// Proxy-Target server
var n = 0; sleep = 0;
http.createServer(function (req, res) {
n++;
var start_time = new Date().getTime();
res.writeHead(200, {'Content-Type': 'text/plain'});
if (n % 2 == 0){
sleep = 2000;
} else {
sleep = 5000;
}
setTimeout(function(){
res.end("...");
}, sleep);
res.on('finish', function(d) {
var diff_time = new Date().getTime() - start_time;
console.log("The request was processed in " + (new Date().getTime() - start_time) + "ms");
});
}).listen(80);
因此,目标服务器的时间被正确测量,导致一个请求可能持续 2 秒或 5 秒,但代理测量的响应时间有时只有几毫秒。
我通过使用 apache-bench 进行了尝试,例如:ab -n 10 -c 3 http://localhost:3000/
和控制台的结果:
The request was processed in 2007ms
The request was proxied in 2017ms
The request was processed in 2003ms
The request was proxied in 2006ms
The request was processed in 5002ms
The request was processed in 5001ms
The request was proxied in 980ms
The request was proxied in 981ms
The request was processed in 2002ms
The request was proxied in 2006ms
The request was processed in 2002ms
The request was proxied in 2005ms
The request was processed in 5000ms
The request was proxied in 8ms
The request was processed in 5000ms
The request was proxied in 982ms
The request was processed in 2001ms
The request was proxied in 2005ms
The request was processed in 5002ms
The request was proxied in 4998ms
最佳答案
现在可以了,在nodejs google-gloup上得到了关键提示,本地没有设置start_time
的地址,所以这里是工作代码:
var httpProxy = require('http-proxy');
var http = require('http');
var proxy = new httpProxy.createProxyServer({});
// before: var start_time = 0;
var proxyServer = http.createServer(function (req, res) {
// now
var start_time = new Date().getTime();
proxy.web(req, res, { target: 'http://localhost:80' });
res.on('finish', function() {
console.log("The request was proxied in " + (new Date().getTime() - start_time) + "ms");
});
});
proxyServer.listen(3000);
关于javascript - 如何获取 node-http-proxy 完成的每个代理请求的响应时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21315637/