@micl/server-racache
v0.1.7
Published
micl server cache
Readme
@micl/server-racache
提供时间敏感的内存缓存,支持本地文件快照存储。适用于 Node.js 服务端应用的数据缓存管理。
✨ 特性
- 提供时间敏感的缓存检索和存储功能
- 内存存储 + 本地文件快照持久化
- 自动过期和自动清理机制
- 支持自动存储和自动加载
- 完整的 TypeScript 类型支持
- 单例模式,全局统一管理
📦 安装
npm install @micl/server-racache
# or
pnpm add @micl/server-racache
# or
yarn add @micl/server-racache🎯 快速使用
JavaScript
const MraCache = require('@micl/server-racache');
// 配置缓存
MraCache.config({
expireTime: '1d',
storePath: './cache-snapshots.json',
autoStore: true,
autoClear: true
});
// 设置数据
MraCache.set('user_data', { name: 'John Doe', age: 30 });
// 设置带过期时间的数据
MraCache.set('temp_data', { id: 1 }, '30m');
// 获取数据
const userData = MraCache.get('user_data');
// 移除数据
MraCache.remove('user_data');
// 清空所有数据
MraCache.clearAll();
// 保存缓存快照
MraCache.store('./cache-snapshots.json');
// 加载缓存快照
MraCache.load('./cache-snapshots.json');TypeScript
const MraCache = require('@micl/server-racache');
interface User {
name: string;
age: number;
}
// 配置缓存
MraCache.config({
expireTime: '1d',
storePath: './cache-snapshots.json',
autoStore: true,
autoClear: true
});
// 设置数据
MraCache.set<User>('user_data', { name: 'John Doe', age: 30 });
// 获取数据
const userData = MraCache.get<User>('user_data');📚 API 参考
MraCache 配置
MraCacheOptionInterface
| 配置项 | 类型 | 默认值 | 描述 |
|--------|------|--------|------|
| expireTime | string | '1h' | 默认过期时间(格式:1d、1h、1m) |
| storePath | string | '' | 默认快照存储路径 |
| autoStore | boolean | false | 是否自动存储 |
| autoClear | boolean | false | 是否自动清理过期数据 |
config(options: MraCacheOptionInterface): void
更新全局配置设置。
参数:
options- 配置选项
MraCache.config({
expireTime: '1d',
storePath: './cache-snapshots.json',
autoStore: true,
autoClear: true
});缓存操作
get<T>(key: string): T | undefined
从缓存中检索数据。
参数:
key- 缓存数据的唯一标识符
返回: 缓存的数据(如果存在且未过期)
const data = MraCache.get<User>('user_data');set<T>(key: string, data: T, expireTime?: string): string
在缓存中存储数据,可指定过期时间。
参数:
key- 缓存数据的唯一标识符data- 要存储的数据expireTime(可选) - 过期时间(格式:1d、1h、1m)
返回: 存储数据的唯一标识符
// 带自定义过期时间
const uuid = MraCache.set('user_data', { name: 'John Doe' }, '2h');set<T>(data: T): string
在缓存中存储数据,自动生成唯一标识符。
参数:
data- 要存储的数据
返回: 自动生成的唯一标识符
const uuid = MraCache.set({ name: 'John Doe' });remove(key: string): string | undefined
从缓存中移除数据。
参数:
key- 要移除数据的唯一标识符
返回: 移除数据的唯一标识符,如果未找到则为 undefined
const uuid = MraCache.remove('user_data');clearAll(): void
清空缓存中的所有数据。
MraCache.clearAll();快照管理
store(path?: string): boolean
将当前缓存数据保存为快照。
参数:
path(可选) - 快照存储路径
返回: 保存成功返回 true,否则返回 false
MraCache.store('./cache-snapshots.json');load(path?: string): void
从指定路径加载快照。
参数:
path- 快照加载路径
MraCache.load('./cache-snapshots.json');🕐 时间格式
支持的时间格式:
| 格式 | 说明 |
|------|------|
| 1s | 1 秒 |
| 1m | 1 分钟 |
| 1h | 1 小时 |
| 1d | 1 天 |
🤝 贡献
欢迎提交 Issue 和 Pull Request 来完善这个模块。
📄 许可证
本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。
Copyright (c) alexgogoing [email protected]
📞 支持
如有问题或建议,请提交 Issue 或联系维护者。
@micl/server-racache - 时间敏感的内存缓存,简单高效 🚀
