Ubuntu上Node.js如何进行缓存策略配置
导读:Ubuntu 上 Node.js 缓存策略配置 一 概念与范围 在 Ubuntu 上,Node.js 的缓存策略通常包含三个层面: HTTP 缓存策略:通过响应头控制浏览器与中间代理的缓存行为(如 Cache-Control、ETag、...
Ubuntu 上 Node.js 缓存策略配置
一 概念与范围
- 在 Ubuntu 上,Node.js 的缓存策略通常包含三个层面:
- HTTP 缓存策略:通过响应头控制浏览器与中间代理的缓存行为(如 Cache-Control、ETag、Last-Modified)。
- 数据层缓存:在应用内或引入 Redis 等实现分布式缓存,降低数据库与计算压力。
- 依赖与构建缓存:配置 npm/Yarn 本地缓存目录,以及在 CI 中对依赖与构建产物进行缓存,加速安装与构建。
二 HTTP 缓存策略配置
- 常用响应头与含义
- Cache-Control:核心指令,常用值包括 public、private、max-age=< 秒> 、no-cache、no-store、must-revalidate、immutable。
- Expires:HTTP/1.0 过期时间,优先级低于 Cache-Control。
- ETag / If-None-Match:资源标识与验证,未变更返回 304。
- Last-Modified / If-Modified-Since:时间戳与验证,未变更返回 304。
- 示例 1 原生 Node.js
- 强缓存示例(静态资源,缓存 1 小时)
- 代码示例:
- const http = require(‘http’); const server = http.createServer((req, res) => { res.setHeader(‘Cache-Control’, ‘public, max-age=3600’); res.end(‘Hello, World!’); } ); server.listen(3000);
- 代码示例:
- 协商缓存示例(返回 ETag,命中返回 304)
- 代码示例:
- const http = require(‘http’); const crypto = require(‘crypto’); const server = http.createServer(async (req, res) => { const content = ‘Hello, World!’; const etag = ‘"’ + crypto.createHash(‘md5’).update(content).digest(‘hex’) + ‘"’; const ifNoneMatch = req.headers[‘if-none-match’]; if (ifNoneMatch === etag) { res.writeHead(304); return res.end(); } res.setHeader(‘Cache-Control’, ‘public, max-age=0’); res.setHeader(‘ETag’, etag); res.end(content); } ); server.listen(3000);
- 代码示例:
- 强缓存示例(静态资源,缓存 1 小时)
- 示例 2 Express
- 全局无缓存(适用于隐私/敏感页面)
- 代码示例:
- const express = require(‘express’); const app = express(); app.use((req, res, next) => { res.setHeader(‘Cache-Control’, ‘no-store, no-cache, must-revalidate’); res.setHeader(‘Pragma’, ‘no-cache’); res.setHeader(‘Expires’, ‘0’); next(); } ); app.get(‘/’, (req, res) => res.send(‘Never cached’)); app.listen(3000);
- 代码示例:
- 按路由设置缓存(静态资源长期缓存,HTML 不缓存)
- 代码示例:
- const express = require(‘express’); const path = require(‘path’); const app = express(); app.use(‘/static’, express.static(path.join(__dirname, ‘public’), { maxAge: ‘365d’, // 强缓存 1 年 immutable: true // 可配合指纹/文件名哈希使用 } )); app.get(‘/’, (req, res) => { res.setHeader(‘Cache-Control’, ‘no-cache, must-revalidate’); res.sendFile(path.join(__dirname, ‘views’, ‘index.html’)); } ); app.listen(3000);
- 代码示例:
- 全局无缓存(适用于隐私/敏感页面)
- 示例 3 Koa 与 Hapi
- Koa:使用 ctx.set(‘Cache-Control’, ‘public, max-age=3600’)。
- Hapi:在路由 options 中设置 cache: { expiresIn: 3600 } 。
三 数据层缓存 Redis
- 适用场景:热点数据、重复计算、数据库查询风暴等。
- Ubuntu 安装与启动 Redis
- 命令:
- sudo apt update & & sudo apt install redis-server
- sudo systemctl start redis-server
- redis-cli ping(应返回 PONG)
- 命令:
- Node.js 使用 Redis 作为分布式缓存
- 安装客户端(示例选用 4.x):npm install redis@4.6.7
- 示例(带缓存与 10 分钟过期):
- const { createClient } = require(‘redis’); const client = createClient({ url: ‘redis://localhost:6379’ } ); client.on(‘error’, err => console.error(‘Redis error:’, err)); (async () => { await client.connect(); } )(); async function getData(key) { const cached = await client.get(key); if (cached) return JSON.parse(cached); const fresh = await computeExpensiveData(); // 业务计算/查询 await client.setEx(key, 600, JSON.stringify(fresh)); // 600 秒 return fresh; }
- 失效策略建议:基于业务设置 TTL、写入即失效(如内容变更时 DEL)、版本化键、定时清理等。
四 依赖与构建缓存配置
- npm/Yarn 本地缓存目录
- 自定义 npm 缓存目录并持久化:
- export NPM_CONFIG_CACHE=~/.cache/nodejs
- echo ‘export NPM_CONFIG_CACHE=~/.cache/nodejs’ > > ~/.bashrc
- npm config get cache(验证)
- 自定义 Yarn 缓存目录:
- yarn config set cache-folder ~/.cache/yarn
- yarn config get cache-folder(验证)
- 自定义 npm 缓存目录并持久化:
- CI 中的缓存示例(GitHub Actions)
- 缓存 npm 依赖与构建产物:
-
- uses: actions/cache@v3 with: path: ~/.npm key: ${ { runner.os } } -node-${ { hashFiles(‘**/package-lock.json’) } }
-
- uses: actions/cache@v3 with: path: ./build key: ${ { runner.os } } -build-${ { github.sha } }
-
- 说明:依赖缓存以 package-lock.json 内容哈希为键,构建产物以 git SHA 为键,命中时可显著缩短安装与构建时间。
- 缓存 npm 依赖与构建产物:
五 验证与最佳实践
- 验证 HTTP 缓存
- 使用 cURL 检查响应头:curl -I http://localhost:3000/static/app.js
- 观察是否存在 Cache-Control、ETag、Last-Modified 等字段;协商缓存未变更时应返回 304。
- 最佳实践
- 静态资源:使用 Cache-Control: public, max-age、immutable,并配合文件名哈希或版本号实现长期缓存与快速失效。
- 动态/隐私内容:使用 no-store 或 no-cache, must-revalidate,必要时同时设置 Pragma: no-cache、Expires: 0。
- 协商缓存:为可变内容生成 ETag/Last-Modified,减少传输体积与时延。
- 数据层:热点数据引入 Redis 等分布式缓存,合理设置 TTL 与失效策略,避免脏读与雪崩。
- 依赖与构建:在 CI 中缓存 ~/.npm 与构建目录,以 锁文件/提交哈希 作为缓存键,提升持续交付效率。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Ubuntu上Node.js如何进行缓存策略配置
本文地址: https://pptw.com/jishu/764929.html
