hash_data vcl_hash 有什么作用?

Joh*_*oca 4 caching varnish varnish-vcl

有人可以解释以下 vcl 代码。

sub vcl_hash {
    hash_data(req.url);

    if (req.http.host) {
      hash_data(req.http.host);
    } else {
      hash_data(server.ip);
    }

    if (req.http.Cookie) {
      hash_data(req.http.Cookie);
    }
}
Run Code Online (Sandbox Code Playgroud)

我只了解使用 hash_data 函数作为缓存键的 req.url 的散列。下一个 if else 代码对我来说是模糊的。

请帮忙。谢谢。

ale*_*jdg 5

hash_data方法用于设置缓存对象的哈希值,即键值。该键用于将对象与缓存中已有的对象进行比较。

在您发布的代码中,首先考虑散列的是所请求页面的 URL:req.url

但请注意,如果 Varnish 仅使用 URL 来散列对象,则它会过于模糊,并可能导致将相同的缓存传送到不同的站点,例如www.example.com/test_urlwww.example2.com/test_url

为了避免这个问题,它会将主机(req.http.host)添加到散列(如果存在),如果不存在,它将添加IP(server.ip),例如,http://192.168.0.1/test_url

最后,它会检查 Cookie 是否存在,如果确实存在,也会将它们添加到哈希中。这是在页面根据 cookie 显示不同内容时完成的。