问题
I have the following VCL:
vcl 4.0;
import std;
import directors;
backend one {
.host = "localhost";
.port = "3333";
}
backend two {
.host = "localhost";
.port = "3333";
}
sub vcl_init {
new random_director = directors.random();
random_director.add_backend(two, 10);
random_director.add_backend(one, 8);
}
sub vcl_recv {
std.log("start vcl_recv");
set req.backend_hint = random_director.backend();
if (req.backend_hint == one) {
std.log("one");
} else if (req.backend_hint == two) {
std.log("two");
} else {
std.log("neither one");
}
std.log("end vcl_recv");
}
When I run it, the output is always:
start vl_recv
neither one
end vcl_recv
How can I properly check to see which backend has been selected?
Thanks
回答1:
In vcl_backend_fetch
you should be able to access bereq.backend.name
So moving your code, you might have something like:
sub vcl_backend_fetch {
if (bereq.backend.name == "one") {
std.log("one");
} else if (bereq.backend.name == "two") {
std.log("two");
} else {
std.log("neither one");
}
}
回答2:
Update: it's not possible to know the selected backend before requesting a backend call, so you'll never get this information in the vcl_recv
. As you may not need the backend selection (if the object is already in cache), or because the backend could change (if one goes down) before the selection is run (so the time between the vcl_recv
and vcl_fetch_response
), it would be a waste of resources to determine it in the vcl_recv
.
But in Varnish 5.0+ you can use the beresp.backend
(or beresp.backend.name
as you need to log it as a string) available in vcl_backend_response
, which is defined as:
This is the backend we fetched from. If bereq.backend was set to a director, this will be the backend selected by the director.
See: https://varnish-cache.org/docs/5.0/reference/vcl.html#beresp
来源:https://stackoverflow.com/questions/43357690/varnish-vcl-how-can-i-switch-on-req-backend-hint