llm-chat/backend/utils/cache.js

267 lines
6.0 KiB
JavaScript

const { LRUCache } = require('lru-cache');
const crypto = require('crypto');
class CacheManager {
constructor() {
// 主缓存实例 - 用于API响应缓存
this.cache = new LRUCache({
max: parseInt(process.env.CACHE_MAX_SIZE) || 500,
ttl: parseInt(process.env.CACHE_TTL) || 1800000, // 30分钟
allowStale: false,
updateAgeOnGet: false,
updateAgeOnHas: false
});
// 会话缓存 - 用于用户会话状态
this.sessionCache = new LRUCache({
max: 100,
ttl: 3600000, // 1小时
allowStale: false
});
// 对话上下文缓存 - 用于LLM上下文
this.contextCache = new LRUCache({
max: 200,
ttl: 900000, // 15分钟
allowStale: false
});
console.log('缓存管理器初始化完成');
}
/**
* 生成缓存键
*/
generateKey(prefix, ...args) {
const data = args.join(':');
const hash = crypto.createHash('md5').update(data).digest('hex');
return `${prefix}:${hash}`;
}
/**
* 设置缓存
*/
set(key, value, options = {}) {
try {
const cacheInstance = this.getCacheInstance(options.type);
const ttl = options.ttl || undefined;
cacheInstance.set(key, value, { ttl });
return true;
} catch (error) {
console.error('设置缓存失败:', error);
return false;
}
}
/**
* 获取缓存
*/
get(key, options = {}) {
try {
const cacheInstance = this.getCacheInstance(options.type);
return cacheInstance.get(key);
} catch (error) {
console.error('获取缓存失败:', error);
return null;
}
}
/**
* 检查缓存是否存在
*/
has(key, options = {}) {
try {
const cacheInstance = this.getCacheInstance(options.type);
return cacheInstance.has(key);
} catch (error) {
console.error('检查缓存失败:', error);
return false;
}
}
/**
* 删除缓存
*/
delete(key, options = {}) {
try {
const cacheInstance = this.getCacheInstance(options.type);
return cacheInstance.delete(key);
} catch (error) {
console.error('删除缓存失败:', error);
return false;
}
}
/**
* 清空指定类型的缓存
*/
clear(type = 'default') {
try {
const cacheInstance = this.getCacheInstance(type);
cacheInstance.clear();
console.log(`${type} 缓存已清空`);
return true;
} catch (error) {
console.error('清空缓存失败:', error);
return false;
}
}
/**
* 获取缓存实例
*/
getCacheInstance(type = 'default') {
switch (type) {
case 'session':
return this.sessionCache;
case 'context':
return this.contextCache;
default:
return this.cache;
}
}
/**
* 缓存LLM API响应
*/
cacheApiResponse(messages, response, options = {}) {
const key = this.generateKey('api_response', JSON.stringify(messages));
return this.set(key, response, {
type: 'default',
ttl: options.ttl || 1800000 // 30分钟
});
}
/**
* 获取缓存的LLM API响应
*/
getCachedApiResponse(messages) {
const key = this.generateKey('api_response', JSON.stringify(messages));
return this.get(key, { type: 'default' });
}
/**
* 缓存对话上下文
*/
cacheConversationContext(conversationId, context) {
const key = `context:${conversationId}`;
return this.set(key, context, {
type: 'context',
ttl: 900000 // 15分钟
});
}
/**
* 获取对话上下文缓存
*/
getConversationContext(conversationId) {
const key = `context:${conversationId}`;
return this.get(key, { type: 'context' });
}
/**
* 删除对话上下文缓存
*/
deleteConversationContext(conversationId) {
const key = `context:${conversationId}`;
return this.delete(key, { type: 'context' });
}
/**
* 缓存用户会话信息
*/
cacheUserSession(sessionId, sessionData) {
const key = `session:${sessionId}`;
return this.set(key, sessionData, {
type: 'session',
ttl: 3600000 // 1小时
});
}
/**
* 获取用户会话缓存
*/
getUserSession(sessionId) {
const key = `session:${sessionId}`;
return this.get(key, { type: 'session' });
}
/**
* 删除用户会话缓存
*/
deleteUserSession(sessionId) {
const key = `session:${sessionId}`;
return this.delete(key, { type: 'session' });
}
/**
* 获取缓存统计信息
*/
getStats() {
return {
default: {
size: this.cache.size,
max: this.cache.max,
calculatedSize: this.cache.calculatedSize,
ttl: this.cache.ttl
},
session: {
size: this.sessionCache.size,
max: this.sessionCache.max,
calculatedSize: this.sessionCache.calculatedSize,
ttl: this.sessionCache.ttl
},
context: {
size: this.contextCache.size,
max: this.contextCache.max,
calculatedSize: this.contextCache.calculatedSize,
ttl: this.contextCache.ttl
}
};
}
/**
* 缓存装饰器 - 用于自动缓存函数结果
*/
cached(keyPrefix, ttl = 1800000) {
return (target, propertyName, descriptor) => {
const originalMethod = descriptor.value;
descriptor.value = async function(...args) {
const key = this.generateKey(keyPrefix, ...args);
// 尝试从缓存获取
let result = this.get(key);
if (result !== null && result !== undefined) {
return result;
}
// 执行原方法
result = await originalMethod.apply(this, args);
// 缓存结果
this.set(key, result, { ttl });
return result;
};
return descriptor;
};
}
/**
* 清空所有缓存
*/
clearAll() {
this.clear('default');
this.clear('session');
this.clear('context');
console.log('所有缓存已清空');
}
}
// 创建单例实例
const cacheManager = new CacheManager();
module.exports = cacheManager;