前言
了解和测量http时间有助于我们发现客户端到服务器或服务器到服务器之间的通信性能瓶颈。 本文介绍了http请求中的时间开销,并展示了如何在node.js中进行测量。
在我们开始了解http时间开销之前,让我们来看一些基本的概念:
现在我们来看一下通常http请求的时间表:
如何通过http时间开销帮助发现性能瓶颈?
例如,如果您的dns查询所花费的时间比预期的要长,那么问题可能是您的dns提供商或dns缓存设置。
缓慢的内容传输可能是由效率低下的反应机构引起的,例如发回太多的数据(未使用的json属性等)或缓慢的连接。
测量node.js中的http时间开销
为了测量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协议:
// 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时间。
在jaeger中使用opentracing-auto的http请求时序。
总结
使用node.js测量http时间可以帮助您发现性能瓶颈。 node生态系统提供了很好的工具来从应用程序中提取这些指标。
好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。
翻译自understanding & measuring http timings with node.js
如对本文有疑问, 点击进行留言回复!!
offset、client、scroll (width,height、left,top、X,Y)
网友评论