Varnish:使每个 API key 对象单独缓存

标签 varnish varnish-vcl varnish-4

我安装了 Varnish 4,根据每个请求 header 中的 API key 选择后端,例如(我们在 vcl_recv 中):

if (req.url ~ "/content") {
    # Check for presence of X-Api-Key header
    if ((! req.http.X-Api-Key) || ((! req.http.X-Api-Key ~ "prod-") && (! req.http.X-Api-Key ~ "test-"))) {
        return(synth(403,"Access Denied - API key missing or invalid."));
    }
    if (req.http.X-Api-Key ~ "prod-") {
        set req.backend_hint = PROD.backend();
    }
    if (req.http.X-Api-Key ~ "test-") {
        set req.backend_hint = TEST.backend();
    }
}

但是,如果从 PROD 后端获取的对象的 TTL 未过期,则可以将其传递给对 TEST 后端的请求,反之亦然。

如何确保每个后端的内容彼此隔离?

最佳答案

这个很简单。由于您希望缓存因特定 header 而异,因此您应该告诉 Varnish。因此,要么让你的后端发送 Vary: X-Api-Key (最佳路由),或者在该 header 的值上使用 Varnish hash:

sub vcl_hash {
    if (req.http.X-Api-Key) {
        hash_data(req.http.X-Api-Key);
    }
}

关于Varnish:使每个 API key 对象单独缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54747583/

相关文章:

nginx - 特定数量的请求后,在Varnish-Cache中缓存资源

apache - 如何使用多个apache虚拟主机设置varnish 4.1.2?

php - laravel 中用于缓存的 varnish 等效包

varnish - 在 Varnish 4 中重试期间更改后端

使用cookie缓存而不使用cookie

varnish - 从缓存发出 Varnish 服务请求(cookies被清除)

varnish4 与 varnish3 - 优雅行为

Varnish 缓存和 Google 跟踪代码管理器

nginx - Vagrant + Puppets 模块