Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTTP缓存策略 #48

Open
varHarrie opened this issue Dec 2, 2022 · 0 comments
Open

HTTP缓存策略 #48

varHarrie opened this issue Dec 2, 2022 · 0 comments
Labels
Milestone

Comments

@varHarrie
Copy link
Owner

varHarrie commented Dec 2, 2022

image

一、强制缓存

1、Expires(已废弃)

服务器在HTTP响应头中返回Expires字段,指定一个过期时间(如Thu, 01 Dec 2022 15:46:39 GMT),在下次请求之前对比本地当前时间是否在过期时间之前,如符合,则从内存或硬盘中读取缓存,不去请求服务器资源。

缺陷:过度依赖本地时间,如果本地时间与服务器时间不同步,则可能导致资源无法缓存或永远缓存的问题。

2、Cache-Control

服务器在HTTP响应头中返回Cache-Control字段,包含以下属性:

  • no-store:不进行任何缓存策略
  • no-cache:跳过强制缓存策略,进行协商缓存策略,与no-store互斥
  • public:允许资源被代理服务器缓存
  • private:仅允许资源被浏览器缓存,与public互斥
  • max-age:浏览器缓存时长,单位秒
  • s-maxage:代理服务器缓存时长,单位秒,仅public时有效

举例:

Cache-control:max-age=60000,s-maxage=120000,public

通常使用Cache-Control代替Expires,因为前者时HTTP 1.1的,如果要考虑兼容性,仍可使用Expires。

二、协商缓存

1、Last-Modified / If-Modified-Sine

服务器在HTTP响应头中返回Last-Modified字段,即当前文件的修改时间,浏览器会在下一次请求时携带If-Modified-Sine字段,值为上次的Last-Modified,服务端判断时间如果时间一致,则返回304状态码,前端直接使用上次缓存的资源。

缺陷:如果文件内容没有修改,但修改时间已经更新(如只修改了文件名),这种情况仍会导致缓存失效。或者文件在几百毫秒内完成了再次修改,因为记录的最小单位是秒,依然会被认为没有修改。

2、ETag / If-None-Match

服务器在HTTP响应头中返回ETag字段,即当前文件指纹,浏览器在下次请求时携带If-None-Match字段,值为上一次的ETag,服务端判断如果一致,则返回304状态码,前端直接使用上次缓存的资源。

缺点:计算文件指纹意味着服务端需要有更多开销;ETag存在强校验、弱校验,强校验情况下生成的哈希码会深入到文件的每个字节,能够最大程度进行精确判断,但同时也意味着更大的性能消耗,弱校验整体速度比较快,但也意味着准确率较低,降低协商缓存的有效性。

三、针对不同文件采取不同缓存策略

1、文件名包含哈希码的静态文件:采用Cache-Control强制缓存。

2、index.html:采用协商缓存,具体看服务器性能、文件修改情况。

@varHarrie varHarrie added the HTTP label Dec 28, 2022
@varHarrie varHarrie added this to the Posts milestone Dec 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant