IT类翻译 -- HTTP/2正给Web性能最佳实践带来怎样的影响?

# How HTTP/2 Is Changing Web Performance Best Practices

# HTTP/2正给Web性能最佳实践带来怎样的影响?

原文地址:https://dzone.com/articles/how-http2-is-changing-web-performance-best-practic

HTTP/2 debuted in May 2015, and since its inception, it'sbeen influencing web performance best practices. Here's a look at binaryframes, latency reduction, and possible cons of HTTP/2.

HTTP/2于2015年5月正式推出。自诞生以来,它就一直在影响着网络性能最佳实践。在本篇博文中,我们将讨论HTTP/2的二进制帧、延迟削减以及潜在利弊。

Clay Smith

2016年02月09日

The Hypertext Transfer Protocol (HTTP) underpins the WorldWide Web and cyberspace. If that sounds dated, consider that the version of theprotocol most commonly in use, HTTP 1.1, is nearly 20 years old. When it was[ratified back in 1997](https://www.ietf.org/rfc/rfc2068.txt) , floppy drivesand modems were must-have digital accessories and Java was a new, up-and-comingprogramming language. Ratified in May 2015, HTTP/2 was created to address somesignificant performance problems with HTTP 1.1 in the modern Web era. Adoptionof HTTP/2 has increased in the past year as browsers, Web servers, commercialproxies, and major content delivery networks have committed to or releasedsupport.

超文本传输协议(简称HTTP)正是万维网与网络空间创建的基石。尽管HTTP听起来已经有些过时,毕竟该协议中使用最广泛的版本--HTTP1.1,现如今已快迎来它的第二十个年头。[时光回溯到1997年,HTTP1.1刚刚出现的年代](https://www.ietf.org/rfc/rfc2068.txt),当时,软驱与调制解调器还是PC设备的必备周边产品,Java也仅仅是一个刚刚崭露头角的、前途一片光明的编程语言。而今,2015年5月,HTTP/2正式亮相,致力于解决HTTP1.1在现代网络时代下无法应对的某些重大性能难题。过去一年以来,越来越多的浏览器、Web服务器、商用代理以及主要内容交付网络开始支持HTTP/2。

Unfortunately for people who write code for the Web, transitioningto HTTP/2 isn’t always straightforward and a speed boost isn’t automaticallyguaranteed. The new protocol challenges some common wisdom when buildingperformant Web applications and many existing tools—such as debuggingproxies—don’t support it yet. This post is an introduction to HTTP/2 and how itchanges Web performance best practices.

遗憾的是,对于负责编写Web代码的开发人员而言,HTTP/2的过渡工作并不简单,所谓的速度的提升也不会自行出现。如何才能采用这个新型协议打造高性能Web应用,该怎样处理那些尚不支持该协议的现有工具——例如debug代理工具,这些问题对所有人来说仍是一个挑战。今天的博文将向您介绍HTTP/2,以及其如何改变Web性能的最佳实践。

#Binary frames: The ‘fundamental unit’ of HTTP/2

#二进制帧:HTTP/2的“基本单位”

One benefit of HTTP 1.1 (over non-secure connections, atleast) is that it supports interaction with Web servers using text in a telnetsession on port 80: typing GET / HTTP/1.1 returns an HTML document on most Webservers. Because it’s a text protocol, debugging is relatively straightforward.

HTTP 1.1的一大优势(至少相较于非安全连接而言)在于其支持在端口80的telnet会话中利用文本与Web服务器进行交互:在大多数Web服务器上输入GET/ HTTP/1.1,都能返回一个HTML文档。由于这是一项文本协议,因此其debug工作相对简单。

Instead of text, requests and responses in HTTP/2 arerepresented by a stream of binary frames, described as a “basic protocol unit”in the [HTTP/2 RFC](https://tools.ietf.org/html/rfc7540). Each frame has a typethat serves a different purpose. The authors of HTTP/2 realized that HTTP 1.1will exist indefinitely (the [Gopherprotocol](https://en.wikipedia.org/wiki/Gopher_%28protocol%29) still is outthere, after all). The binary frames of an HTTP/2 request map to an HTTP 1.1request to ensure backwards compatibility.

相对于HTTP1.1这个文本协议,HTTP/2中的请求与响应则通过二进制帧流的形式来表现,我们将其称为[HTTP/2RFC](https://tools.ietf.org/html/rfc7540)中的“基本协议单位”。每一帧都拥有自己的类型,用于实现不同的作用。考虑到HTTP1.1将会“永远”存在(毕竟[Gopher协议](https://en.wikipedia.org/wiki/Gopher_%28protocol%29)都还在用呢!),因此HTTP/2的作者们要求,HTTP/2请求的二进制帧都必须被映射到HTTP1.1请求上去,从而确保其向下兼容的能力。

There are some new features in HTTP/2 that don’t map to HTTP1.1, however. Server push (also known as “cache push”) and stream reset arefeatures that correspond to types of binary frames. Frames can also have apriority that allows clients to give servers hints about the priority of someassets over others.

当然,HTTP/2当中也有一些其他新特性,无法映射至HTTP 1.1。例如,服务器推送(也叫“缓存推送”)和流重置都是利用二进制帧类型实现的新特性。帧可以具备一个优先级排序,通过客户端可以向服务器发送排序,从而优先处理一部分资产类别。

Other than using [Wireshark 2.0](https://www.wireshark.org/),one of the easiest ways to actually see the individual binary frames is byusing the net-internals tab of Google Chrome (typechrome://net-internals/#http2 into the address bar). The data can be hard tounderstand for large Web pages. [Rebecca Murphey](https://github.com/rmurphey)helpfully wrote [a useful tool for displaying itvisually](https://github.com/rmurphey/chrome-http2-log-parser) in the commandline.

除了使用[Wireshark 2.0](https://www.wireshark.org/)之外,对个别二进制帧进行实际查看的最为简便的方法之一就是利用谷歌Chrome浏览器的net-internals标签(在浏览器地址栏中输入chrome://net-internals/#http2)。由于理解大型网页的数据通常比较困难,[RebeccaMurphey](https://github.com/rmurphey)特意编写了[一款极为实用的可视化工具](https://github.com/rmurphey/chrome-http2-log-parser),从而将其显示在命令行中。

Additionally, the protocol used to fetch assets can bedisplayed in the Chrome Web developer tools—right click on the column headerand select “Protocol”:

除此之外,这个用于获取资产的协议还能够显示在Chrome Web的开发者工具当中--只需右键点击列标题,接着选择“协议”即可:

![enter image descriptionhere](http://newtest.cnw.cn/resources/2016_02/2016_02_17/20160217140912_2285.jpg)

*Viewing protocol types in Google Chrome developer tools.*

*在谷歌Chrome开发者工具当中查看协议类型。*

All of the HTTP/2 requests in this listing use a secureconnection over Transport Layer Security (TLS). All major browsers requireHTTP/2 connections to be secure. This is done for a practical reason: anextension of TLS called Application-Layer Protocol Negotiation (ALPN) letsservers know the browser supports HTTP/2 (among other protocols) and avoids anadditional round-trip. This also helps services that don’t understand HTTP/2,such as proxies—they see only encrypted data over the wire.

这里列出的所有HTTP/2请求都使用通过传输层安全(TLS)建立的安全连接。各主流浏览器都要求HTTP/2连接是安全的。这样做是有切实理由的:TLS的一套称为应用层协议协商(ALPN)的扩展,让服务器知道浏览器支持HTTP2(在各种其他协议中),从而避免了额外的数据往来。这也能保住那些无法解读HTTP/2的服务,例如代理——只看得见传输线路上的加密数据。

#Reducing latency with multiplexing

#多路复用减少延迟

A key performance problem with HTTP 1.1 is latency, or thetime it takes to make a request and receive a response. This issue has becomemore pronounced as the number of images and amount of JavaScript and CSS on atypical Web page continue to [increase](http://httparchive.org/trends.php) .Every time an asset is fetched, a new TCP connection is generally needed. Thisrequirement is important for two reasons: the number of simultaneous open TCPconnections per host is limited by browsers and there’s a performance penaltyincurred when establishing new connections. If a physical Web server is faraway from users (for example, a user in Singapore requesting a page hosted at adata center on the U.S. East Coast), latency also increases. This scenario isnot uncommon— [one recentreport](http://www.nextgov.com/big-data/2016/01/70-percent-global-internet-traffic-goes-through-northern-virginia/124976/)says that more than 70% of global Internet traffic passes through the unmarkeddata centers of Northern Virginia.

HTTP 1.1的一大问题是延迟,换而言之就是它花在提出请求和接受响应上的时间。随着典型网页中图片数量、JavaScrip和CSS的使用量不断[增加](http://httparchive.org/trends.php),这个问题日益严重。每获取一项资产,通常都得新建一个TCP连接。这种需求因为两个理由很重要:每台主机能同时打开的TCP连接数受浏览器的限制;新建连接都会引发性能损失。如果物理服务器里用户很远(如:一位新加坡用户向美国东海岸数据中心请求一个页面),延迟会变多。这不是罕见的情况——[近期一份报告](http://www.nextgov.com/big-data/2016/01/70-percent-global-internet-traffic-goes-through-northern-virginia/124976/)表示全球70%以上的互联网流通都会通过北佛吉尼亚一些不知名的数据中心。

HTTP 1.1 offers different workarounds for latency issues,including pipelining and the Keep-Alive header. However, pipelining was neverwidely implemented and the Keep-Alive header suffered from head-of-lineblocking: the current request must complete before the next one can be sent.

HTTP 1.1提供了多种方案以解决延迟问题,包括通道传输与Keep-Alive协议头。然而,通道传输从未被广泛采纳过,而Keep-Alive协议头则饱受线头阻塞的困扰:只有在当前请求必须彻底完成后,下一请求才能被发送出去。

In HTTP/2, multiple asset requests can reuse a single TCPconnection. Unlike HTTP 1.1 requests that use the Keep-Alive header, therequests and response binary frames in HTTP/2 are interleaved and head-of-lineblocking does not happen. The cost of establishing a connection (the well-known“three-way handshake”) has to happen only once per host. Multiplexing isespecially beneficial for secure connections because of the performance costinvolved with multiple TLS negotiations.

在HTTP/2当中,多条资产请求可以重复利用单一TCP连接。与使用Keep-Alive协议头的HTTP1.1请求不同,HTTP/2的请求与响应二进制帧以交错方式进行,线头阻塞问题也不复存在。建立连接的成本(即著名的的‘三方握手’)在每台主机上只进行一次。多路复用对于安全连接来说尤为重要,因为多次TLS协商方案的性能成本将会得到显著提高。

![enter image descriptionhere](https://blog.newrelic.com/wp-content/uploads/TCP-connection.jpg)

*Requests for multiple assets on a single host use a singleTCP connection in HTTP/2.*

*在HTTP/2中,单一主机内的多资产请求只使用单一TCP连接。*

#Implications for Web Performance: Goodbye Inlining,Concatenation, and Image Sprites?

#Web性能影响:与内联、级联及图像精灵说再见?

HTTP/2 multiplexing has broad implications for frontend Webdevelopers. It removes the need for several long-standing workarounds that aimto reduce the number of connections by bundling related assets, including:

HTTP/2多路复用对前端Web开发人员造成了深远的影响。长久以来,人们用尽方法,试图通过捆绑相关资产来削减连接的数量,而现在这一切都不需要了。人们尝试过的方法包括:

- **ConcatenatingJavaScript and CSS files:** Combining smaller files into

a larger file toreduce the total number of requests.

- **Image spriting:**Combining multiple small images into one larger image.

- **Domainsharding:** Spreading requests for static assets across several domains toincrease the total number of open TCP connections allowed by the browser.

- **Inliningassets:** Bundling assets with the HTML document

source, includingbase-64 encoding images or writing JavaScript code

directly insidescript tags.

- **JavaScript与CSS文件级联:**将多个小文件合成一个大文件,从而降低总体请求数量。

- **图像精灵:**将多个小图像合成一张大图像。

- **域名碎片:**在多个域之间发送静态资产请求,从而增加浏览器所能允许的总体开放TCP连接数量。

- **内联资产:**将资产同HTML文档源绑定,包括base-64编码图片,以及直接写入script标签的JavaScript代码。

With unbundled assets, there is greater opportunity toaggressively cache smaller pieces of a Web application. It’s easiest to explainthis with an example:

因为不需要再绑定资产,我们就有了更多机会,将Web应用程序中的小片段加以缓存。举个例子可以帮我们更好的理解这一点:

![enter image descriptionhere](https://blog.newrelic.com/wp-content/uploads/css-graphic.jpg)

*A concatenated and fingerprinted CSS file unbundles intofour smaller fingerprinted files.*

*一个级联且指纹验证型CSS文件被解绑为四个较小的指纹验证文件。*

A common concatenation pattern has been to bundle stylesheetfiles for different pages in an application into a single CSS file to reducethe number of asset requests. This large file is then fingerprinted with an MD5hash of its contents in the filename so it can be aggressively cached bybrowsers. Unfortunately, this approach means that a very small change to thevisual layout of the site, like changing the font style for a header, requiresthe entire concatenated file to be downloaded again.

常见的级联模式是将样式表文件进行绑定,将单一应用程序内的不同页面合到一个单一的CSS文件之内,以减少资产请求的数量。这个大文件随后会通过文件名内的MD5哈希值进行指纹校验,确保其能够被浏览器主动缓存。遗憾的是,这样的解决方案意味着,当站点的可视化布局中出现了任何一点小的改变,如标题字体的改变,都需要重新下载整个级联文件。

When smaller asset files are fingerprinted, significantamounts of JavaScript and CSS components that don’t change frequently can becached by browsers—a small refactor of a single function no longer invalidatesa massive amount of JavaScript application code or CSS.

当对小型资产文件进行指纹校验时,相当一部分的JavaScript与CSS组件都不会频繁产生变动,因此可以被浏览器缓存--也就是说,任何一个单一功能的小型重构,不会再导致大量的JavaScript应用程序代码或者CSS失效。

Lastly, deprecating concatenation can reduce frontend buildinfrastructure complexity. Instead of having several pre-build steps thatconcatenate assets, they can be included directly in the HTML document assmaller files.

最后,级联机制的消失能够降低前端构建基础的复杂性。与以往通过一些列预置步骤来级联资产不同,现在它们作为小型文件,可以直接被放入HTML文档中。

#Potential Downsides of Using HTTP/2 in the Real World

#真实使用HTTP/2的潜在弊端

Optimizing only for HTTP/2 clients potentially penalizesbrowsers that don’t yet support it. Older browsers still prefer bundled assetsto reduce the number of connections. As of February 2016,[caniuse.com](http://caniuse.com/) reports [global browser support of HTTP/2 at71%](http://caniuse.com/#feat=http2). Much like dropping Internet Explorer 8.0support, the decision to adopt HTTP/2 or go with a hybrid approach must be madeusing relevant data on a per-site basis.

仅仅针对支持HTTP/2客户端而做出的各类优化,意味那些不支持HTTP/2的浏览器可能因此陷入不利境地。那些“有年头”的浏览器们仍然倾向于绑定资产,以此降低连接数量。截至2016年2月,[caniuse.com](http://caniuse.com/)网站报道称,[全球浏览器中能够支持HTTP/2的占比71%](http://caniuse.com/#feat=http2)。与浏览器们曾经决定放弃支持IE8.0一样,支持HTTP/2或者采取某种混合作业的方式,这样的决定只能根据各个网站自身的相关数据来做出。

As described in [a post by Kahn AcademyEngineering](http://engineering.khanacademy.org/posts/js-packaging-http2.htm)that analyzed HTTP/2 traffic on its site, unbundling a large number of assetscan actually increase the total number of bytes transferred. With[zlib](http://www.zlib.net/), compressing a single large file is more efficientthan compressing many small files. The effect can be significant on an HTTP/2site that has unbundled hundreds of assets.

正如[卡恩工程院的博文](http://engineering.khanacademy.org/posts/js-packaging-http2.htm)所述,他们曾分析了其网站上的HTTP/2流量,事实上,拆分大量资产会增加所传输字节的总量。而使用[zlib](http://www.zlib.net/)压缩单一大型文件,比压缩多个小型文件要更有效率。对于拥有成百上千解绑资产的HTTP/2站点来说,这种效应更为显著。

Using HTTP/2 in browsers also requires assets to bedelivered over TLS. Setting up TLS certificates can be cumbersome for theuninitiated. Fortunately, open source projects such as [Let’sEncrypt](https://letsencrypt.org/) are working on making certificateregistration more accessible.

在浏览器中使用HTTP/2还要求我们通过TLS进行资产交付。对于菜鸟们来说,设置TLS证书就是个烦人的活。幸运的是,诸如[Let’sEncrypt](https://letsencrypt.org/)的开源项目正努力让证书注册工作变得更加便捷。

#A Work in Progress

#仍在进行中的工作

Most users don’t care what application protocol your siteuses—they just want it to be fast and work as expected. Although HTTP/2 hasbeen officially ratified for almost a year, developers are still learning bestpractices when building faster websites on top of it. The benefits of switchingto HTTP/2 depend largely on the makeup of the particular website and whatpercentage of its users have modern browsers. Moreover, debugging the newprotocol is challenging and easy-to-use developers tools are still underconstruction.

大部分用户并不在意你的站点用了啥协议——他们只想要它速度快,运行如人预期。虽然HTTP/2已经正式被批准快一年了,开发人员还在学习如何利用它来建立更快速网站的最优实践。换用HTTP/2的好处更多取决于具体站点的制作和多大比例的用户使用现代的浏览器。再有就是,调试新协议很有挑战性,更易用的开发工具也在研制中。

Despite these challenges, HTTP/2 adoption is growing.According to researchers scanning popular Web properties, [the number of topsites that use HTTP/2 isincreasing](http://isthewebhttp2yet.com/measurements/adoption.html), especiallyafter [CloudFlare](https://www.cloudflare.com/) and [WordPress](https://wordpress.com/)announced their support in late 2015. When considering a switch, it’s importantto carefully measure and monitor asset- and page-load time in a variety ofenvironments. As vendors and Web professionals educate themselves on the implicationsof this massive change, making decisions from real user data is critical. Inthe midst of a [website obesitycrisis](http://idlewords.com/talks/website_obesity.htm), now is a great time tocut down on the total number of assets regardless of the protocol.

虽然有这些挑战,HTTP/2的采纳度在增加。根据研究人员扫描流行网站属性的结果,[排名前列的站点中使用HTTP/2的一直在增加](http://isthewebhttp2yet.com/measurements/adoption.html),特别是[CloudFlare](https://www.cloudflare.com/)和[WordPress](https://wordpress.com/)2015年宣布提供支持之后。考虑转换的时候,很重要的一点是仔细测量资源和页面在不同环境下加载的时间。供应商和专业网站人员都熟悉了大量转换背后的含义,从真实用户数据中做出判断才是关键的。在[网站臃肿危机](http://idlewords.com/talks/website_obesity.htm)之时,这是一个无视协议削减资源数量的好时机。

In Part 2 of this series on HTTP/2, we’ll focus on practicalimplementation details of HTTP/2 and how to enable it on your server and debugreal traffic.

在这一关于HTTP/2系列的第二部分中,我们会聚焦如何在服务器上实现HTTP/2和调试真是网络通信的具体实现细节。

This article was written by Clay Smith, with contributionsof technical feedback and invaluable suggestions by Jeff Martens, ProductManager for New Relic Browser, and Web performance expert Andy Davies.

本文作者为Clay Smith,同时New Relic浏览器的产品经理JeffMartens和Web性能专家AndyDavies都给出了技术反馈和极为宝贵的建议。

你可能感兴趣的:(IT类翻译 -- HTTP/2正给Web性能最佳实践带来怎样的影响?)