You need to enable JavaScript to run this app. Varnish基于Cookie做差异化缓存时如何避免产生重复缓存条目
优惠活动
大模型
产品
解决方案
定价
更多

Varnish基于Cookie做差异化缓存时如何避免产生重复缓存条目

解决方案

方案1:最低成本适配(推荐大多数场景)

每个商城的每个页面最多只会产生1份重复缓存,占用的存储空间极低,远低于深度改造的开发成本,无需修改任何代码,直接沿用现有逻辑即可。

方案2:完全消除重复缓存

你的初始思路是可行的,通过解析后端返回的Set-Cookie头提取默认货币,统一哈希键即可实现,具体配置如下:

步骤1:调整vcl_recv逻辑

sub vcl_recv {
    if (req.http.cookie) {
        cookie.parse(req.http.cookie);
        set req.http.x-currency = cookie.get("currency");
    }
    # 新增:读取已缓存的当前站点默认货币
    set req.http.x-site-default-currency = cache.get("def_curr_" + req.http.host, "");
    # 新增:如果用户当前货币等于站点默认货币,统一清空x-currency值,共用缓存键
    if (req.http.x-currency == req.http.x-site-default-currency) {
        unset req.http.x-currency;
    }
    ...
}

步骤2:保留原有vcl_hash逻辑

sub vcl_hash {
    if(req.url !~ "^/(contact|sitemap)") {
        hash_data(req.http.x-currency);
    }
}

步骤3:新增vcl_backend_response逻辑

sub vcl_backend_response {
    # 提取Set-Cookie中的默认货币值
    if (bereq.http.x-currency == "" && beresp.http.Set-Cookie ~ "currency=([A-Z]{3})") {
        set beresp.http.x-temp-def-curr = regsub(beresp.http.Set-Cookie, ".*currency=([A-Z]{3}).*", "\1");
        # 缓存当前站点默认货币,有效期可根据币种修改频率调整,此处设为1天
        cache.set("def_curr_" + bereq.http.host, beresp.http.x-temp-def-curr, 86400s);
        unset beresp.http.x-temp-def-curr;
    }
    # 原有其他逻辑保留
    ...
}

注:开源版Varnish如果没有内置cache模块,可以用vmod_kvstore或者vmod_redis实现键值缓存,也可以选择改造后端新增X-Default-Currency响应头,无需正则解析Set-Cookie,稳定性更高。

内容的提问来源于stack exchange,提问作者Diyan Slavov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 11:51:03