varnish-4.x VCL之directors
man vcl
man vmod_directors
一.引用语法
示例:
import directors;
sub vcl_init {
new vdir = directors.random();
vdir.add_backend(backend1, 10);
vdir.add_backend(backend2, 5);
}
二.4种调度算法
· Object
fallback
· VOID fallback.add_backend(BACKEND)
· BACKEND fallback.backend()
A fallback director will try each of the added backends in turn, and return the first one that is healthy
fallback算法,将request按顺序下发给第一个healthy的后端server
· Object
hash
· VOID hash.add_backend(BACKEND, REAL)
· BACKEND hash.backend(STRING_LIST)
The director chooses the backend server by computing a hash/digest of the string given to .backend().
Commonly used with
client.identity or a session cookie to get sticky sessions.
根据hash策略下发request, 可保证相同客户端的request下发到相同的后端server上
· Object
random
· VOID random.add_backend(BACKEND, REAL)
· BACKEND random.backend()
The random director distributes load over the backends using a weighted random probability distribution
按权重比下发请求到后端server
权重比计算方式:100 * (weight / (sum(all_added_weights))) ,如:
vdir.add_backend(backend1, 10);
vdir.add_backend(backend2, 5);
# 2/3 to backend1, 1/3 to backend2.
· Object
round_robin
· VOID round_robin.add_backend(BACKEND)
· BACKEND round_robin.backend()
说明: hash和random都支持权重
如下是本人测试的示例文件,包含healthcheck申明,director引用, purge acl
vcl 4.0;
import std;
import directors;
probe healthcheck_nginx {
.url = "/healthy.jpg";
.timeout = 3s;
.interval = 5s;
.window = 5;
.threshold = 3;
}
probe healthcheck_apache {
.url = "/healthy.jpg";
.timeout = 3s;
.interval = 5s;
.window = 5;
.threshold = 3;
}
backend nginx {
.host = "192.168.192.10";
.port = "8080";
.connect_timeout = 3s;
.first_byte_timeout = 5s;
.between_bytes_timeout = 5s;
.max_connections = 30000;
.probe = healthcheck_nginx;
}
backend apache {
.host = "192.168.192.10";
.port = "8081";
.connect_timeout = 3s;
.first_byte_timeout = 5s;
.between_bytes_timeout = 5s;
.max_connections = 3000;
.probe = healthcheck_apache;
}
sub vcl_init {
new round_robin_director = directors.round_robin();
round_robin_director.add_backend(apache);
round_robin_director.add_backend(nginx);
new random_director = directors.random();
random_director.add_backend(nginx, 10);
random_director.add_backend(apache, 5);
new hash_director = directors.hash();
hash_director.add_backend(nginx, 10);
hash_director.add_backend(apache, 5);
}
acl purgers {
"127.0.0.1";
"192.168.0.0"/24;
}
sub vcl_recv {
# allow PURGE from localhost and 192.168.0...
if (req.restarts == 0) {
unset req.http.X-Purger;
}
if (req.method == "PURGE") {
if (!client.ip ~ purgers) {
return (synth(405, "Purging not allowed for " + client.ip));
}
return (purge);
}
#set req.backend_hint = round_robin_director.backend();
set req.backend_hint = hash_director.backend(req.http.cookie);
}
sub vcl_purge {
set req.method = "GET";
set req.http.X-Purger = "Purged";
return (restart);
}
sub vcl_deliver {
if (req.http.X-Purger) {
set resp.http.X-Purger = req.http.X-Purger;
}
}