定义后端主机列表:
vim /etc/varnish/default.vcl
# Default backend definition. Set this to point toyour content server.
backend websrv1 {
.host ="192.168.2.223";
.port ="80";
.probe = {
.url ="/index.htm";
}
}
backend websrv2 {
.host ="192.168.2.224";
.port ="80";
.probe = {
.url ="/index.htm";
}
}
import directors; #导入directors
#[root@node230 varnish]# man vmod_directors 配置命令详解
sub vcl_init {
newmycluster = directors.round_robin(); #定义集群,后端服务器轮询
mycluster.add_backend(websrv1);
mycluster.add_backend(websrv2);
}
sub vcl_recv {
set req.backend_hint = mycluster.backend();
}
动态加载vcl文件:
[root@node230 ~]# varnishadm -S /etc/varnish/secret -T192.168.2.230:6082
vcl.list
200
active 0boot
vcl.load test2 test.vcl
200
VCL compiled.
vcl.use test2
200
VCL 'test2' now active
vcl.list
200
available 0boot
active 0test2
在varnish服务器上可以看到负载均衡器效果:
一个请求同时到后端两台服务器上去取数据
varnishd 24295 varnish 26u IPv4 736836 0t0 TCP node230:52496->192.168.2.223:http(ESTABLISHED
)
varnishd 24295varnish 27u IPv4 736837 0t0 TCP node230:45026->192.168.2.224:http(ESTABLISHED
)
varnishd 24295varnish 28u IPv4 736838 0t0 TCP node230:52500->192.168.2.223:http(ESTABLISHED
)
varnishd 24295varnish 29u IPv4 736839 0t0 TCP node230:45030->192.168.2.224:http(ESTABLISHED
)
负载均衡算法
sub vcl_init {
new mycluster = directors.round_robin(); #定义集群,后端服务器轮询
mycluster.add_backend(websrv1);
mycluster.add_backend(websrv2);
}
其它算法:
fallback
random
round_robin
hash