1. varnish服务配置 2. varnish多后端配置 3. varnish调度策略配置 4. 网页方式管理缓存
安装varnish 软件下载安装顺序
jemalloc-3.6.0-1.el7.x86_64.rpm varnish-libs-4.0.5-1.el7.x86_64.rpm varnish-4.0.5-1.el7.x86_64.rpm查看文件/usr/lib/systemd/system/varnished.service 文件最大限制数
LimitNOFILE=131072 最大打开文件数131072/2反向代理,连接占用/打开占用最大缓存大小
LimitMEMLOCK=820000 最大查看文件/etc/varnish/varnish.params 修改端口
VARNISH_LISTEN_PORT=80查看/etc/security/limits.conf 修改本机限制
varnish - nofile 131072 varnish - memlock 82000修改配置文件/etc/varnish/default.vcl 添加缓存对象
# 添加缓存对象 backend default { .host = "172.25.41.2"; .port = "80"; }返回缓存命中结果
# 返回缓存命中结果 sub vcl_deliver { if (obj.hits > 0) { set resp.http.X-Cache = "HIT from westos cache"; } else { set resp.http.X-Cache = "MISS from westos cache"; } return (deliver); }安装apache
yum insatll -y httpd编写index.html,内容为www.octopus.com 启动apache
主机访问CDN主机 第一次访问结果为MISS 第二次访问结果为HIT 手动清除缓存
varnishadm ban req.url "~" /清除固定页面缓存
vanishadm ban req.url "~" /index.html清除缓存后再次测试 Age时间到达之后也会自动刷新缓存
添加一个新的主机,安装apache服务 设置主页面为bbs.octopus.com 启动apache服务,测试访问
修改varnish服务端配置文件/etc/varnish/default.vcl 配置多后端文件
backend www { .host = "172.25.41.2"; .port = "80"; } # 添加一个新的apache服务器 backend bbs { .host = "172.25.41.3"; .port = "80"; }配置接收策略
sub vcl_recv { # Happens before we check if we have this in cache already. # # Typically you clean up the request here, removing cookies you don't need, # rewriting the request, etc. if (req.http.host ~ "^(www.)?octopus.com") { set req.http.host = "www.octopus.com"; set req.backend_hint = www; } elsif (req.http.host ~ "^bbs.octopus.com") { set req.backend_hint = bbs; } else { return (synth(405)); } }重启服务varnish
systemctl restart varnish配置访问主机的本地域名解析 验证结果
修改配置文件/etc/varnish/default.vcl 添加模块
import directors from "/usr/lib64/varnish/vmods/libvmod_directors.so";设置调度器
sub vcl_init{ new lb = directors.round_robin(); lb.add_backend(www); lb.add_backend(bbs); }使用调度器
sub vcl_recv { # Happens before we check if we have this in cache already. # # Typically you clean up the request here, removing cookies you don't need, # rewriting the request, etc. if (req.http.host ~ "^(www.)?octopus.com") { set req.http.host = "www.octopus.com"; # 使用调度器 set req.backend_hint = lb.backend(); # 清除缓存,实际配置的时候不需要加 return (pass); } elsif (req.http.host ~ "^bbs.octopus.com") { set req.backend_hint = bbs; } else { return (synth(405)); } }访问www.octopus.com轮询不同的网站,访问bbs.octopus.com只返回一个网站
修改配置文件/etc/varnish/default.vcl 添加可修改权限
acl octopus { "127.0.0.1"; "172.25.41.0"/24; }设置接收方式和返回值
if (req.method == "BAN"){ if (!client.ip ~ octopus){ return (synth(405,"Not allowed.")); } ban("req.url ~ " + req.url); return (purge); }安装apache,php,修改端口为8080 解压文件bansys,移动所有文件至网站发布目录/var/www/html 修改其中的config.php文件内容如下
<?php //varnish主机列表 //可定义多个主机列表 $var_group1 = array( //CDN主机 'host' => array('172.25.41.1'), //端口 'port' => '8080', ); //varnish群组定义 //对主机列表进行绑定 $VAR_CLUSTER = array( # 设定主机列表 'www.octopus.com' => $var_group1, ); //varnish版本 //2.x和3.x推送命令不一样 $VAR_VERSION = "3"; ?>启动apache
systemctl start httpd打开网页
发送清除缓存的内容,发现缓存刷新