varnish介绍:
Varnish是一款高性能、开源的反向代理服务器和缓存服务器。Varnish使用内存缓存文件来减少响应时间和网络带宽消耗。
由于varnish先进的设计理念,性能要比squid高上许多, varnish还可以通过端口进行管理,使用正则语句做到清除指定缓存的功能,这些squid都做不到。但是varnish在高并发的情况下,资源消耗较高,而且varnish服务进程一~旦崩溃 ,重启,内存中的缓存数据将全部丢失
varnish是基于现代设备设计的服务项目,所以仅支持64位系统。Manager Preess负责处理请求任务,保证每个任务分配一个worker threads。所以varnish是一 个重线程型服务。 除此之外,manager process包含接受CL命令控制的功能,包括调整运行参数,vcl|配置更新。初始化子进程Cacher Process ,并按一定频率检测cacher在线与否。
**制作varnish代理服务器
首先准备环境 编译环境
yum install -y gcc gcc-c++ make
关闭防火墙或者设置防火墙规则
systemctl stop firewalld setenforce 0
安装所需依赖插件
yum install -y
libtool
ncourses-devel
pcre-devel
libedit-devel
libxslt
groff
pkgconfig
ncurses-devel
python-*
安装所需的依赖包
rpm -ivh libedit-devel-3.0-12.20121213cvs.el7.x86_64.rpm rpm -ivh python-docutils-0.11-0.2.20130715svn7687.el7.noarch.rpm
解压软件包
tar xf varnish-5.2.1.tgz -C /opt
进入解压后的文件夹中定义需要的模块
cd /opt/varnish-5.2.1/
检查系统环境
sh autogen.sh
定制功能
./configure
--prefix=/usr/local/varnish
--enable-debugging-symbols
--enable-developer-warnings
编辑安装
make && make install
软连接
cd /usr/local/varnish/ ln -s /usr/local/varnish/sbin/varnishd /usr/sbin/ ln -s /usr/local/varnish/bin/* /usr/local/bin/
配置文件模板拷贝出来用
cp /usr/local/varnish/share/doc/varnish/example.vcl /usr/local/varnish/default.vcl 或者cp /opt/varnish-5.2.1/etc/example.vcl /usr/local/varnish/default.vcl
进入配置文件
vi /usr/local/varnish/default.vclg 注:.host 是代理httpd服务的IP地址
指定监听的ip和端口启动varnish
varnishd -f /usr/local/varnish/default.vcl -a 0.0.0.0:80
在另一台linux虚拟机上搭建一个web服务器:
yum install -y httpd vi /var/www/html/index.html server 1 systemctl start httpd 测试,在windows浏览器中输入http://192.168.80.100(varnish服务器的ip地址) 结果图·
Varnishlog #查看日志,实时滚动方式
以上是单台代理服务器· 多带代理服务器如下:
vi /usr/local/varnish/default.vcl 找到以下内容并修改: vcl 4.0; import directors; //新增一行,导入一个directors
-----以下增加业务服务器节点----- backend web1 { #把default修改为web1,就是后面的web服务器,有几个web节点就复制几个backend域 .host = "192.168.80.101"; #后端web服务器的地址 .port = "80"; #web服务器端口 } backend web2 { .host = "192.168.80.102"; .port = "80"; }
-----接着以上代码接着定义调度算法及指定流量转发---- sub vcl_init { #在init子函数中定义 new bar = directors.round_robin(); //random(随机) round_robin dns #定义服务器组,让新的 bar 等于之前定义的变量directors,后面接轮询(rr)算法 bar.add_backend(web1); #注意这里有几个backend就添加几个 bar.add_backend(web2); } sub vcl_recv { set req.backend_hint = bar.backend(); //流量转发给所有结点 注意括号 }
检查配置文件是否有错误
varnishd -C -f /usr/local/varnish/default.vcl > /dev/null 出现以下代表没有错误
杀死进程
pkill -9 varnish
开启服务
varnishd -f /usr/local/varnish/default.vcl
查看服务是否启动
netstat -anpt | grep varnishd
注:由于varnish缓存的原因,当我们访问varnish的时候,并没有像我们预期的那样根据rr算法各自访问后面两台web服务器的不同页面,这时我们让一台web服务器网络中断,这时varnish就会访问到另一台了。
后端主机健康检测机制:
vi /usr/local/varnish/default.vcl probe healthche { 定义健康检测方法,自定义名称 .url="/index.html"; #检测时请求的URL,默认为"/" .timeout = 2s; #超时时间 .window = 6 ; #基于最近的多少次检测来判断其健康状态 .threshold = 5; #最近.window中定义的这么次检查中至有.threshhold定义的次数是成功的; .interval = 2s; #检测频度; } 在定义后端服务器时引用检测方法 backend web1 { .host = "1921.68.80.100"; .port = "80"; .probe = healthche; #引用检测方式 } 查看效果 varnishadm