node-cache
是一个流行的 Node.js 缓存库,它提供了内存中的键值对缓存功能。然而,node-cache
默认情况下不会在请求之间持久化数据,这意味着当服务器重启或进程结束时,缓存中的数据将会丢失。
持久化是指将数据保存到可以长期存储的设备上,以便在系统重启或数据丢失后能够恢复数据。
node-cache
,数据存储在内存中,速度快但不持久。node-cache
默认使用内存存储,没有内置的持久化机制。因此,当服务器重启或进程结束时,内存中的数据会丢失。
可以使用外部缓存服务,如 Redis 或 Memcached,这些服务提供了持久化选项。
Redis 示例:
redis
Node.js 客户端:npm install redis
const redis = require('redis');
const client = redis.createClient();
client.on('error', (err) => {
console.error('Redis error:', err);
});
function getFromCache(key, callback) {
client.get(key, (err, data) => {
if (err) return callback(err);
callback(null, data ? JSON.parse(data) : null);
});
}
function setToCache(key, value, ttl = 60) {
client.setex(key, ttl, JSON.stringify(value));
}
如果不想使用外部服务,可以实现自定义的持久化机制,例如将数据定期保存到文件或数据库中。
文件持久化示例:
fs
模块(Node.js 内置模块,无需额外安装)。const fs = require('fs');
const path = require('path');
const cacheDir = path.join(__dirname, 'cache');
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir);
}
function getFromCache(key, callback) {
const filePath = path.join(cacheDir, `${key}.json`);
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) return callback(err);
callback(null, data ? JSON.parse(data) : null);
});
}
function setToCache(key, value, ttl = 60) {
const filePath = path.join(cacheDir, `${key}.json`);
fs.writeFile(filePath, JSON.stringify(value), (err) => {
if (err) throw err;
setTimeout(() => {
fs.unlink(filePath, (err) => {
if (err && err.code !== 'ENOENT') throw err;
});
}, ttl * 1000);
});
}
node-cache
默认不支持持久化,但可以通过使用外部缓存服务(如 Redis)或实现自定义持久化机制来解决这个问题。选择合适的方案取决于具体需求和应用场景。
领取专属 10元无门槛券
手把手带您无忧上云