web cache: browser cache + http cache

1. Browser cache

localStorage, sessionStorage, cookieare all homologous.

1、localStorage

Features:

  • Store data permanently unless deleted by code or manually
  • It is only saved in the client (ie browser), and does not participate in communication with the server
  • Can store 5MBdata

Common business scenarios:

  • Login information storage, same-domain information sharing
  • Data persistence, storing infrequently changing data
  • Store search history data

2、sessionStorage

Features:

  • Based on the existence of the session window, it will fail when the browser window is closed
  • It is only saved in the client (ie browser), and does not participate in communication with the server
  • Can store 5MBdata

Common business scenarios:

  • Login information storage to achieve multi-window login
  • Store some data that you want to clear when the browser window is closed, and save it next time you come in

3、cookie

Features:

  • Support setting expiration time, if not set, it will be invalid when the browser window is closed
  • Supports communication with the server, and will be carried in HTTPthe header
  • Different browsers can store different numbers, try to control it within 20, each can store up to 3000 4KBdata , if it exceeds, it will be cut off

Common business scenarios:

  • User login information storage, idstore cookiein (the user idmust be encrypted), apiand judge cookiewhether other requests are made, if it exists, the user has logged in, if it does not exist, it means the user has not logged in

2. HTTP cache

When Weba request arrives at the cache, if there is a "cached" copy locally, the document can be fetched from local storage instead of the origin server.

Common business scenarios:

The cache is mainly used to store static resources such as html, css, js, img, etc. Generally, dynamic resources are not stored, because the cache of dynamic resources will affect the real-time performance of data.
insert image description here

1. Mandatory caching

Strong caching means that when we URLvisit , we will not send a request to the server and read resources directly from the cache, but will return a 200 status code.

We enter the page for the first time, request the server, and then the server responds. The browser will judge response Headerwhether to cache the resource according to . If the response header expiresor fieldpragma indicates that this is a strong cache, the browser will cache the resource in or in .cache-controlmemory cachedisk cache

When the second request is made, the browser judges the request parameters, and if it meets the strong cache condition, it directly returns a status code of 200 and fetches the data from the local cache. Otherwise, store the response parameters in request headerthe request header to see if they conform to the negotiation cache. If yes, the status code 304 will be returned. If not, the server will return a new resource.

Return example:
insert image description here

Strong caching based on the Expires field (deprecated)

Set in the response header expires: 本地时间戳to compare whether it has expired (there is a problem of inconsistency between the server time and the local time, which causes the cache to be abnormal and discarded)

Strong cache based on Cache-control

Set in the response header cache-control: max-age=缓存的时间秒数, compare whether it is expired, and return the cached data within the effective time of the cache, otherwise request a new resource to return.

Cache-controlDescription of common field values:

  • max-age=100: The cache expires after 100 seconds, and the resources are cached locally (commonly used)
  • s-maxage: Override max-age, only used for caching in the proxy server
  • no-cache: use negotiated cache
  • no-store: no cache
  • public: can be cached by all users, including clients and proxy servers
  • private: It can only be cached by the client, and it is not allowed to be cached by relay cache servers such as CDN

2. Negotiation cache

Negotiation cache (also called comparison cache) is determined by the server to determine whether the resource is available. When the browser sends a request for the first time, it will bring a field (or), and subsequent requests will Last-Modifiedbring Etagthe corresponding request field ( if-modified-since或者if-none-Match). If the response If there is no header Last-Modified Etag, there will be no corresponding field in the request header.

When the browser does not hit the strong cache, it will send a request to the server to verify whether the negotiation cache is hit. If the cache is hit, it will return a 304 status code, otherwise it will return new resource data.

Negotiation cache based on last-modified implementation

  1. First, you need to read the file modification time on the server side.
  2. Assign the read modification time to last-modifiedthe field .
  3. final settingCache-control:no-cache
const http = require('http');
const fs = require('fs');
http.createServer((req,res) => {
    
    
    if (req.url === 'logo.png') {
    
    
        const data = fs.readFileSync('./logo.png');
        // 1. 读取文件修改时间
        const {
    
    mtime} = fs.statSync('./logo.png');
        // 2. 请求头重携带过来的上次文件修改的时间
        const temp = req.headers['if-modified-since'];
        // 3. 对比两次文件修改时间是否一样
        if (temp === mtime.toUTCString()) {
    
    
            // 3.1 两次文件修改时间一样,返回304状态码和空的响应主体
            res.statusCode = 304;
            res.end();
            return;
        }
        // 3.1 两次文件修改时间不一样,返回新的数据并携带新的修改时间
        res.setHeader('last-modified', mtime.toUTCString());
        res.setHeader('Catch-Control', 'no=cache');
        res.end(data);
    } else {
    
    
        res.end(fs.readFileSync('./index.html'));
    }
})

Negotiation cache based on ETag

  1. When requesting a resource for the first time, the server reads the file and calculates the file fingerprint, puts the file fingerprint in Etagthe field and returns it to the client together with the resource.
  2. When requesting a resource for the second time, the client ETagautomatically . And assign it to if-None-Matchthe field , so that the last file fingerprint returns to the server along with the request.
  3. The server gets is-None-Matchthe field (that is, the last file fingerprint), reads the target resource again and generates a file fingerprint, and compares the two fingerprints. If the fingerprints of the two files are exactly the same, indicating that the file has not been changed, a 304 status code and an empty response body will be returned directly return. If the two file fingerprints do not match, it means that the file has been changed, then store the new file fingerprint ETagin and return it to the client
const http = require('http');
const fs = require('fs');
const etag = require('etag');
http.createServer((req,res) => {
    
    
    if (req.url === 'logo.png') {
    
    
        const data = fs.readFileSync('./logo.png');
        // 1. 读取文件指纹
        const etagContent = etag(data);
        // 2. 请求头重携带过来的上次的文件指纹
        const noMatch = req.headers['if-none-match'];
        // 3. 对比两次文件指纹是否一样
        if (noMatch === etagContent) {
    
    
            // 3.1 两次文件指纹一样,返回304状态码和空的响应主体
            res.statusCode = 304;
            res.end();
            return;
        }
        // 3.1 两次文件指纹不一样,返回新的数据并携带新的文件指纹
        res.setHeader('etag', etagContent);
        res.setHeader('Catch-Control', 'no=cache');
        res.end(data);
    } else {
    
    
        res.end(fs.readFileSync('./index.html'));
    }
})

3. Advantages of HTTP caching

1. Save bandwidth and traffic, save money
2. Obtain resources locally, load pages faster
3. Reduce the requirements for the original server, the server can respond faster and avoid overloading

Guess you like

Origin blog.csdn.net/weixin_45921387/article/details/129394411