在Node.js项目中实现数据缓存是提升服务器性能的有效手段,以下是几种主流的缓存方案及其适用场景,结合了多个来源的最佳实践:
1. 内存缓存(快速但易失性)
适用场景:高频访问的临时数据(如会话信息、计算结果),单服务器环境。
推荐工具:
- node-cache:简单易用,支持过期时间设置。
1
2
3
4const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 60 }); // 60秒过期
cache.set('key', 'value');
const value = cache.get('key'); - lru-cache:基于LRU算法(最近最少使用),适合限制内存占用的场景。
1
2const LRU = require('lru-cache');
const cache = new LRU({ max: 500, maxAge: 1000 * 60 }); // 最多500条,1分钟过期
- node-cache:简单易用,支持过期时间设置。
优点:极快(内存读写),无网络开销。
缺点:进程重启后数据丢失,多实例间无法共享。
2. 分布式缓存(多服务器共享)
适用场景:多实例部署或需要持久化的缓存(如用户数据、热点查询)。
推荐工具:
- Redis:高性能键值存储,支持复杂数据结构和持久化。
1
2
3
4const redis = require('redis');
const client = redis.createClient();
client.setex('key', 3600, 'value'); // 缓存1小时
client.get('key', (err, reply) => console.log(reply)); - Memcached:轻量级,适合简单键值缓存。
1
2
3const Memcached = require('memcached');
const memcached = new Memcached('localhost:11211');
memcached.set('key', 'value', 300, (err) => {}); // 缓存5分钟
- Redis:高性能键值存储,支持复杂数据结构和持久化。
优点:跨进程/服务器共享,高可用性(如Redis集群)。
缺点:需额外维护缓存服务,网络延迟略高。
3. HTTP缓存(减少重复请求)
- 适用场景:API响应或静态资源(如HTML、CSS文件)。
- 实现方式:通过
Cache-Control
等响应头控制客户端或CDN缓存。1
2
3
4
5
6const express = require('express');
const app = express();
app.get('/data', (req, res) => {
res.set('Cache-Control', 'public, max-age=300'); // 缓存5分钟
res.json({ data: 'cached' });
}); - 优点:减少服务器负载,提升客户端体验。
- 缺点:仅适用于可公开缓存的数据。
4. 文件缓存(持久化但较慢)
- 适用场景:低频变更的静态数据(如配置文件、模板)。
- 示例:
1
2
3
4
5
6const fs = require('fs');
const cachePath = './cache.json';
// 写入缓存
fs.writeFileSync(cachePath, JSON.stringify({ key: 'value' }));
// 读取缓存
const data = JSON.parse(fs.readFileSync(cachePath)); - 优点:数据持久化。
- 缺点:I/O性能较低,不适合高频读写。
5. 数据库查询缓存
- 适用场景:复杂查询结果缓存(如MySQL查询缓存或ORM层缓存)。
- 工具:ORM(如Sequelize)内置缓存或手动结合Redis。
1
2
3
4
5
6
7
8
9// 使用Redis缓存数据库查询
async function getCachedUser(id) {
const key = `user:${id}`;
const cached = await client.get(key);
if (cached) return JSON.parse(cached);
const user = await db.query('SELECT * FROM users WHERE id = ?', [id]);
client.setex(key, 3600, JSON.stringify(user)); // 缓存1小时
return user;
}
选择建议
- 单机临时数据:
node-cache
或lru-cache
。 - 多实例/持久化:Redis(支持数据结构)或Memcached(简单键值)。
- 静态资源:HTTP缓存 + CDN。
- 敏感数据:避免缓存或加密存储。
注意事项:
- 设置合理的过期时间,避免脏数据。
- 监控缓存命中率(如Redis的
INFO
命令)。 - 处理缓存穿透(布隆过滤器)和雪崩(随机过期时间)。