我可以缓存这个吗?
此库说明何时可以从缓存中重用回复, 同时考虑到 HTTP RFC 7234/9111 导弹 用于用户代理和共享缓存的规则.
它还执行 stale-if-error 财务报告和审定财务报表 stale-while-revalidate 从 RFC 5861 (韩语)。 。 。 .
它知道很多棘手的细节 比如.. Vary 头,代理重新验证,和认证的回复.
基本用途
CachePolicy 是一个元数据对象,意在存储在缓存中,它将跟踪响应的缓存性.
HTTP 响应的可缓存性取决于它是如何请求的,所以两者都是 request 财务报告和审定财务报表 response 需要制定该政策.
const policy = new CachePolicy(request, response, options);
if (!policy.storable()) {
// throw the response away, it's not usable at all
return;
}
// Cache the data AND the policy object in your cache
// (this is pseudocode, roll your own cache (lru-cache package works))
letsPretendThisIsSomeCache.set(
request.url,
{ policy, body: response.body }, // you only need to store the response body. CachePolicy holds the headers.
policy.timeToLive()
);
// And later, when you receive a new request:
const { policy, body } = letsPretendThisIsSomeCache.get(newRequest.url);
// It's not enough that it exists in the cache, it has to match the new request, too:
if (policy && policy.satisfiesWithoutRevalidation(newRequest)) {
// OK, the previous response can be used to respond to the `newRequest`.
// Response headers have to be updated, e.g. to add Age and remove uncacheable headers.
return {
headers: policy.responseHeaders(),
body,
}
}
// Cache miss. See revalidationHeaders() and revalidatedPolicy() for advanced usage.
这也许令人惊讶,但单靠HTTP反应是不够的 新鲜 满足一个请求。 它可能需要匹配请求头 Vary。即使匹配的新响应,如果新请求限制缓存性等,也可能仍然无法使用.
关键方法是 satisfiesWithoutRevalidation(newRequest),检查是否 newRequest 符合原始请求,以及是否符合所有缓存条件.
构造选项
请求和答复必须有 headers 属性,小写后所有标题. url, (中文(简体) ), status 财务报告和审定财务报表 method 是可选的( 默认是任意 URL, 状态) 200,以及 GET 页:1.
const request = {
url: '/',
method: 'GET',
headers: {
accept: '*/*',
},
};
const response = {
status: 200,
headers: {
'cache-control': 'public, max-age=7234',
},
};
const options = {
shared: true,
cacheHeuristic: 0.1,
immutableMinTimeToLive: 24 * 3600 * 1000, // 24h
ignoreCargoCult: false,
};
若为 options.shared 实值 true (默认),然后从共享缓存(即:. private 不可缓存和 s-maxage (见E/CN.4/Sub.2/2003/L.10和Add.1和2) 若为 options.shared 实值 false,然后从单个用户缓存(即:. private 可缓存和 s-maxage 页:1. shared: true 建议HTTP客户端.
options.cacheHeuristic 是作为后退缓存持续时间的响应年龄的一小部分。 默认为0.1 (10%),例如如果一个文件有100天没有被修改,它会被缓存100*0.1=10天.
options.immutableMinTimeToLive 是数以毫秒作为缓存回复的默认时间 Cache-Control: immutable。注意: 每个RFC 这些会变得僵化,所以 max-age 仍然覆盖默认值.
若为 options.ignoreCargoCult 如果非标准, 常见的防缓存指令将被完全忽略 pre-check 财务报告和审定财务报表 post-check 有指令存在。 这两种无用指令最常见于坏 Stack Overflow 答案和PHP的"会话限制器"默认.
storable()
回返 true 如果响应可以存储在缓存中。 如果是这样 false 您必须不存储请求或回复.
satisfiesWithoutRevalidation(newRequest)
使用这种方法来检查缓存响应在新请求的上下文中是否仍然新鲜.
如果它回来了 true,然后给定 request 匹配此缓存策略已创建的原始响应, 并且该响应无需联系服务器即可被再使用 。 注意,没有更新,旧的响应无法返回 responseHeaders()。 。 。 .
如果它回来了 false,则该响应可能根本不匹配(例如它用于不同的URL或方法),或可能需要先被刷新(参见 revalidationHeaders()) (中文(简体) ).
responseHeaders()
返回更新,过滤的一组响应头,以返回接受缓存响应的客户端. 此功能是必需的, 因为代理 MUST 总是去除 hop- by- hop headers( 例如 TE 财务报告和审定财务报表 Connection) 和更新回复 Age 以避免缓存时间翻倍.
cachedResponse.headers = cachePolicy.responseHeaders();
timeToLive()
建议时间在 毫秒 用于此缓存条目可能有用的时间。 这不是新鲜的,所以总是检查 satisfiesWithoutRevalidation()。这一次可能比答复的时间更长 max-age 允许 stale-if-error 财务报告和审定财务报表 stale-while-revalidate。 。 。 .
之后(何时) timeToLive() <= 0)该响应在某些情况下可能仍然可用,例如,如果客户端可以明确允许呆滞响应.
toObject()编号 :fromObject(json)
你会想储存 CachePolicy 对象与缓存的响应. obj = policy.toObject() 给出一个简单的 JSON 序列大小对象. policy = CachePolicy.fromObject(obj) 从中创造一个实例.
完成使用
evaluateRequest(newRequest)
返回告诉下一步要做什么的对象——可选 revalidation选择 response 从缓存。 其中任何一个都会存在 两者可能同时出席.
{
// If defined, you must send a request to the server.
revalidation: {
headers: {}, // HTTP headers to use when sending the revalidation response
// If true, you MUST wait for a response from the server before using the cache
// If false, this is stale-while-revalidate. The cache is stale, but you can use it while you update it asynchronously.
synchronous: bool,
},
// If defined, you can use this cached response.
response: {
headers: {}, // Updated cached HTTP headers you must use when responding to the client
},
}
示例
let cached = cacheStorage.get(incomingRequest.url);
// Cache miss - make a request to the origin and cache it
if (!cached) {
const newResponse = await makeRequest(incomingRequest);
const policy = new CachePolicy(incomingRequest, newResponse);
cacheStorage.set(
incomingRequest.url,
{ policy, body: newResponse.body },
policy.timeToLive()
);
return {
// use responseHeaders() to remove hop-by-hop headers that should not be passed through proxies
headers: policy.responseHeaders(),
body: newResponse.body,
}
}
// There's something cached, see if it's a hit
let { revalidation, response } = cached.policy.evaluateRequest(incomingRequest);
// Revalidation always goes first
if (revalidation) {
// It's very important to update the request headers to make a correct revalidation request
incomingRequest.headers = revalidation.headers; // Same as cached.policy.revalidationHeaders()
// The cache may be updated immediately or in the background,
// so use a Promise to optionally defer the update
const updatedResponsePromise = makeRequest(incomingRequest).then(() => {
// Refresh the old response with the new information, if applicable
const { policy, modified } = cached.policy.revalidatedPolicy(incomingRequest, newResponse);
const body = modified ? newResponse.body : cached.body;
// Update the cache with the newer response
if (policy.storable()) {
cacheStorage.set(
incomingRequest.url,
{ policy, body },
policy.timeToLive()
);
}
return {
headers: policy.responseHeaders(), // these are from the new revalidated policy
body,
}
});
if (revalidation.synchronous) {
// If synchronous, then you MUST get a reply from the server first
return await updatedResponsePromise;
}
// If not synchronous, it can fall thru to returning the cached response,
// while the request to the server is happening in the background.
}
return {
headers: response.headers, // Same as cached.policy.responseHeaders()
body: cached.body,
}
刷新 stale 缓存( 重新验证)
当缓存响应已过期时,可以通过向源服务器提出请求再次被刷新. 服务器可能以状态304(没有被修改)响应,而不再次发送响应正文,节省带宽.
以下方法有助于有效和正确地进行更新.
revalidationHeaders(newRequest)
返回更新,过滤的请求信头集,以发送到源服务器,以检查缓存响应是否可以被再利用. 这些信头允许源服务器返回状态 304 表示响应仍然新鲜. 所有与卡通无关的车头都是按原样通过.
从源服务器上更新缓存时使用此方法 。 也可查阅 evaluateRequest(newRequest).revalidation.headers。 。 。 .
updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest);
revalidatedPolicy(revalidationRequest, revalidationResponse)
使用这种方法在从源服务器收到新响应后更新缓存. 它返回一个带有两个键的对象:
policy-一个新的CachePolicy并更新 HTTP 头来自revalidationResponse。您总是可以替换旧的缓存CachePolicy与新的一个.modified——布尔表示响应正体是否改变,您应当使用服务器发送的新响应正体.- 若为
true,您应当使用新的响应正文,并且可以将旧的缓存响应替换为更新的响应. - 若为
false,那么你应该重新使用旧的缓存反应机体。 要么收到有效的304没有修改的答复,要么发生错误stale-if-error允许返回缓存.
- 若为
哟,FRESH

用于
- 图像 optim API, (中文(简体) ), 调制相机, (中文(简体) ), 可缓存请求 (单位:千美元)已经, (中文(简体) ), npm/ registry-fach (英语), (中文(简体) ), 包括:.
- 此库的粗版。 。 。 .
已执行
Cache-Control反应头和所有的怪异.Expires检查坏钟.Pragma响应头.Age响应头.Vary响应头.- 状态和方法的默认缓存性 .
- 要求提供陈旧的数据.
- 逐一过滤 hop-by-hop headers.
- 基本重新验证请求
stale-if-errorstale-while-revalidate
未执行
- 合并范围请求,
If-Range(但正确支持它们为不可取) - 更改多重表述
信任服务器 Date
根据 RFC ,缓存应当考虑服务器提供之间的时间 Date 以及收到答复的时间。 RFC授权的行为造成了两个问题:
- 设置错误的时区服务器可能会为缓存年龄增加数小时(或者更多,如果时钟完全错误).
- 即使是合理正确的时钟 也可能关闭几秒钟,打破
max-age=1trick (用于高流量服务器上的反向代理).
此库的前几个版本如果"太不准确",可以忽略服务器日期. 支持 max-age=1 {\fn黑体\fs22\bord1\shad0\3aHBE\4aH00\fscx67\fscy66\2cHFFFFFF\3cH808080}图书室也得忽略如此准确的日期 没有任何意义可以选择只信任一点不准确的日期,因此这个库不会信任任何服务器日期. max-age 将从收到答复时而不是从发出答复时开始解释。 这只会影响 RFC 1149网络。 。 。 .