当前位置:网站首页>Understand HTTP cache in 30 minutes
Understand HTTP cache in 30 minutes
2022-07-19 02:35:00 【Insomnia book】
One 、 Reading guide
Whether you're the front end , Or the back end , You can't avoid meeting and in your daily work HTTP Cache related issues . For example, it is found that the file that should be updated is not updated because of the cache , The usual practice is to timestamp the file path of the requested resource , Simple, crude and effective , But as a aspiring programmer , We shouldn't just stop at solving the problem OK At the level of , Further more , Think about whether there is a better solution ? For different scenes 、 Different types of resources , Is there a more efficient cache design ? I hope that after reading this article , Be able to HTTP A deeper and more comprehensive understanding of caching , Master them , It will be helpful for us to solve some complex daily problems .
Two 、HTTP What is caching ?
Suppose there is no cache , Just imagine , When a client accesses an original server page multiple times , The server transmits the same document multiple times , One client at a time . Some of the same content will be transmitted over and over the network . These redundant data transmissions will exhaust expensive network bandwidth , Reduce the transmission speed , aggravate Web Server load .
With caching , You can keep a copy of the first server response , Subsequent requests can be handled by cached copies , This can reduce those inflows / Out of the original server 、 Wasted duplicate traffic . By reusing previously acquired resources , Can significantly improve the performance of websites and Applications . besides , Other collateral benefits are also obvious , For example, it can reduce the network request time 、 Reduce bandwidth consumption 、 Lifting performance .
Like what? HTTP The response is cached by the client ?
- By default , The request method is as follows: GET、HEAD The response content of is cacheable , In the case of including freshness information ,POST The response content can also be cached ;
- By default , Response code such as 200、206、300、301、302、404 And so on can be cached ;
- The response header and request header do not indicate that caching is not used , Such as Cache-Control: no-store.
3、 ... and 、 What are private cache and shared cache ?
- Private cache
A cache for one client only , That is, the cache on the client is for your own use only , It usually only exists on clients such as browsers .
The first request initiated by each client is processed by the source server . When the cache is in effect , Subsequent requests from the same client will not even be sent , Instead, the service is provided by the local cache .
- Shared cache
A cache that can be used by multiple clients , Usually rely on proxy servers .
The first request initiated by the client accesses the source server through the proxy server , After the cache takes effect, it will be stored in the proxy server , The same request initiated by subsequent clients , The proxy server provides caching services , Shared caching can reduce the pressure on the source server .
The content related to the concept is finished , We're starting to go deeper HTTP The specific working mechanism of cache .
Four 、HTTP Cache processing flow
Before the official start , Let's understand from a macro perspective through the following picture HTTP Cache processing flow ( Execution order ).
Please study this picture carefully , It is very important , Many of the contents below are extended explanations for a link in the figure .
For websites , Caching is an important part of high performance , Cache needs to be configured properly , Because not all resources are permanent .Cache-Control The header can control the cache ,Cache-Control Can be used for HTTP Request and response , Support multiple instructions , Separated by commas :
| Ask for the first | describe |
|---|---|
| Cache-Control: no-store | Do not use cache |
| Cache-Control: no-cache | Before using the cache , Regardless of whether the local copy has expired , You need to request the source server to verify ( Negotiate cache validation ) |
| Cache-Control: max-age= second | Set the maximum age of cache storage , Beyond this period, the cache is considered expired , Time is relative to the requested time |
| Cache-Control: max-stale= second | The client is willing to receive an expired resource . You can set an optional number of seconds , Indicates that the response cannot be out of date for more than the given time |
| Cache-Control: min-fresh= second | The client wants to get a response that can keep its latest state for a specified number of seconds |
| Cache-Control: s-maxage= second | Same as max-age, Only for shared cache |
| Cache-Control: private | Private cache , The response can only be cached by a single client |
| Cache-Control: public | Shared cache , That is, the cache provided by the cache proxy server , The response can be cached by multiple clients |
| Cache-Control: must-revalidate | If the local copy has not expired , Can continue to be used by the client , There is no need to verify with the source server again ; If the local copy has expired ( For example, it has exceeded max-age), Before successfully verifying with the source server , The cache cannot respond to subsequent requests with this resource |
| Cache-Control: proxy-revalidate | Same as must-revalidate, Only for shared cache |
Cache-Control Several instructions are particularly confusing , You can't take meaning from words . such as no-cache, It doesn't mean you can't use cache, The client will still send the with no-cache Cache your response , Just don't use the cache directly every time , But first go to the server to verify , So actually no-cache The right name is must-revalidate. If you want the client to not cache the response at all , Should use the no-store, with no-store The response will not be cached to any disk or memory , It's the real no-cache
- How to detect whether the cache is fresh ?
Service life :Cache-Control: max-age= second
We can specify the maximum lifetime of a cache , Relative to cache creation time , If the maximum service life is exceeded , It means that the cache is no longer fresh
Cache-Control: max-age= second
Take a chestnut :
As shown in the figure , When in the response header Cache-Control Of max-age Set to 10 seconds , It means starting with the first request , The cache validity of this resource is 10 second ,10 Requesting the resource again within seconds will read from the cache ; exceed 10 second , Then the client sends a request to the source server , The validity of the cache starts counting again
- Expiration date :Expires
We can also specify an absolute expiration date , If the expiration date has passed , It means that the cache is no longer fresh
Expires: Expiration date
Expires yes HTTP/1.0 The first ,Cache-Control yes HTTP/1.1 The first ,Expires The first and Cache-Control:max-age The first thing I did was essentially the same , But because of Cache-Control The first part uses relative time instead of absolute date , So I prefer to use newer Cache-Control The first one . The absolute date depends on the correct setting of the computer clock
5、 ... and 、HTTP Server revalidation
- What is server-side revalidation ?
Just because a cached document has expired doesn't mean it's actually different from the document on the source server , This just means checking with the server , Note that the cache needs to ask the source server whether the document has changed , This situation is called “ Server revalidation ”
There are two situations for server-side revalidation : - The server documentation has changed : The cache will get a new copy of the document , And store it in the location of the old document , Then send the document to the client ;
- The server-side document has not changed : The cache just needs to get the new header , Include a new expiration date , And update the first part of the cache , The document can still be used
Caching does not have to verify the validity of the document for each request —— It only needs to be revalidated with the server when the document expires - How to revalidate the server ?
Modify the date and then verify :If-Modified-Since: The most common cache revalidation header is If-Modified-Since
If-Modified-Since: Date last modified
It means , Only when resources have changed since a certain date , The server will execute the request :
- If after the specified date , The document has been modified ,If-Modified-Since The condition is true , Usually the request will execute successfully . The document with the new header will be returned to the cache , The first new one, among other things , It also includes a new expiration date
- If after the specified date , The document has not been modified , Conditions are false , The server will return a 304 NotModified response message , The body of the document will not be returned
- If-Modified-Since The value of is the last returned by the server last-modified Value . If the content is modified during this period , The last modification date will be different , The source server will send back the new document . otherwise , The server will think that the last modification date of the cache matches the current last modification date of the server document , Will return a 304 NotModified Respond to

In some cases, it is not enough to use only the last modification date for revalidation , such as : - Some documents may be rewritten periodically ( such as , Write... From a background process ), But the actual data is often the same . Although the content has not changed , But the date of revision will change
- Some documents may have been modified , But the changes don't matter , There's no need to have the world's caches reload data ( Such as changes in spelling or notes )
- Some servers can't accurately determine the last modification date of their pages
- Some servers provide documents that change in milliseconds ( such as , Real time monitor ), For these servers , A one second modification date may not be enough
To solve these problems ,HTTP Allow users to label entities as they are called (ETag) Of “ Version identifier ” Compare
If there is an entity tag in the cache ETag, It will revalidate with the source server , If the entity tag on the server still matches it , Will return a message 304 NotModified Respond to . If the entity tag on the server has changed , The server will be in a 200 OK New content and corresponding new... Are returned in the response Etag
If-None-Match The value of is the last returned by the server ETag Value . stay ETag Add... Before the value of W/ Prefix representation can adopt relatively loose algorithm
When and when to use the validation tag again ?
If the server returns a ETag The first one , The client must use If-None-Match Entity tag revalidation ;
If the server returns a Last-Modified The first one , The client can use it If-Modified-Since Modify the date and then verify ;
If ETag and Last-Modified provide , The client should use both revalidation schemes at the same time
If HTTP/1.1 The request received by the cache or server has both If-Modified-Since, And with If-None-Match, So only when both of these conditions are met , Before returning 304 Not Modified Respond toending
Thank you for reading this patiently ,HTTP Caching is not very simple ? Put this to use , If you have mastered all the above , Cache related problems encountered in daily work , I believe you can handle it easily
For special situations at work , How to make an efficient cache design , I believe there is an answer . Limited to space ,HTTP Some knowledge of caching is not exhaustive , You can find more detailed references on the Internet to learn them —— When you need them
边栏推荐
- 网络层协议和IP数据包的格式(详解)
- [hdrp HD rendering pipeline] create hdrp project and upgrade the built-in pipeline project to hdrp project
- postman的json脚本转jmeter的jmx脚本
- Known preorder traversal, preorder traversal, find the sequence traversal of the tree
- 【瑞吉外卖⑩】Linux 粗略学习 & Redis 粗略学习
- Stl--queue container
- Static routing (detailed)
- UE4 笔记
- Array transformer blocking idea
- Software testing technology interim testing summary | software testing foundation & Executive testing & test design and development
猜你喜欢

Summary of tree and heap knowledge points

Buaaos-lab0 experimental report

Chapter 2 - system control principle - > classical control theory

bugku---game1

After unity imports the FBX model, the rotation and position of the object will change automatically at runtime

In depth performance test data analysis

Attack and defense world - easytornado notes

Visual studio 2019-qt debugging

MeterSphere基于JMeter分布式性能压测平台

Software testing technology interim testing summary | software testing foundation & Executive testing & test design and development
随机推荐
jmeter连接数据库的方法
[tools] unity2d character controller, which controls 2D players to move and jump in four directions and horizontal directions
[unity development tips] unity packs the EXE on the PC side and compresses and packs it into an EXE file
[tools] unity screen drawing line, unity screen drawing Hsj drawing tool
Chapter 2 - system control principle - > classical control theory
【Unity编辑器扩展】快速定位资源和脚本的指定文件和路径
Test points of login function
Jmeter响应时间测试组件&多接口并发
next数组-循环节
[hdrp HD rendering pipeline] create hdrp project and upgrade the built-in pipeline project to hdrp project
How to do a good job of test case review
Nmon使用方法
Performance bottleneck positioning XMIND
深入性能测试数据分析
Jstat命令查看jvm的GC情况
How to use nmon
UE4 notes
网络一般知识(详)
The solution to the bounce and offset of unity3d game characters when jumping to the ground
Detailed explanation of caduceus project of metauniverse public chain (I): project concept and technical framework of caduceus metaverse protocol