synthia-cache-system
v0.0.2
Published
Synthia Engine Cache System - 核心缓存系统实现,提供多级缓存、版本管理、性能监控等功能
Maintainers
Readme
Synthia Cache System
Synthia Engine 核心缓存系统 - 提供高效的多级缓存、版本管理、性能监控等功能
✨ 核心特性
- 多级缓存: 本地 + 云端混合缓存策略
- 智能同步: 自动同步本地和云端缓存
- 版本管理: 智能的缓存版本控制和依赖追踪
- 性能监控: 详细的缓存统计和性能指标
- 压缩优化: 多种压缩算法,节省存储空间
- 智能清理: 基于多种策略的智能缓存清理
- 插件系统: 可扩展的插件架构
- 类型安全: 完整的 TypeScript 类型支持
- 批量操作: 支持批量 CRUD 操作,提升性能
- 事务支持: 提供事务性缓存操作
🚀 快速开始
安装
npm install synthia-cache-system基本使用
import { SynthiaCacheManager, type CacheConfig } from 'synthia-cache-system';
// 配置缓存系统
const config: CacheConfig = {
local: {
dir: '.synthia-cache',
maxSize: 100 * 1024 * 1024, // 100MB
ttl: 7 * 24 * 60 * 60 * 1000, // 7天
compression: true,
},
cloud: {
enabled: false, // 设置为 true 启用云端缓存
provider: 'aws-s3',
bucket: 'your-bucket-name',
region: 'us-east-1',
accessKeyId: 'your-access-key-id',
accessKeySecret: 'your-secret-access-key',
},
strategy: {
level: 'local', // 'local' | 'cloud' | 'hybrid'
localFirst: true,
autoSync: false,
syncInterval: 5 * 60 * 1000, // 5分钟
},
};
// 创建缓存管理器
const cacheManager = new SynthiaCacheManager(config);
// 设置缓存
await cacheManager.set('user:123', {
id: 123,
name: 'John Doe',
email: '[email protected]',
});
// 获取缓存
const user = await cacheManager.get('user:123');
console.log(user); // { id: 123, name: 'John Doe', email: '[email protected]' }📋 API 文档
CacheManager
基本操作
// 设置缓存
await cacheManager.set(key: string, value: any, options?: Partial<CacheMeta>)
// 获取缓存
const value = await cacheManager.get(key: string)
// 删除缓存
await cacheManager.delete(key: string)
// 清空缓存
await cacheManager.clear()批量操作
// 批量设置缓存
await cacheManager.setBatch(items: Array<{
key: string
value: any
options?: Partial<CacheMeta>
}>)
// 批量获取缓存
const results = await cacheManager.getBatch(keys: string[])
// 批量删除缓存
await cacheManager.deleteBatch(keys: string[])事务操作
// 事务性操作缓存
await cacheManager.setTransaction(operations: Array<{
type: 'set' | 'delete'
key: string
value?: any
options?: Partial<CacheMeta>
}>)高级操作
// 获取缓存统计
const stats = await cacheManager.getStats()
// 预热缓存
await cacheManager.warmup(keys: string[])
// 清理过期缓存
await cacheManager.cleanup()
// 导出缓存
const data = await cacheManager.export()
// 导入缓存
await cacheManager.import(data)CacheVersionManager
缓存版本管理器,提供版本控制和依赖追踪功能:
import { CacheVersionManager } from 'synthia-cache-system';
const versionManager = new CacheVersionManager();
// 更新缓存版本信息
const meta = versionManager.updateCacheVersion(
'user:123',
userData,
['package.json', 'src/config.ts'],
['user', 'profile'],
'1.0.0'
);
// 检查缓存是否有效
const isValid = versionManager.isCacheValid('user:123', dependencies);
// 获取受影响的缓存键
const affectedKeys = versionManager.getAffectedCacheKeys(['src/config.ts']);
// 清理无效版本
versionManager.cleanupInvalidVersions();CacheCompressor
缓存压缩器,提供多种压缩算法:
import { CacheCompressor } from 'synthia-cache-system';
const compressor = new CacheCompressor();
// 压缩数据
const compressed = await compressor.compress(data, 'gzip');
// 解压缩数据
const decompressed = await compressor.decompress(compressed, 'gzip');
// 选择最佳压缩算法
const result = await compressor.selectBestCompression(data);
console.log(`最佳算法: ${result.algorithm}, 压缩比: ${result.ratio}`);
// 批量压缩
const compressedItems = await compressor.compressBatch(items, 'gzip');CacheStrategyManager
缓存策略管理器,提供智能的预热和清理策略:
import { CacheStrategyManager } from 'synthia-cache-system';
const strategyManager = new CacheStrategyManager(cacheManager);
// 预热缓存
await strategyManager.warmup(['user:123', 'user:124']);
// 智能清理
const result = await strategyManager.smartCleanup();
console.log(
`清理了 ${result.cleanedItems} 项,释放了 ${result.freedSpace} 字节`
);
// 优化策略
const recommendations = await strategyManager.optimizeStrategy();
console.log('优化建议:', recommendations.recommendations);
// 批量预热
await strategyManager.batchWarmup([
{ keys: ['user:123'], priority: 'high' },
{ keys: ['user:124', 'user:125'], priority: 'medium' },
]);CacheMetricsCollector
性能监控和指标收集器:
import { CacheMetricsCollector } from 'synthia-cache-system';
const metricsCollector = new CacheMetricsCollector();
// 记录操作
metricsCollector.recordOperation({
type: 'get',
key: 'user:123',
timestamp: Date.now(),
duration: 15,
success: true,
});
// 生成性能报告
await metricsCollector.generateReport();
// 获取指标
const metrics = metricsCollector.getMetrics();
console.log('实时指标:', metrics.realTime);
console.log('性能指标:', metrics.performance);
console.log('优化建议:', metrics.recommendations);
// 导出指标数据
const data = metricsCollector.exportMetrics();CachePluginManager
插件管理器,提供可扩展的插件架构:
import {
CachePluginManager,
CacheManagerWithPlugins,
} from 'synthia-cache-system';
const pluginManager = new CachePluginManager();
// 定义插件
const myPlugin: CachePlugin = {
name: 'my-plugin',
version: '1.0.0',
description: '我的缓存插件',
hooks: {
beforeGet: async (key: string) => {
console.log(`准备获取缓存: ${key}`);
},
afterSet: async (key: string, value: any) => {
console.log(`缓存设置完成: ${key}`);
},
},
};
// 注册插件
pluginManager.registerPlugin(myPlugin);
// 创建带插件的缓存管理器
const enhancedCacheManager = new CacheManagerWithPlugins(
cacheManager,
pluginManager
);
// 初始化插件
await pluginManager.initializePlugins();
// 使用增强的缓存管理器
await enhancedCacheManager.set('user:123', userData);🎯 使用场景
1. 构建缓存
// 缓存构建结果
const buildCache = new SynthiaCacheManager({
local: { dir: '.build-cache', maxSize: 500 * 1024 * 1024 },
cloud: { enabled: true, provider: 'aws-s3', bucket: 'build-cache' },
strategy: { level: 'hybrid', autoSync: true },
});
await buildCache.set('build:main', buildOutput, {
dependencies: ['src/**/*.ts', 'package.json'],
tags: ['build', 'main'],
version: '1.0.0',
});2. API 响应缓存
// API 响应缓存
const apiCache = new SynthiaCacheManager({
local: { dir: '.api-cache', ttl: 5 * 60 * 1000 }, // 5分钟
strategy: { level: 'local' },
});
// 批量缓存 API 响应
const apiResponses = [
{ key: 'api:users', value: usersData },
{ key: 'api:products', value: productsData },
];
await apiCache.setBatch(apiResponses);3. 数据库查询缓存
// 数据库查询缓存
const dbCache = new SynthiaCacheManager({
local: { dir: '.db-cache', ttl: 30 * 60 * 1000 }, // 30分钟
strategy: { level: 'local' },
});
// 事务性缓存数据库操作
await dbCache.setTransaction([
{ type: 'set', key: 'user:123', value: userData },
{ type: 'set', key: 'user:124', value: userData2 },
{ type: 'delete', key: 'user:125' },
]);🔧 配置选项
本地缓存配置
const localConfig = {
dir: '.synthia-cache', // 缓存目录
maxSize: 100 * 1024 * 1024, // 最大缓存大小 (100MB)
ttl: 7 * 24 * 60 * 60 * 1000, // 过期时间 (7天)
compression: true, // 启用压缩
};云端缓存配置
const cloudConfig = {
enabled: true, // 启用云端缓存
provider: 'aws-s3', // 云服务提供商
bucket: 'my-cache-bucket', // 存储桶名称
region: 'us-east-1', // 区域
accessKeyId: 'your-key-id', // 访问密钥ID
accessKeySecret: 'your-secret', // 访问密钥
};缓存策略配置
const strategyConfig = {
level: 'hybrid', // 缓存级别
localFirst: true, // 本地优先
autoSync: true, // 自动同步
syncInterval: 5 * 60 * 1000, // 同步间隔 (5分钟)
};📊 性能优化
1. 批量操作
使用批量操作可以显著提升性能:
// 批量设置 - 比单个设置快 3-5 倍
await cacheManager.setBatch(items);
// 批量获取 - 减少网络往返
const results = await cacheManager.getBatch(keys);2. 压缩优化
选择合适的压缩算法可以节省存储空间:
const compressor = new CacheCompressor();
const result = await compressor.selectBestCompression(data);
// 通常可以节省 30-70% 的存储空间3. 智能清理
定期执行智能清理可以保持缓存性能:
const strategyManager = new CacheStrategyManager(cacheManager);
await strategyManager.smartCleanup();
// 自动选择最佳清理策略🛠️ 开发工具
性能监控
const metricsCollector = new CacheMetricsCollector();
// 记录所有缓存操作
metricsCollector.recordOperation(operation);
// 生成详细报告
await metricsCollector.generateReport();版本管理
const versionManager = new CacheVersionManager();
// 检查缓存有效性
const isValid = versionManager.isCacheValid(key, dependencies);
// 获取受影响的缓存
const affectedKeys = versionManager.getAffectedCacheKeys(changedFiles);🔍 工作原理
1. 缓存键生成
系统会根据以下因素生成缓存键:
- 项目路径和版本
- 依赖文件哈希
- 构建配置哈希
- 源文件变化
2. 缓存策略
- 本地优先: 优先使用本地缓存
- 云端同步: 支持云端缓存同步
- 智能失效: 自动检测缓存失效
- 版本管理: 多版本缓存管理
3. 性能优化
- 并行处理: 并行执行缓存操作
- 批量操作: 批量处理缓存请求
- 压缩存储: 智能压缩减少存储空间
- 预热机制: 智能预热常用缓存
🧪 测试
# 运行测试
npm test
# 运行特定测试
npm test -- --testNamePattern="LocalCache"
# 运行测试并生成覆盖率报告
npm test -- --coverage📝 示例
查看 examples/ 目录中的完整示例:
basic-usage.ts- 基本使用示例cloud-cache.ts- 云端缓存示例plugin-example.ts- 插件开发示例
🤝 贡献
欢迎贡献代码!请查看 贡献指南 了解详细信息。
📄 许可证
MIT License - 查看 LICENSE 文件了解详细信息。
