当前位置:网站首页>3000 words speak through HTTP cache
3000 words speak through HTTP cache
2022-07-07 16:25:00 【I'm Leon】
summary
This paper starts from HTTP Cache policy
For entrance , Explain HTTP Caching in browser applications .
Article by Strong cache
、 Negotiate the cache
and Heuristic cache
Three categories , In depth analysis .
HTTP Cache policy
HTTP Caching is divided into three strategies :
- Storage strategy
- Expiration strategy
- Comparison strategy ( Also called negotiation strategy )
Storage strategy
Storage strategy , Used to decide HTTP Response content , Whether it can be cached to the client .
Cache-Control
The head of the max-age
、no-cache
、no-store
、public
、private
、s-maxage
, Use storage policies , To indicate whether the resource file can be cached .
Expiration strategy
Expiration strategy , Used to determine whether the client can read file data directly from the local cache , There is no need to initiate HTTP request .
Response header contains Cache-Control: public
The file of , Although it will be cached , However, it is not clear whether the current document is within the period of validity , So other fields are needed “ Expiration strategy ”.
Strongly cached Expires
Field , Just use “ Expiration strategy ” Define the validity period of the cache file . by means of , The browser can determine whether to initiate HTTP request .
Response header contains Cache-Control: max-age=<seconds>
The file of , Storage policy and expiration policy .
Specific strategy application , You can refer to the following Cache-Control
chapter .
Comparison strategy
Identify the data of the local cache file , Send it to the server for verification , Determine whether the file is valid . This strategy , It's called comparison strategy , Also called negotiation strategy .
Comparison strategy , For negotiating cache scenarios , The corresponding field is :
- Last-Modified and If-Modified-Since
- ETag and If-None-Match
for example :
ETag
Used to store the hash value of the cache file .
When the browser needs to judge whether the current cache file is valid , Need to put ETag
Put the value of into the request header If-None-Match
Field , Send to server .
After the server receives the request , contrast If-None-Match
Whether the value in is consistent with the value in the latest file , To decide whether to use caching .
When the two values are consistent , Then return to HTTP Status code 304, Tell the browser , Local cache files can be used .
When the two values are inconsistent , Then return to HTTP Status code 200, And bring the latest file back to the browser .
Specific strategy application , You can refer to the following Negotiate the cache
chapter .
Summary
Strong cache
Strong cache through field Expires
and Cache-Control
To control the validity of local cache files .
If the local cache is valid , The browser will not initiate HTTP request .
In the browser console
NetWork
The expression in is :200 OK (from disk cache)
perhaps200 OK (from memory cache)
paraphrase
200 OK (from disk cache)
HTTP Status code 200, The cached file is read from the hard disk200 OK (from memory cache)
HTTP Status code 200, The cached file is read from memory
Strongly cached fields
Field | Protocol version | Cache type | Response head | Request header |
---|---|---|---|---|
Expires | HTTP1.0 | Strong cache | ️ | |
Cache-Control | HTTP1.1 | Strong cache | ️ | ️ |
HTTP1.1 Field Priority ratio HTTP1.0 Field height .
Expires
Expires
Indicates the expiration time of the cache , Time represents Server time .
If the local time is less than Expires
Time for , Within the validity period . The browser will read the cache directly , Will not initiate HTTP request .
Expires: Sun, 14 Jun 2020 02:50:57 GMT
shortcoming
Expires
Limited by local time , If the local time is modified , It may cause cache invalidation .
Cache-Control
Cache-Control
A special , Can be in Response head
and Request header
Use in . It provides different values , To define the cache policy .
Cache-Control
Is in all cache definition fields , The highest priority .
Cache-Control Field value | meaning | Storage strategy | Expiration strategy | Response head | Request header |
---|---|---|---|---|---|
max-age | Cache resources , But at the appointed time ( The unit is in seconds ) Post cache expiration | ️ | ️ | ️ | ️ |
no-cache | amount to max-age:0,must-revalidate That is, resources are cached , But the cache expires immediately , At the same time, the validity of resources will be forcibly verified during the next visit | ️ | ️ | ️ | ️ |
no-store | Requests and responses are not cached | ️ | ️ | ️ | |
public | Resources will be cached by clients and proxy servers | ️ | ️ | ||
private | Resources are cached only by clients , The proxy server does not cache | ️ | ️ | ||
s-maxage | rely on public Set up , Cover max-age, And only valid on proxy server | ️ | ️ | ️ | |
must-revalidation / proxy-revalidation | If the cache fails , Force a retransmission to the server ( Or agent ) Initiate validation ( because max-stale And other fields may change the expiration time of the cache ) | ️ | ️ | ||
max-stale | Within the specified time , Even if the cache is out of date , Resources are still available | ️ | ️ | ||
min-fresh | The cached resources should be kept fresh for at least a specified time | ️ | ️ | ||
only-if-cached | Return only cached resources , No access to the Internet , If there is no cache, return 504 | ️ | |||
no-transform | Force the proxy server not to convert resources , The proxy server is forbidden to Content-Encoding , Content-Range , Content-Type Field modification ( Therefore, the agent gzip Compression will not be allowed ) | ️ | ️ |
paraphrase
Cache-Control:max-age=31536000
From the time the request was initiated +31536000
Seconds later , Will expireCache-Control: must-revalidate
In any case where the cache expires , Must initiate a request for revalidationCache-Control: s-maxage=60
Same as max-age It works the same , From the time the request was initiated +60
Seconds later , Will expire .
Only works on the proxy server ( such as CDN cache ),s-maxage Priority over max-age, Only right public Caching works . Set up s-maxage, No settings public, The proxy server can also cache this resource .Cache-Control: no-store
Nothing is cached , No forced caching , Negotiation caching is also not used .Cache-Control: no-cache
Whether to use local cache or not requires negotiation cache to verify the decision . UseEtag
perhapsLast-Modified
Field to control the cache .Cache-Control:max-age=31536000,max-stale=60
From the time the request was initiated +31536000
second +60
Seconds later , Cache will be invalidated .max-stale
Indicates the maximum allowable expiration time , The unit is seconds .Cache-Control:max-age=31536000, min-fresh=60
From the time the request was initiated +31536000
second -60
Seconds later , Cache will be invalidated .min-fresh
It means that there should be at least N Second freshness , The unit is seconds .
When max-age And max-stale and min-fresh When used at the same time , Their settings take effect independently of each other , The most conservative caching strategy is always effective .
That is, which expiration time is the earliest , Just after this expiration time , Initiate a resource request , Verify with the server again .
Negotiate the cache
When the browser requests a resource , Missed the strong cache , And find the cache file locally , Then a request will be sent to the server , Verify that the local cache is valid .
If the local cache file is valid , The server responds to the request , return HTTP Status as :304(Not Modified)
, Without message body .
If the local cache file expires , The server responds to the request , return HTTP Status as :200
, And carry the resource entity data .
Negotiate cached fields
There are two types of negotiation cache fields :
- Last-Modified and If-Modified-Since
- ETag and If-None-Match
Field | Header type | Protocol version | Cache type |
---|---|---|---|
Last-Modified | Response( Response head ) | HTTP1.0 | Negotiate the cache |
If-Modified-Since | Request( Request header ) | HTTP1.0 | Negotiate the cache |
ETag | Response( Response head ) | HTTP1.1 | Negotiate the cache |
If-None-Match | Resquest( Request header ) | HTTP1.1 | Negotiate the cache |
HTTP1.1 Field Priority ratio HTTP1.0 Field height .
Last-Modified and If-Modified-Since
Last-Modified
Indicates the last modification date of the local file ( Accurate to seconds ).
When the browser initiates a resource request , The file's Last-Modified
value , Put in If-Modified-Since
in , Send it to the server , Ask the document after that date , Is there an update .
If you open and modify the cache file locally , Will lead to Last-Modified
The date was modified .
Here is an example :
- Response head
Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT
- Request header
If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT
shortcoming
- When editing cache files locally , The cache will fail .( Although the content may not be changed )
If-Modified-Since
Only second level modifications can be detected , If it is 1 I've changed N Time , The validity of the file cannot be judged .
Be careful
Last-Modified
It is the server response headerResponse Headers
In the field .If-Modified-Since
Is the client request headerRequest Headers
In the field .If-Modified-Since
It can only be used inGET
orHEAD
In request .- When and
If-None-Match
When they come together ,If-None-Match
Higher priority .If-Modified-Since
Will be ignored , Unless the server doesn't supportIf-None-Match
.
ETag and If-None-Match
ETag
Like the fingerprint of a document , Every time the content changes ,ETag
Values change .
When the browser initiates a resource request , The last file will be ETag
value , Put in If-None-Match
in , Send it to the server , Ask if the file is updated .
ETag
Values are compared using Weak comparison algorithm , That is, except that each byte of the two files is the same , The same content can also be considered the same . for example , If the generation time of two pages is different only in the footer , It can be considered that the two are the same .
for instance :
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
ETag: W/"0815"
among ,'W/'
( Case sensitive ) Said the use of Weak verifier .
Be careful
ETag
It is the server response header Response Headers
In the field .If-None-Match
Is the client request header Request Headers
In the field .
avoid “ collision in airspace ” And HTTP Status code 412
collision in airspace , It means that multiple people modify the same file at the same time , There is competition .
If the server receives everyone's save request , There will be a state of mutual coverage .
therefore , Need to rely on ETag value , Before preservation , Do some checks , To avoid this .
When you need to modify or upload files , contains If-Match
head ( ETag value ) Of POST
request , It will be sent to the server .
If-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"
If the file hash value of the server is the same as If-Match
The values of the headers are not equal , Then the supporting documents have been modified .
In this case , The server can return HTTP Status code 412 Precondition Failed
( Precondition failed ) Indicates a client error , Reject processing request .
Heuristic cache
There is no Expires
, Cache-Control: max-age
, or Cache-Control:s-maxage
Field , And set up Last-Modified
, Then the browser will adopt one by default Heuristic algorithms .
Heuristic caching algorithm
Take the response header Date value - Last-Modified value
The result of 10% As cache time .
Details can be viewed Caching in HTTP In the introduction , The author intercepts part of the original text as follows :
If none of Expires, Cache-Control: max-age, or Cache-Control: s- maxage (see section 14.9.3) appears in the response, and the response does not include other restrictions on caching, the cache MAY compute a freshness lifetime using a heuristic. The cache MUST attach Warning 113 to any response whose age is more than 24 hours if such warning has not already been added.
Also, if the response does have a Last-Modified time, the heuristic expiration value SHOULD be no more than some fraction of the interval since that time. A typical setting of this fraction might be 10%.
The calculation to determine if a response has expired is quite simple:
response_is_fresh = (freshness_lifetime > current_age)
Consolidation exercises
How to make browsers not cache static resources
- Browser disable cache ( Open console , Check no-cache), Open the page in browser privacy mode
- Set request header :
Cache-Control: no-cache, no-store, must-revalidate
- Put the version number on the requested resource
<link rel="stylesheet" type="text/css" href="../css/style.css?version=1.8.9"/>
- Some browsers support HTML Disable caching in
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/>
Request headers with the same function
Cache-Control: no-cache
AndCache-Control: max-age=0
max-age=0
Indicates that the resource is already in 0 Seconds after expired , Negotiation strategy is required . therefore , andCache-Control: no-cache
equally .
Reference resources
- If-Modified-Since
- CDN Cache understanding
- Understand thoroughly Http Caching mechanisms - Based on the three factor decomposition of cache strategy
- Browser cache mechanism analysis
Insist on originality , Output valuable articles !
friend , If the article helps you , Please give me encouragement in the following ways :
- While collecting , Don't forget to like this article
- GitHub Order one star
Recently, the author is sorting out the first e-book manuscript 《 Front end interview manual 》, Interested students can Order one star Pay attention to
边栏推荐
- Detailed explanation of several ideas for implementing timed tasks in PHP
- Usage of config in laravel
- Step by step monitoring platform ZABBIX
- How can laravel get the public path
- Laravel 服务提供者实例教程 —— 创建 Service Provider 测试实例
- What are compiled languages and interpreted languages?
- JS 模块化
- Apache Doris just "graduated": why should we pay attention to this kind of SQL data warehouse?
- Sysom case analysis: where is the missing memory| Dragon lizard Technology
- Good news! Kelan sundb database and Hongshu technology privacy data protection management software complete compatibility adaptation
猜你喜欢
星瑞格数据库入围“2021年度福建省信息技术应用创新典型解决方案”
Step by step monitoring platform ZABBIX
无法将“pip”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
SPI master RX time out interrupt
Vs tool word highlight with margin
spark调优(三):持久化减少二次查询
Logback logging framework third-party jar package is available for free
如何快速检查钢网开口面积比是否符合 IPC7525
Leetcode-231-2的幂
【Android -- 数据存储】使用 SQLite 存储数据
随机推荐
47_ Contour lookup in opencv cv:: findcontours()
JS中null NaN undefined这三个值有什么区别
Migration and reprint
How can laravel get the public path
hellogolang
Leetcode-231-2的幂
Dotween -- ease function
[excelexport], Excel to Lua, JSON, XML development tool
Limit of total fields [1000] in index has been exceeded
MySQL中, 如何查询某一天, 某一月, 某一年的数据
Prometheus API deletes all data of a specified job
Balanced binary tree (AVL)
平衡二叉树(AVL)
PHP realizes wechat applet face recognition and face brushing login function
Unity的三种单例模式(饿汉,懒汉,MonoBehaviour)
Three. JS introductory learning notes 19: how to import FBX static model
laravel中将session由文件保存改为数据库保存
Talk about the cloud deployment of local projects created by SAP IRPA studio
Laravel5.1 Routing - routing packets
删除 console 语句引发的惨案