1、Http2优势
信道复用
分帧传输
Server Push
如下图: 上面是http1,下面是http2
2、搭建http2
1)配置前端
文件结构
server.js
const http = require('http'); const fs = require('fs') http.createServer(function(request, response){ console.log('request come', request.url) const html = fs.readFileSync("test.html",'utf-8') const img = fs.readFileSync("test.jpg"); if(request.url === '/'){ response.writeHead(200,{ 'Content-Type':'text/html', 'Connection':'close', 'Link': '</test.jpg>; as=image; rel=preload' }) response.end(html) }else{ response.writeHead(200,{ 'Content-Type':'text/html', 'Connection':'close' }) response.end(img) } }).listen(7080); console.log('server listening on 7080')
test.html
<html> <head> <title>Document</title> </head> <body> </body> </html>
test.jpg是一张图片
2)配置nginx
test.conf
server{ listen 80 default_server; listen [::]:80 default_server; server_name test.com; return 302 https://$server_name$request_uri; } server{ listen 443 http2; server_name test.com; http2_push_preload on; ssl on; ssl_certificate_key ../certs/localhost-privkey.pem; ssl_certificate ../certs/localhost-cert.pem; location / { proxy_pass http://127.0.0.1:7080; proxy_set_header Host $host; } }
启动nginx,这里nginx需要大于一定的版本才支持http2
3)、访问test.com
可以看到Protocol为h2,它就是http2. 看上去是一个请求,因为这是一个demo,在本地运行。那如何查看是push呢?
4)、如何查看是push?
Chrome打开chrome://net-internals/#http2,
可以看到,有一条Pushed。