目录
- http2的特点以及限制
- 实现服务端推送
- 兼容http1.1和http2
1. http2的特点以及限制
- http2支持信道复用和分帧传输,因而可以将数据分成小部分发送,使tcp可并发发送http,因而一个用户只用使用一个tcp连接即可,减少了tcp连接时的开销。
- http支持Server Push,即服务端可以主动向客户端发送http,例如在客户端读取html后,css,js等静态资源文件同时由服务端向客户端推送,而不用再由浏览器解析出资源连接,在发送http请求,加快了加载的速度。
- 由于大部分语言后端代码仍只支持http1.1,因而nginx会将得到的请求变为http1.1的格式,再转发给http1.1给服务端。因为服务端通常是在内网中,速度较快。nginx支持http2后,保证了浏览器到nginx的传输中使用的http2的,加快了这段的传输。
- 目前使用http2必须在https上,但是在理论上http2与https是不相交的。
- 测试http2的性能
2. 实现服务端推送
-
代码实现
<img src="test.jpg" alt="">
- 最重要的代码就一行
'Link': '</test.jpg>; as=image; rel=preload'
/**
* 1. 使用nginx实现http2
*/
const http = require('http')
const fs =require('fs')
const port = 9000
http.createServer(function (request, response) {
const url = request.url
const html = fs.readFileSync('test.html', 'utf-8')
const img = fs.readFileSync('image.jpg')
switch(url) {
case '/': {
response.writeHead(200, {
'Content-Type': 'text/html',
'Connection': 'close',
'Link': '</test.jpg>; as=image; rel=preload'
})
response.end(html)
}
case '/test.jpg': {
response.writeHead(200, {
'Content-Type': 'image/jpg',
'Connection': 'close'
})
response.end(img)
}
}
}).listen(port)
console.log("serve is listen ", port)
- nginx服务保持之前实现的https
- 在listen中增加http2
-
http2_push_preload on
,开启http2的服务端推送功能
server {
# listen 80 default_server;
# listen [::]:80 default_server;
listen 80;
server_name test.com;
return 302 https://$server_name$request_uri;
}
server {
listen 443 http2; # https端口 + http2
server_name test.com;
http2_push_preload on; # 开启http2的服务端推送功能
ssl on; # 开启ssl
ssl_certificate_key ../certs/localhost-privkey.pem; # 私钥
ssl_certificate ../certs/localhost-cert.pem; # 证书
location / {
proxy_pass http://localhost:9000/;
}
}
-
测试
- 首先注释掉node代码中提到的实现推送的一行,开启node和nginx服务后,访问
test.com:443
。 - 观察图中内容可知当前的图片是由index解析出来的,请求得到的,
-
取消注释,重启node服务,这次可以看到来源是Other,也就是不是解析html代码出来的,可以视为是服务端推送得到的
更明确的观察是否有服务端推送,需要访问
chrome://net-internals/#http2
。-
下图中可以找到我们使用
Server Push
发送的http2协议
image.png
3. 兼容http1.1和http2
- 使用alpn兼容http1.1和http2,也就是客户端是否支持http2都能顺利的运行。
- 使用http2访问:
curl -v -k https://test.com/
,-k
参数的功能是忽略证书的验证。
- 使用http1.1访问:
curl -v -k --http1.1 https://test.com/
。