69 # 强制缓存的配置

强制缓存

  • 强制缓存:以后的请求都不需要访问服务器,状态码为 200
  • 协商缓存:每次都判断一下,告诉是否需要找缓存,状态码为 304

默认强制缓存,不缓存首页(如果已经断网,那这个页面应该也访问不到,所以首页不会被强制缓存),引用的资源可以被缓存下来,后续找缓存,不会向服务器发送请求

例子:下面设置 10s 内不要在向服务器发送请求

新建 cache.js 文件

javascript 复制代码
const http = require("http");
const fs = require("fs");
const path = require("path");
const url = require("url");

const server = http.createServer((req, res) => {
    const { pathname } = url.parse(req.url);
    const filePath = path.join(__dirname, pathname);
    console.log(pathname);
    // expires 老版本浏览器支持的 绝对时间
    // cache-control 相对时间
    res.setHeader("Expires", new Date(Date.now() + 10 * 1000).toGMTString());
    res.setHeader("Cache-Control", "max-age=10");
    fs.stat(filePath, (err, statObj) => {
        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);

然后新建 public 文件夹,里面添加 index.htmlstyle.css

html 复制代码
<!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>
css 复制代码
body {
    background-color: seagreen;
}

我们启动服务,访问 http://127.0.0.1:5000/public/index.html,加了缓存头之后,css 资源第一次之后就从缓存中读取了,过了 10 s 之后才继续请求一次服务器

bash 复制代码
nodemon cache.js

强制缓存不会向服务器发送请求,所以不会判断缓存是否过期,所以需要设置缓存过期时间,否则缓存永远不会过期,会导致页面修改后,视图依旧采用老的

另外还可以设置响应头:

缓存但是每次都请求服务器

js 复制代码
res.setHeader("Cache-Control", "no-cache");

不在浏览器中进行缓存,每次请求服务器

js 复制代码
res.setHeader("Cache-Control", "no-store");
相关推荐
轻揉小乔 真新人14 小时前
使用memc-nginx和srcache-nginx模块构建高效透明的缓存机制
运维·nginx·缓存
小园子的小菜1 天前
Redis 核心原理深度解析:从数据结构、IO 模型到持久化机制
数据库·redis·缓存
BullSmall2 天前
Another Redis Desktop Manager(ARDM)下载指南
数据库·redis·缓存
nvd112 天前
ArgoCD 双层轮询深入拆解:从 redis-app.yaml 注册到缓存重建的完整链路
redis·缓存·argocd
xiaoxiangsiyan2 天前
LNMP + Redis Sentinel 高可用架构部署手册(续)
运维·网络·数据库·redis·缓存·架构·sentinel
難釋懷2 天前
Nginx外置缓存-redis2-nginx-module
nginx·缓存·junit
LearnYard2 天前
Android存储空间清理策略对比:缓存识别与多种清理方案的技术分析
缓存·智能手机
时空自由民.2 天前
STM32的缓存Cache
stm32·嵌入式硬件·缓存
Sam_Deep_Thinking2 天前
如何维持缓存的一致性?
java·缓存·面试·程序员·系统架构
ai_coder_ai2 天前
分布式缓存架构设计与实践
分布式·缓存