您的位置:首页 > 其它

Varnish 4 笔记

2016-03-16 19:03 344 查看

安装

环境Ubuntu 12.04+ varnish-4.1.2+nginx

apt-get install apt-transport-https
curl https://repo.varnish-cache.org/GPG-key.txt | apt-key add -
echo "deb https://repo.varnish-cache.org/ubuntu/ trusty varnish-4.1" >> /etc/apt/sources.list.d/varnish-cache.list
apt-get update
apt-get install varnish


端口配置

默认的端口是监听6081

vim /etc/default/varnish

DAEMON_OPTS="-a :6081 \
-T localhost:6082 \
-f /etc/varnish/default.vcl \
-S /etc/varnish/secret \
-s malloc,256m -t 120"


-a #如果希望80端口直接访问修改

-t 缓存的时间

-s使用的内存

-S认证的文件
varnishadm -T localhost:6082 -S secret


配置文件

vcl 4.0;

# Default backend definition. Set this to point to your content server.
#后端的HTTP服务器IP和端口
backend default {
.host = "127.0.0.1";
.port = "8001";
}

#设置清理缓存的IP
acl purgers {
"127.0.0.1";
}

sub vcl_recv {
if (req.method == "PURGE") {    # PURGE请求的处理
if (!client.ip ~ purgers) {
return(synth(405,"Method not allowed"));
}
#清理缓存
return(purge);
}
# 禁止缓存的文件
if (req.url ~ "aaa.html") {
return(pass);
}
if (req.method != "GET" && req.method != "HEAD") {
return (pass);
}
#不缓存认证信息和Cookie,
#nginx静态文件默认带Cookie信息,我开始配置的时候一直不能命中缓存查了很久才找到原因在这,
if (req.http.Authorization || req.http.Cookie) {
return (pass);
}
#不正常的访问不缓存
if (req.method != "GET" &&
req.method != "HEAD" &&
req.method != "PUT" &&
req.method != "POST" &&
req.method != "TRACE" &&
req.method != "OPTIONS" &&
req.method != "PATCH" &&
req.method != "DELETE") {
return (pipe);
}
}

sub vcl_backend_response {
# Happens after we have read the response headers from the backend.
#
# Here you clean the response headers, removing silly Set-Cookie headers
# and other mistakes your backend does.
}

sub vcl_deliver {
if (obj.hits > 0) {
#如果命中缓存 Response Headers x-cache-lookup= MemCache
set resp.http.x-cache= "MemCache";
} else {
set resp.http.x-cache= "MISS";
}
#删除Response Headers 部分信息
#unset resp.http.Server;
#unset resp.http.X-Drupal-Cache;
#unset resp.http.X-Varnish;
#unset resp.http.Via;
#unset resp.http.Age;
#unset resp.http.Link;
}


我用的是varnish-4.1.2 不同的版本配置不一致

详细的配置模板

https://github.com/mattiasgeniar/varnish-4.0-configuration-templates/blob/master/default.vcl

效果

第一次访问没缓存



再刷新一次



也可以查看后台的nginx的日志

Varnish默认遵循源:根据Cache-Control的规则进行缓存。如果请求头里面有Cache-Control:no-cache 或者 Age:0是不缓存的,比如Ctrl+F5 刷新浏览器会在请求头里面加Cache-Control:no-cache

如果想缓存,可以在程序或者nginx 加 expires 15d; 也可以修改Varnish配置

sub vcl_backend_response {
set beresp.http.Cache-Control = "public";
}


我的个人网址全站加了缓存,每次添加或者修改后都需要清理缓存

清理缓存

配置文件指定了PURGE和IP 就可以用
curl
清理缓存

curl -X PURGE http://127.0.0.1:6081/


缓存命中率

缓存命中率的高低,直接反映Varnish的运行状态,以下通过varnishstat命令查看状态信息

varnishstat




Hitrate n 第一个数字范围0-10,第二个数字范围0-100,第三个数字范围0-1000。分别表示过去N秒内的

avg(n) 里的内容是命中率,需要乘以100转换成百分比 。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ubuntu Varnish