const timings = {
// use process.hrtime() as it's not a subject of clock drift
startAt: process.hrtime(),
dnsLookupAt: undefined,
tcpConnectionAt: undefined,
tlsHandshakeAt: undefined,
firstByteAt: undefined,
endAt: undefined
} const req = http.request({ ... }, (res) => {
res.once('readable', () => {
timings.firstByteAt = process.hrtime()
})
res.on('data', (chunk) => { responseBody += chunk })
res.on('end', () => {
timings.endAt = process.hrtime()
})
})
req.on('socket', (socket) => {
socket.on('lookup', () => {
timings.dnsLookupAt = process.hrtime()
})
socket.on('connect', () => {
timings.tcpConnectionAt = process.hrtime()
})
socket.on('secureConnect', () => {
timings.tlsHandshakeAt = process.hrtime()
})
})
DNS查找只会发生在有域名的时候:
/ There is no DNS lookup with IP address
const dnsLookup = dnsLookupAt !== undefined ?
getDuration(startAt, dnsLookupAt) : undefinedTCP连接在主机解析后立即发生:
const tcpConnection = getDuration((dnsLookupAt || startAt), tcpConnectionAt)TLS握手(SSL)只能使用https协议:
// There is no TLS handshake without https
const tlsHandshake = tlsHandshakeAt !== undefined ?
getDuration(tcpConnectionAt, tlsHandshakeAt) : undefined我们等待服务器开始发送第一个字节:
const firstByte = getDuration((tlsHandshakeAt || tcpConnectionAt), firstByteAt)总持续时间从开始和结束日期计算:
const total = getDuration(startAt, endAt)看到整个例子,看看我们的https://github.com/RisingStac…仓库。
测量时间的工具
现在我们知道如何使用Node测量HTTP时间,我们来讨论可用于了解HTTP请求的现有工具。
request module著名的request module具有测量HTTP定时的内置方法。 您可以使用time属性启用它。
const request = require('request')request({
uri: 'https://risingstack.com',
method: 'GET',
time: true
}, (err, resp) => {
console.log(err || resp.timings)
})
分布式跟踪
可以使用分布式跟踪工具收集HTTP定时,并在时间轴上可视化它们。 这样,您可以全面了解后台发生的情况,以及构建分布式系统的实际成本是多少。
RisingStack的opentracing-auto库具有内置的标志,可通过OpenTracing收集所有HTTP时间。









