目录结构
nginx
test.conf
proxy_cache_path cache levels=1:2 keys_zone=my_cache:10m;
server {
listen 80;
server_name test.com;
location / {
proxy_cache my_cache;
proxy_pass http://127.0.0.1:8888;
proxy_set_header Host $host;
}
}
本地
server.js
max-age=20用于设置服务器的缓存
const http = require('http');
const fs = require('fs');
const wait = (seconds) => {
return new Promise((resolve,reject) => {
setTimeout(() => {
resolve()
},seconds * 1000)
})
}
http.createServer(function(req, res) {
console.log('request come', req.headers.host);
if (req.url === '/') {
const html = fs.readFileSync('test.html', 'utf8');
res.writeHead(200, {
})
res.end(html)
}
if(req.url === '/data'){
res.writeHead(200, {
'Cache-Control':'max-age=20'
})
wait(2).then(() => {
res.end('success')
})
}
}).listen(8888)
console.log('server start at port 8888')
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>this is content, <span id="data"></span></div>
<script>
fetch('/data').then(function(res){
return res.text()
}).then(function(text){
document.getElementById('data').innerText = text;
})
</script>
</body>
</html>
运行
- 第一次请求,等了2秒才显示content
- 刷新,不用等待,直接显示
- 等待20秒,请求2秒才显示
请求头
s-maxage=20
用于设置nginx的缓存
- 第一次请求,等了2秒才显示content
- 刷新,不用等待,直接显示
- 等待20秒,请求2秒才显示
if(req.url === '/data'){
res.writeHead(200, {
'Cache-Control':'max-age=2,s-maxage=20;'
})
wait(2).then(() => {
res.end('success')
})
}
private
每次请求,等了2秒才显示content
if(req.url === '/data'){
res.writeHead(200, {
'Cache-Control':'max-age=2,s-maxage=20,private;'
})
wait(2).then(() => {
res.end('success')
})
}
验证缓存
除了url相同外,还有别的判断缓存的东西
server.js
if(req.url === '/data'){
res.writeHead(200, {
'Cache-Control':'s-maxage=200;',
'Vary':'X-Test-Cache'
})
wait(2).then(() => {
res.end('success')
})
}
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>this is content, <span id="data"></span></div>
<button id="button">click</button>
<script>
var index = 0;
function doRequest() {
var data = document.getElementById('data');
data.innerText = '';
fetch('/data',{
headers:{
'X-Test-Cache':index++
}
}).then(function (res) {
return res.text()
}).then(function (text) {
document.getElementById('data').innerText = text;
})
}
document.getElementById('button').addEventListener('click',doRequest)
</script>
</body>
</html>
由于每次X-Test-Cache
都不同,所以并不会缓存
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。