4-2 Nginx代理配置和代理缓存的用处
2018-12-07 本文已影响0人
伯纳乌的追风少年
nginx配置:
proxy_cache_path cache levels=1:2 keys_zone=my_cache:10m;
#cache:目录
#levels:可自建的目录等级
#keys_zone:缓存区名
#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; #nginx对http请求的host进行转发
}
}
server {
listen 80;
server_name a.test.com;
location / {
proxy_pass http://127.0.0.1:8888;
proxy_set_header Host $host; #nginx对http请求的host进行转发
}
}
server {
listen 80;
server_name b.test.com;
location / {
proxy_pass http://127.0.0.1:8888;
proxy_set_header Host $host; #nginx对http请求的host进行转发
}
}
server.js
const http=require('http');
const fs=require('fs')
const wait=(second)=>{
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve()
},second*1000)
})
}
http.createServer(function(request,response){
console.log('request come',request.headers.host)
if (request.url==='/') {
const html=fs.readFileSync('test.html','utf8')
response.writeHead(200,{
'Content-Type':'text/html',
})
response.end(html)
};
if (request.url==='/data') {
response.writeHead(200,{
'Cache-Control':'s-maxage=200',
'Vary':'X-Text-Cache'
})
wait(2).then(()=>{
response.end('success')
})
};
}).listen(8888)
console.log('server listening on 8888')
server响应头配置说明:
'Cache-Control':'max-age=5,s-maxage=20' 浏览器缓存使用max-age的值,代理服务器使用s-maxage的值
'Cache-Control':'max-age=5,s-maxage=20,private' 只有浏览器缓存,代理服务器不允许缓存
'Cache-Control':'max-age=5,s-maxage=20,nostore' 浏览器和代理服务器都不允许缓存
'Vary':'X-Text-Cache' 只有Vary指定的http的头是相同的情况下才会使用缓存
test.html
<html>
<head>
<title>4-2 Nginx代理配置和代理缓存的用处</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
<div>This is content,the data is <span id="data"></span></div>
<button id="btn">click me</button>
</body>
<script type="text/javascript">
var index=0;
function doRequest(){
document.getElementById('data').innerText=''
fetch('/data',{
headers:{
'X-Text-Cache':index++
}
}).then((resp)=>{
return resp.text()
}).then((text)=>{
document.getElementById('data').innerText=text
})
}
document.getElementById('btn').addEventListener('click',doRequest)
</script>
</html>

如图所示,当第一次点击按钮时,请求头会带上
'X-Text-Cache':0
,如果缓存服务器已经缓存过'X-Text-Cache':0
的数据,则直接从缓存服务器拿取数据。当下次点击按钮时,请求头变成了
'X-Text-Cache':1
,倘若此时缓存服务器没有存过'X-Text-Cache':1
的数据,则从后台服务器拿取数据。