目錄
- http2的特點(diǎn)以及限制
- 實(shí)現(xiàn)服務(wù)端推送
- 兼容http1.1和http2
1. http2的特點(diǎn)以及限制
- http2支持信道復(fù)用和分幀傳輸,因而可以將數(shù)據(jù)分成小部分發(fā)送脱吱,使tcp可并發(fā)發(fā)送http蹬叭,因而一個(gè)用戶只用使用一個(gè)tcp連接即可偿曙,減少了tcp連接時(shí)的開(kāi)銷(xiāo)惩猫。
- http支持Server Push嘁灯,即服務(wù)端可以主動(dòng)向客戶端發(fā)送http辞友,例如在客戶端讀取html后师痕,css溃睹,js等靜態(tài)資源文件同時(shí)由服務(wù)端向客戶端推送,而不用再由瀏覽器解析出資源連接胰坟,在發(fā)送http請(qǐng)求因篇,加快了加載的速度泞辐。
- 由于大部分語(yǔ)言后端代碼仍只支持http1.1,因而nginx會(huì)將得到的請(qǐng)求變?yōu)閔ttp1.1的格式竞滓,再轉(zhuǎn)發(fā)給http1.1給服務(wù)端咐吼。因?yàn)榉?wù)端通常是在內(nèi)網(wǎng)中,速度較快商佑。nginx支持http2后锯茄,保證了瀏覽器到nginx的傳輸中使用的http2的,加快了這段的傳輸茶没。
- 目前使用http2必須在https上肌幽,但是在理論上http2與https是不相交的。
- 測(cè)試http2的性能
2. 實(shí)現(xiàn)服務(wù)端推送
-
代碼實(shí)現(xiàn)
<img src="test.jpg" alt="">
- 最重要的代碼就一行
'Link': '</test.jpg>; as=image; rel=preload'
/**
* 1. 使用nginx實(shí)現(xiàn)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服務(wù)保持之前實(shí)現(xiàn)的https
- 在listen中增加http2
-
http2_push_preload on
抓半,開(kāi)啟http2的服務(wù)端推送功能
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; # 開(kāi)啟http2的服務(wù)端推送功能
ssl on; # 開(kāi)啟ssl
ssl_certificate_key ../certs/localhost-privkey.pem; # 私鑰
ssl_certificate ../certs/localhost-cert.pem; # 證書(shū)
location / {
proxy_pass http://localhost:9000/;
}
}
-
測(cè)試
- 首先注釋掉node代碼中提到的實(shí)現(xiàn)推送的一行喂急,開(kāi)啟node和nginx服務(wù)后,訪問(wèn)
test.com:443
笛求。 - 觀察圖中內(nèi)容可知當(dāng)前的圖片是由index解析出來(lái)的廊移,請(qǐng)求得到的,
-
取消注釋?zhuān)貑ode服務(wù)探入,這次可以看到來(lái)源是Other狡孔,也就是不是解析html代碼出來(lái)的,可以視為是服務(wù)端推送得到的
更明確的觀察是否有服務(wù)端推送蜂嗽,需要訪問(wèn)
chrome://net-internals/#http2
步氏。-
下圖中可以找到我們使用
Server Push
發(fā)送的http2協(xié)議
image.png
3. 兼容http1.1和http2
- 使用alpn兼容http1.1和http2,也就是客戶端是否支持http2都能順利的運(yùn)行徒爹。
- 使用http2訪問(wèn):
curl -v -k https://test.com/
,-k
參數(shù)的功能是忽略證書(shū)的驗(yàn)證芋类。
- 使用http1.1訪問(wèn):
curl -v -k --http1.1 https://test.com/
隆嗅。