- 监控请求响应时间
- 原理:在接收到请求时记录开始时间,在发送响应前记录结束时间,两者差值即为响应时间。
- 关键代码示例:
const http = require('http');
const server = http.createServer((req, res) => {
const startTime = Date.now();
// 处理请求逻辑
//...
res.on('finish', () => {
const endTime = Date.now();
const responseTime = endTime - startTime;
console.log(`Request response time: ${responseTime} ms`);
});
res.end('Hello World');
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
- 监控吞吐量
- 原理:记录一段时间内接收和发送的数据量,然后通过计算得到吞吐量(数据量 / 时间)。可以使用定时器定期计算。
- 关键代码示例:
const http = require('http');
let totalReceivedBytes = 0;
let totalSentBytes = 0;
const interval = 1000; // 1 秒
setInterval(() => {
const throughputReceived = totalReceivedBytes / interval * 1000; // 每秒接收的字节数
const throughputSent = totalSentBytes / interval * 1000; // 每秒发送的字节数
console.log(`Throughput (Received): ${throughputReceived} bytes/s`);
console.log(`Throughput (Sent): ${throughputSent} bytes/s`);
totalReceivedBytes = 0;
totalSentBytes = 0;
}, interval);
const server = http.createServer((req, res) => {
req.on('data', (chunk) => {
totalReceivedBytes += chunk.length;
});
res.on('drain', () => {
totalSentBytes += res.writableLength;
});
res.end('Hello World');
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});