当前位置:网站首页>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
NetWorkThe 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=31536000From the time the request was initiated +31536000Seconds later , Will expireCache-Control: must-revalidateIn any case where the cache expires , Must initiate a request for revalidationCache-Control: s-maxage=60Same as max-age It works the same , From the time the request was initiated +60Seconds 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-storeNothing is cached , No forced caching , Negotiation caching is also not used .Cache-Control: no-cacheWhether to use local cache or not requires negotiation cache to verify the decision . UseEtagperhapsLast-ModifiedField to control the cache .Cache-Control:max-age=31536000,max-stale=60From the time the request was initiated +31536000second +60Seconds later , Cache will be invalidated .max-staleIndicates the maximum allowable expiration time , The unit is seconds .Cache-Control:max-age=31536000, min-fresh=60From the time the request was initiated +31536000second -60Seconds later , Cache will be invalidated .min-freshIt 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-SinceOnly 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-ModifiedIt is the server response headerResponse HeadersIn the field .If-Modified-SinceIs the client request headerRequest HeadersIn the field .If-Modified-SinceIt can only be used inGETorHEADIn request .- When and
If-None-MatchWhen they come together ,If-None-MatchHigher priority .If-Modified-SinceWill 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-cacheAndCache-Control: max-age=0max-age=0Indicates that the resource is already in 0 Seconds after expired , Negotiation strategy is required . therefore , andCache-Control: no-cacheequally .
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
边栏推荐
- PHP realizes wechat applet face recognition and face brushing login function
- What is the difference between IP address and physical address
- 目标跟踪常见训练数据集格式
- Excessive dependence on subsidies, difficult collection of key customers, and how strong is the potential to reach the dream of "the first share of domestic databases"?
- Limit of total fields [1000] in index has been exceeded
- [excelexport], Excel to Lua, JSON, XML development tool
- 23. 合并K个升序链表-c语言
- hellogolang
- Notification uses full resolution
- spark调优(三):持久化减少二次查询
猜你喜欢

Rongyun won the 2022 China Xinchuang digital office portal excellence product award!

Talk about the cloud deployment of local projects created by SAP IRPA studio

预测——灰色预测

1亿单身男女“在线相亲”,撑起130亿IPO

【C 语言】 题集 of Ⅹ

Xingruige database was shortlisted as the "typical solution for information technology application and innovation in Fujian Province in 2021"

Numpy --- basic learning notes

Step by step monitoring platform ZABBIX

2022 the 4th China (Jinan) International Smart elderly care industry exhibition, Shandong old age Expo

Three. JS introductory learning notes 19: how to import FBX static model
随机推荐
如何快速检查钢网开口面积比是否符合 IPC7525
深度之眼(六)——矩阵的逆(附:logistic模型一些想法)
统计学习方法——感知机
Leetcode-231-2的幂
JS 模块化
Bidding announcement: Fujian Rural Credit Union database audit system procurement project (re bidding)
Unity3D_ Class fishing project, control the distance between collision walls to adapt to different models
U3D_ Infinite Bessel curve
Laravel5.1 路由 -路由分组
Description of vs common shortcut keys
用手机在通达信上开户靠谱吗?这样炒股有没有什么安全隐患
prometheus api删除某个指定job的所有数据
[flower carving experience] 15 try to build the Arduino development environment of beetle esp32 C3
23. 合并K个升序链表-c语言
"The" "PIP" "entry cannot be recognized as the name of a cmdlet, function, script file, or runnable program."
95. (cesium chapter) cesium dynamic monomer-3d building (building)
Logback日志框架第三方jar包 免费获取
js中复选框checkbox如何判定为被选中
Leetcode-136-只出现一次的数(用异或来解答)
PHP实现执行定时任务的几种思路详解