当前位置:网站首页>HTTP cache policy, strong cache, negotiation cache
HTTP cache policy, strong cache, negotiation cache
2022-07-22 05:37:00 【Nineteen (drag on and on)】
HTTP Cache policy , Strong cache , Negotiate the cache
List of articles
1: The test file
Server side app.js:
let http = require('http');
let fs = require('fs');
let url = require('url');
let path = require('path');
http.createServer(function (req, rep) {
let pathname = url.parse(req.url).pathname;
let data = fs.readFileSync(path.normalize(__dirname + pathname,'utf-8'));
rep.end(data);
})
.listen(9090);
Here, first get the request url
, Then find the file by splicing the path , Your file may not be here .
You can also directly let data = fs.readFileSync(‘./test1.jpg’,'utf-8'));
stay app.js
Find the corresponding file relative to the directory .( Here is the use of synchronous read files )
And then execute node app.js
Start our server .
Client side index.html:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<img src="http://localhost:9090/test1.jpg" alt="test">
</body>
</html>
The directory looks like this :
2: Strong cache
2.1:Expires
Your format should look like this :Expires: Sun, 17 Jul 2022 14:10:48 GMT
http.createServer(function (req, rep) {
let pathname = url.parse(req.url).pathname;
let date = new Date();
date.setMinutes(date.getMinutes()+1);
rep.writeHead(200, {
'Expires' : date.toUTCString() });
let data = fs.readFileSync(path.normalize(__dirname + pathname,'utf-8'));
rep.end(data);
})
Here we set up 1 Minute strong cache , In a minute , There is no need to request the server .
Refresh index.html
View console , You can find that the corresponding head appears Expires
Field .
At this time, data is obtained from the cache .
but
Expires
There are shortcomings , The time it compares is related to the local system time , If the system time is adjusted , Cache invalidation may occur . High requirements for system and server time . To solve this problem , have access toCache-Control Relative time cache
solve .
2.2:Cache-Control
Cache-Control
Although it can be set Strong cache
, But by setting Cache-Control : no-cache
have access to Negotiate the cache
.
2.2.1:max-age
Set the maximum relative expiration time , Unit is second
.
http.createServer(function (req, rep) {
let pathname = url.parse(req.url).pathname;
rep.writeHead(200, {
'Cache-Control' : 'max-age=30' });
let data = fs.readFileSync(path.normalize(__dirname + pathname,'utf-8'));
rep.end(data);
})
Set up 30
Seconds after expired .
Refresh index.html
:
2.2.2:s-maxage
Its usage and max-age
identical , But it's setting proxy server
The cache time of .
2.2.3:public
public
usage :Cache-Control : 'public,max-age=3600'
Its function is Proxy server can cache
.
2.2.4:private
private
usage :Cache-Control : 'private,max-age=3600'
Its function is Individuals can cache , Proxy server cannot cache
.
The default is
private
2.2.5:no-cache
private
usage :Cache-Control : 'no-cache'
Set up no-cache
after , Before publishing cached copies , Forcing the cache to submit the request to the original server for validation ( Negotiate cache validation ).
2.2.6:no-store
Its function is Disable caching
.
3: Negotiate the cache
Negotiate the cache
Every time I'm going to Server side
Send a request , from Server side
To tell client
Whether to use cache .
If you use caching Server side
Need to return 304
State .
3.1:Last-Modified/If-Modified-Since
Server response :Last-Modified
The client sends :If-Modified-Since
Server side
Received If-Modified-Since
, from Server side
Compare whether the two times are the same , If different, return data , If the same, return 304
tell client
Use the cache .
http.createServer(function (req, rep) {
let pathname = url.parse(req.url).pathname;
let time = fs.statSync(path.normalize(__dirname + pathname)).mtime.toUTCString()
let ifMdifiedSince = req.headers['if-modified-since'];
if(ifMdifiedSince===time){
rep.statusCode = 304
rep.end()
return
}
rep.setHeader("Cache-Control",'no-cache');
rep.setHeader('Last-Modified' ,time);
let data = fs.readFileSync(path.normalize(__dirname + pathname,'utf-8'));
rep.end(data);
})
.listen(9090);
It can be found that only 113B
Memory .
3.1.1: Why does cache still occupy broadband ?
Negotiation caching is not about not sending requests , But after sending the request , from Server side
Determine whether to use cache for this result , But the request still arrived at our server . If the cache is confirmed , be Server side
Need to set up 304
State , Otherwise, do not set .
3.1.2: Test whether it is cached
Clear cache first :
Refresh the view :
Original image size 73.8kb
, But after caching, we only use 113B
.
Be careful :
Last-Modified
The minimum unit is seconds , If the difference time is less than1
second , Then the function fails .
3.2:Etag
Etag It is judged according to the unique fingerprint of the document , Every time you modify a file Fingerprints of documents
Will change .
More relevant knowledge :javascript get files sha-256,sha-384,sha-512 Abstract , Verify that the file has not been tampered with , Verify file consistency , Document security management , Calculate the MD5 value
Server return Etag
Response head .
The client automatically sends If-None-Match
head .
The server determines whether to cache , If caching , The server needs to return 304
State .
let http = require('http');
let fs = require('fs');
let url = require('url');
let path = require('path');
var crypto = require('crypto');
http.createServer(function (req, rep) {
let pathname = url.parse(req.url).pathname;
let data = fs.readFileSync(path.normalize(__dirname + pathname, 'utf-8'));
const hash = crypto.createHash('md5');
hash.update(data, 'utf8');
const md5 = hash.digest('hex');
let ifNoneMatch = req.headers['if-none-match'];
if (ifNoneMatch === md5) {
rep.statusCode = 304
rep.end()
return
}
rep.setHeader("Cache-Control", 'no-cache');
rep.setHeader('Etag', md5);
rep.end(data);
})
.listen(9090);
Our content has been cached , No picture is requested from server .
Be careful : although
Etag
It's solvedLast-Modified
Smallest unitsecond
The problem of , But calculating file fingerprint information consumes memory , thereforeEtag
It's not a complete replacement forLast-Modified
. So which one to use , We need to consider comprehensively according to the use scenario .
4: How to take into account the advantages of strong cache and negotiation cache at the same time
Now we know that Negotiate the cache
You need to send a request , But you can know the time of file change more accurately , Update our cache faster .
Strong cache
Although there is no need to send a request , However, it is impossible to know the changes of the document as soon as possible , Users may not get the latest content for a long time .
Is there a way , At the same time to realize There is no need to send a request to the server
But you can Get the latest content as soon as possible
Well ?
Want to achieve this demand , We need to set strong cache first .
let http = require('http');
let fs = require('fs');
let url = require('url');
let path = require('path');
http.createServer(function (req, rep) {
let pathname = url.parse(req.url).pathname;
let data = fs.readFileSync(path.normalize(__dirname + pathname, 'utf-8'));
rep.writeHead(200,{
'Cache-Control':'max-age=3600'});
rep.end(data);
})
.listen(9090);
When we update the file , We can add a file suffix .
such as : The document we requested is http://localhost:9090/test1.jpg
We can add a suffix , Change to http://localhost:9090/test1.jpg?t=123456
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<img src="http://localhost:9090/test1.jpg?t=123456" alt="">
</body>
</html>
This not only makes the cache strong , And when the file is updated , You can also send a request to get the latest files .
边栏推荐
- [JS foundation] use of random, floor and ceil methods in math
- Write it down once Net analysis of CPU explosion of an intelligent transportation background service
- The way to practice and fight strange things: promise introduction principle and common methods
- pdf. JS how to Preview PDF files of Base64 type
- 性能领域:你知道的越多,不知道的也就越多
- Computer postgraduate entrance examination database question bank
- ES6 从入门到精通 # 04:函数之默认值、剩余参数
- 这还不硬?你来打我!手把手教学!
- 服务器时间自动同步
- 蔚来「城市」探索之路
猜你喜欢
814. Binary tree pruning: simple recursive problem
pdf. JS how to Preview PDF files of Base64 type
低代码平台搭建跨部门沟通系统案例分析
OpenAI正式宣布DALL-E向100万个用户开放测试版
如何清理C盘
Microservice technology development
高度关注!2022开放原子开源峰会最新议程一览
2022.7.9暑假个人训练1-C . Clean up the Powers that Be
ES6 from getting started to mastering 06: arrow function this direction and precautions
China's mobile phones suffered a major setback for the first time, while Samsung and apple increased significantly
随机推荐
dried food! Nine details that you must know about high-speed goods
Yousi College | learn six sigma management from Sun Tzu's art of war
BGP基础配置,聚合,反射器
ES6 from getting started to mastering 05: extended operators and arrow functions of functions
推荐系统之ROC和AUC详解
When the cold winter of mobile phones comes, Samsung is forced to snipe Chinese mobile phones, and apple stands alone on the mountain to see the scenery
NFS shared storage service
手机寒冬到来,三星被迫狙杀中国手机,苹果独站山头看风景
HTTP缓存策略,强缓存,协商缓存
window 系统里 chrome 浏览器一些实用的调试技巧
[attack and defense world web] difficulty 1-star 3-point introductory questions: get, post, robots,, cookies, buttons, weak, PHP, web, serialize
[并发编程基础]-集合的线程安全
Automatic synchronization of server time
长期的远程工作面临的几个问题和持续改进的组织自动化
美国急于发展6G或是重温坐收3G专利费的旧梦,但中国已抢占先机
China's mobile phones suffered a major setback for the first time, while Samsung and apple increased significantly
计算机考研数据库题库
ES6 从入门到精通 # 01:ES6 介绍
[wechat applet] Introduction to wxss and global and page configuration
ES6 from getting started to mastering 06: arrow function this direction and precautions