len-cache
v1.0.0
Published
多驱动缓存管理库,支持内存、文件和Redis
Maintainers
Readme
LenCache 缓存库
一个支持多驱动的 Node.js 缓存库,支持内存、文件和 Redis 三种存储方式。
功能特性
- 支持多种缓存驱动:内存、文件、Redis
- 单例模式设计,全局共享缓存实例
- 灵活的配置方式,支持外部配置文件
- 同时支持 CommonJS 和 ESM 模块系统
- 完善的 TypeScript 类型支持
- 自动清理过期缓存
- LRU 淘汰策略(内存驱动)
安装
npm install len-cache
# 或
yarn add len-cache快速开始
使用默认配置(内存驱动)
import LenCache from 'len-cache';
// 设置缓存
await LenCache.set('user:1', { name: '张三', age: 25 }, 60);
// 获取缓存
const user = await LenCache.get('user:1');
console.log(user); // { name: '张三', age: 25 }
// 检查是否存在
const exists = await LenCache.has('user:1');
console.log(exists); // true
// 删除缓存
await LenCache.delete('user:1');使用配置文件
import LenCache from 'len-cache';
// 从配置文件加载配置
LenCache.config('./cache.config.json');
// 现在可以使用配置的驱动了
await LenCache.set('key', 'value');配置方式
1. 通过配置文件
在项目根目录创建 cache.config.json 文件:
{
"driver": "redis",
"redis": {
"host": "127.0.0.1",
"port": 6379,
"password": "yourpassword",
"db": 0,
"ttl": 3600
}
}2. 通过配置对象
LenCache.config({
driver: 'file',
file: {
path: './data/cache',
ttl: 86400
}
});可用驱动配置
内存驱动
{
"driver": "memory",
"memory": {
"maxSize": 1000,
"ttl": 3600
}
}maxSize: 最大缓存条目数 (LRU淘汰)ttl: 默认过期时间(秒)
文件驱动
{
"driver": "file",
"file": {
"path": "./data/cache",
"ttl": 86400
}
}path: 缓存文件存储路径ttl: 默认过期时间(秒)
Redis驱动
{
"driver": "redis",
"redis": {
"host": "localhost",
"port": 6379,
"password": "yourpassword",
"db": 0,
"ttl": 3600,
"connectTimeout": 5000
}
}API 文档
LenCache.config(config)
加载缓存配置
参数:
config: 配置对象或配置文件路径
async LenCache.set(key, value, [ttl])
存储缓存值
参数:
key: 缓存键value: 缓存值ttl: 过期时间(秒),可选
async LenCache.get(key)
获取缓存值
async LenCache.delete(key)
删除指定缓存
async LenCache.clear()
清空所有缓存
async LenCache.has(key)
检查缓存是否存在
async LenCache.ttl(key)
获取缓存剩余时间(秒)
最佳实践
缓存数据库查询结果
async function getUser(id) {
const cacheKey = `user:${id}`;
let user = await LenCache.get(cacheKey);
if (!user) {
user = await db.query('SELECT * FROM users WHERE id = ?', [id]);
if (user) {
await LenCache.set(cacheKey, user, 3600); // 缓存1小时
}
}
return user;
}多级缓存策略
async function getProduct(id) {
const memoryKey = `product:${id}`;
const fileKey = `product_file:${id}`;
// 1. 检查内存缓存
let product = await LenCache.get(memoryKey);
if (product) return product;
// 2. 检查文件缓存
product = await LenCache.get(fileKey);
if (product) {
// 回填到内存缓存
await LenCache.set(memoryKey, product, 300); // 5分钟
return product;
}
// 3. 从数据库获取
product = await fetchFromDB(id);
if (product) {
// 同时存入文件和内存缓存
await LenCache.set(fileKey, product, 86400); // 1天
await LenCache.set(memoryKey, product, 1800); // 30分钟
}
return product;
}常见问题
如何查看当前使用的驱动类型?
console.log(LenCache.driverType); // 输出: "MemoryDriver", "FileDriver" 或 "RedisDriver"如何切换缓存驱动?
修改配置后重新调用 LenCache.config() 方法即可。
文件驱动如何清理过期缓存?
文件驱动会在读取时自动检查并清理过期缓存,也可以通过定时任务调用 clear() 方法。
参与贡献
欢迎提交 Issue 或 Pull Request。
许可证
MIT
