跳到主要内容

2. 缓存操作概述 (Overview of Cache Operation)

正确的 cache 操作会在减少传输 cache 中已经保存的信息的同时, 保留 HTTP transfer 的语义. Section 3 说明 cache 如何确定哪些 response 可缓存. Section 4 说明如何从 cache entry 构造 response. 本节概述 cache 如何选择和更新 stored response.

尽管缓存是 HTTP 的完全 OPTIONAL 功能, 仍可以假设重用 cached response 是可取的, 并且在没有 requirement 或本地配置阻止时, 这种重用是默认行为. 因此, HTTP cache requirement 关注的是防止 cache 存储不可重用的 response, 或者不恰当地重用 stored response, 而不是要求 cache 总是存储并重用某些特定 response.

request target 的 query component ([RFC7230] Section 5.3) 可以包含特定于某个用户, 一组用户, 或用户当前状态的 request 信息. 一般而言, cache 重用带有 query component 的 request 的 response 来满足另一个用户的相同 request 是不安全的, 因为即使 path 部分相同, 不同用户的 request 也可能包含不同 query value. 接收到 request target 中带有 query component 的 successful response 的 cache recipient SHOULD NOT 为带有不同 query component 的 request 重用该 response, 除非该 response 通过 Cache-Control directive (Section 5.2) 明确允许这样做.

如果 response 被 Cache-Control directive 明确允许, 或者 response 包含 validator ([RFC7232] Section 2.3) 且 cache 遵循 validation requirement, cache 就可以存储并重用针对带有 query component 的 request 的 response. 发生这种情况时, cache MAY 使用该 response 来满足不同 request, 但前提是 cache key 匹配 (Section 4.1), 所有适用 freshness requirement 都得到满足 (Section 4.2), 并且由 request 和 stored response 施加的任何适用 cache requirement 都得到满足.

cache 可以通过多种机制了解 cached response 的当前有效性. 如果 cached response 的 age 尚未超过其 freshness lifetime, 则该 response 是 "fresh". 反之, 如果 cached response 在 cache 中停留的时间已经足以达到或超过其 freshness lifetime, 则该 response 是 "stale".

fresh response 可以用于满足后续 request, 而无需联系 origin server, 从而提升效率. 协议包含这些机制: origin server 分配显式 freshness lifetime 的机制, 未设置显式 lifetime 时计算 heuristic freshness lifetime 的机制, 以及 cached response 变 stale 后通过 validation 延长其 freshness lifetime 的机制.

分配 freshness 的主要机制是 origin server 通过 Expires header field (Section 5.3) 或 max-age response directive (Section 5.2.2.8) 发送显式 expiration time. 一般来说, origin server 会分配足以满足 response 所有预期用途的显式 expiration time. 可以给出较宽松的 lifetime, 以允许 cache 频繁重用; 如果已知内容会定期变化, 则可以给出较保守的 lifetime.

当不存在显式 expiration time 时, cache MAY 计算 heuristic expiration time. 对于本规范未定义其可缓存性的 status code 的 response, cache MUST NOT 使用 heuristic expiration time, 例如 300, 301 或 308 以外的 redirect (见 [RFC7231] Section 6), 或者当 status code 表示错误时, 即 status code 大于或等于 400.

当 stored response stale 时, cache 通常使用 validation ([RFC7232] 中定义的 conditional request) 来更新 stored response, 并避免不必要地传输 representation data. 如果 cache 的配置允许 disconnected operation, 或者 Cache-Control 中的 request directive 允许 (Section 5.2), stale response 仍然可以在不进行 validation 的情况下使用.