- 实现SQLite缓存模块,支持高效查询和存储 - 添加缓存键生成策略(基于原文+语言对的SHA256哈希) - 集成缓存到Translator类,先查缓存再调用API - 添加缓存管理命令:cache clear, cache stats, cache cleanup - 实现组合缓存清理策略(数量限制+时间过期) - 添加完整的单元测试 - 更新配置文件模板,添加缓存配置 - 更新文档和版本记录 版本: v0.5.1
76 lines
2.0 KiB
Go
76 lines
2.0 KiB
Go
package cache
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
)
|
|
|
|
// Cache 缓存接口
|
|
type Cache interface {
|
|
// Get 获取缓存
|
|
Get(ctx context.Context, key string) (*CacheEntry, error)
|
|
|
|
// Set 设置缓存
|
|
Set(ctx context.Context, entry *CacheEntry) error
|
|
|
|
// Delete 删除缓存
|
|
Delete(ctx context.Context, key string) error
|
|
|
|
// Clear 清空缓存
|
|
Clear(ctx context.Context) error
|
|
|
|
// Stats 获取缓存统计信息
|
|
Stats(ctx context.Context) (*CacheStats, error)
|
|
|
|
// Cleanup 清理过期缓存
|
|
Cleanup(ctx context.Context) error
|
|
|
|
// Close 关闭缓存
|
|
Close() error
|
|
}
|
|
|
|
// CacheEntry 缓存条目
|
|
type CacheEntry struct {
|
|
ID int64 `json:"id"`
|
|
CacheKey string `json:"cache_key"`
|
|
OriginalText string `json:"original_text"`
|
|
TranslatedText string `json:"translated_text"`
|
|
FromLang string `json:"from_lang"`
|
|
ToLang string `json:"to_lang"`
|
|
Model string `json:"model"`
|
|
PromptName string `json:"prompt_name,omitempty"`
|
|
PromptContent string `json:"prompt_content,omitempty"`
|
|
PromptTokens int `json:"prompt_tokens"`
|
|
CompletionTokens int `json:"completion_tokens"`
|
|
TotalTokens int `json:"total_tokens"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
LastUsedAt time.Time `json:"last_used_at"`
|
|
}
|
|
|
|
// CacheStats 缓存统计信息
|
|
type CacheStats struct {
|
|
TotalRecords int `json:"total_records"`
|
|
TotalSizeBytes int64 `json:"total_size_bytes"`
|
|
OldestRecord time.Time `json:"oldest_record"`
|
|
NewestRecord time.Time `json:"newest_record"`
|
|
AvgTokensPerRecord float64 `json:"avg_tokens_per_record"`
|
|
}
|
|
|
|
// CacheConfig 缓存配置
|
|
type CacheConfig struct {
|
|
Enabled bool `yaml:"enabled"`
|
|
MaxRecords int `yaml:"max_records"`
|
|
ExpireDays int `yaml:"expire_days"`
|
|
DBPath string `yaml:"db_path"`
|
|
}
|
|
|
|
// NewCacheConfig 创建默认缓存配置
|
|
func NewCacheConfig() *CacheConfig {
|
|
return &CacheConfig{
|
|
Enabled: true,
|
|
MaxRecords: 10000,
|
|
ExpireDays: 30,
|
|
DBPath: "~/.config/yoyo/cache.db",
|
|
}
|
|
}
|