Linux-Varnish缓存
实验环境:
centos7.3
安装:
Jemalloc和varnish-libs先安装哪个都可以,varnish依赖varnish-libs,所以放在最后安装
[root@xuegod63 ~]# rpm -ivh varnish-libs-4.0.5-1.el7.x86_64.rpm
[root@xuegod63 ~]# rpm -ivh jemalloc-3.6.0-1.el7.x86_64.rpm #内存控制工具
[root@xuegod63 ~]# rpm -ivh varnish-3.0.6-1.el6.x86_64.rpm
vcl置文件:
[root@xuegod63 ~]# ls /etc/varnish/default.vcl
varnish主配置文件:
[root@xuegod63 ~]# vim /etc/varnish/varnish.params
启动varnish服务:
[root@xuegod63 ~]# systemctl start varnish
缓存多个网站:
代理服务器: 192.168.1.201 www.vampire.com bbs.vampire.com
Web1 : 192.168.1.202
Web2: 192.168.1.203
配置varnish服务端口:
[root@vampire63 ~]# vim /etc/varnish/varnish.params
改:
66 VARNISH_LISTEN_PORT=6081
为:
VARNISH_LISTEN_PORT=80
修改varnish服务器的配置文件:
[root@localhost ~]# vim /etc/varnish/default.vcl
改:
backend web1 {
.host = "127.0.0.1";
.port = "8080";
}
为:
backend web1 {
.host = "192.168.1.202";
.port = "80";
}
backend web2 {
.host = "192.168.1.203";
.port = "80";
}
注:若有多个网站,只需添加backend,指定对应的名称,以便进行匹配
实现以下功能:
当访问www.vampire.com域名时从web1上取数据,
访问bbs.vampire.com域名时到web2取数据
[root@localhost ~]# vim /etc/varnish/default.vcl #在sub vcl_deliver 处定义以下内容:
sub vcl_recv {
if (req.http.host ~ "(?i)^(www.)?vampire.com$") {
set req.http.host = "www.vampire.com";
set req.backend_hint = web1;
} elsif (req.http.host ~ "(?i)^bbs.vampire.com$") {
set req.backend_hint = web2;
return(hash);
}
}
注:此处需要注意需要在varnish代理服务器上面修改hosts文件,或者在DNS服务器上面天添加解析
此处为修改本地hosts文件:
[root@localhost ~]#vim /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.1.201 www.vampire.com
192.168.1.201 bbs.vampire.com
重新加载varnish配置文件:
[root@localhost ~]# systemctl reload varnish