71 # Negotiate the configuration of the cache: by content

Compare (Negotiate) Cache

Compare and decide whether to use cache or re-fetch data, which will reduce network requests and improve performance.

How Contrast Caching Works

When the client requests the server for the first time, the server will cache the data and generate a cache identifier, which will be sent to the client. When the client requests the server for the second time, the cache identifier will be character sent to the server, the server will judge according to the cache identifier, if the cache identifier is the same, the server will judge whether the cache has expired, if not, the server will return 304, telling the client to use the cache, if the cache identifier is different, Then the server will return 200 and return new data at the same time.

The previous section used the modification time method, this section uses the content to deal with

Use md5 digest algorithm: not an encryption algorithm (irreversible)

  • irreversible
  • Different content conversion results are not the same
  • The converted results are all the same length
  • The same thing produces the same result
  • The avalanche effect, a little difference makes a huge difference

The library used is the crypto library

const crypto = require('crypto');
console.log(crypto.createHash('md5').update('kaimo313').digest('base64'));
// rFDqro5Lox3vFXr5fA4r7Q==
  • client:if-none-match
  • Server: ETagthe unique identifier of the current file

ETag + if-none-matchThe comparison cache can be realized, and the comparison method is more accurate. The disadvantage is that the performance of the file is very poor, but by default we will not generate a hash stamp for the complete content, and a certain part of the file can be taken. In order to ensure accuracy, a part of the content can be added. The total size of the above files is used to generate hash stamps, so the performance will be much better.

new buildcache.js

const http = require("http");
const fs = require("fs");
const path = require("path");
const url = require("url");

const crypto = require("crypto");

const server = http.createServer((req, res) => {
    
    
    const {
    
     pathname } = url.parse(req.url);
    const filePath = path.join(__dirname, pathname);
    console.log(req.headers);
    res.setHeader("Cache-Control", "no-cache");
    // 拿到客户端传过来的 if-none-match 文件标识
    let ifNoneMatch = req.headers["if-none-match"];

    fs.stat(filePath, (err, statObj) => {
    
    
        if (err) return res.end();
        // 进行文件摘要产生hash
        let contentHash = crypto.createHash("md5").update(fs.readFileSync(filePath)).digest("base64");
        if (ifNoneMatch === contentHash) {
    
    
            res.statusCode = 304;
            return res.end();
        }
        res.setHeader("ETag", contentHash);
        // 第一请求,需要根据内容生成一个唯一的标识:可以对应当前的文件
        if (err) return (res.statusCode = 404), res.end("Not Found");
        // 判断是否是文件
        if (statObj.isFile()) {
    
    
            fs.createReadStream(filePath).pipe(res);
        } else {
    
    
            res.statusCode = 404;
            res.end("Not Found");
        }
    });
});
server.listen(5000);

Then create a new public folder, add index.htmlandstyle.css

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>凯小默测试对比缓存:通过内容</title>
</head>

<body>
    <link rel="stylesheet" href="/public/style.css">
</body>

</html>
body {
    
    
    background-color: seagreen;
}

We start the service, visit http://127.0.0.1:5000/public/index.html, and we can see that the resource requested for the second time becomes 304

nodemon cache.js

insert image description here

insert image description here

insert image description here

Guess you like

Origin blog.csdn.net/kaimo313/article/details/132353640