了解和测量HTTP时间有助于咱们发现客户端到服务器或服务器到服务器之间的通讯性能瓶颈。 本文介绍了HTTP请求中的时间开销,并展现了如何在Node.js中进行测量。node
在咱们开始了解HTTP时间开销以前,让咱们来看一些基本的概念:git
例如,若是您的DNS查询所花费的时间比预期的要长,那么问题多是您的DNS提供商或DNS缓存设置。github
缓慢的内容传输多是由效率低下的反应机构引发的,例如发回太多的数据(未使用的JSON属性等)或缓慢的链接。缓存
为了测量Node.js中的HTTP时间开销,咱们须要订阅特定的请求,响应和套接字事件。 这是一个简短的代码片断,展现了如何在Node.js中执行此操做,此示例仅关注时序:安全
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) : undefined
TCP链接在主机解析后当即发生:网络
const tcpConnection = getDuration((dnsLookupAt || startAt), tcpConnectionAt)
TLS握手(SSL)只能使用https协议:socket
// There is no TLS handshake without https const tlsHandshake = tlsHandshakeAt !== undefined ? getDuration(tcpConnectionAt, tlsHandshakeAt) : undefined
咱们等待服务器开始发送第一个字节:tcp
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时间。
在Jaeger中使用opentracing-auto的HTTP请求时序。
使用Node.js测量HTTP时间能够帮助您发现性能瓶颈。 Node生态系统提供了很好的工具来从应用程序中提取这些指标。
关注个人公众号,更多优质文章定时推送