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

[2018-08-15]: HTTP的缓存策略 #3

Open
Lemonreds opened this issue Aug 15, 2018 · 0 comments
Open

[2018-08-15]: HTTP的缓存策略 #3

Lemonreds opened this issue Aug 15, 2018 · 0 comments
Labels

Comments

@Lemonreds
Copy link
Owner

HTTP的缓存策略

什么是缓存

简单来说,缓存就是一份指定资源的拷贝,在下次请求同一份资源时,能利用缓存进行复用,而不是重新去请求服务器再次下载一份新的资源。

缓存的好处

  • 提升网站性能
  • 减少请求带宽
  • 缓解服务器压力

HTTP的两种缓存策略

强缓存

利用http返回头字段来控制,表示资源的最大缓存时间,由于时间是由服务器生成的,本地客户端确认的时候会产生误差。

  • Cache-Control 报头,可选参数如下
    • private 客户端可以缓存资源
    • public 客户端/代理服务器都可以缓存资源
    • max-age: ?s 缓存内容的最大有效时间
    • no-cache 允许使用缓存 但需要确认缓存的有效性
    • no-store 不缓存资源

如:

Cache-Control: public, max-age=6400

或者

  • Expires 报头,由服务器返回的资源到期时间 GMT 格式.

如:

Expires: Fri, 8 Aug 2018 17:09:00 GMT

协商缓存

判断是否可以使用缓存,客户端第一次请求资源时,服务器会返回缓存标识与数据到客户端本地,再次请求资源时,客户端会把缓存标识发送到服务端确认资源的有效性,当缓存失效时,返回200及新的资源内容,当缓存有效时,返回304(Not Modified ),表示资源没有更新,可以使用缓存。

  • Last-Modified / If-Modified-Since 资源时间上的对比
    • Last-Modified 服务器响应请求时,告知资源的最后修改时间
    • If-Modified-Since 客户端再次请求时,发送上一次接收到的时间 与服务器进行资源的有效性对比

如:

Last-Modified: Fri, 8 Aug 2018 17:09:00 GMT
  • Etag / If-None-Match 资源内容上的对比
    • Etag 服务器响应请求时,告知资源的唯一内容标识
    • If-None-Match 客户端再次请求时,发送接收到的内容标识与服务器进行资源的有效性对比
E-tag: xxxxxxxxx

注意: 当强缓存不在时间内时,才会执行协商缓存策略,强缓存的优先级更高,因为强嘛。

@Lemonreds Lemonreds added the HTTP label Aug 15, 2018
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