feat: 添加本地缓存功能,减少API调用

- 实现SQLite缓存模块,支持高效查询和存储
- 添加缓存键生成策略(基于原文+语言对的SHA256哈希)
- 集成缓存到Translator类,先查缓存再调用API
- 添加缓存管理命令:cache clear, cache stats, cache cleanup
- 实现组合缓存清理策略(数量限制+时间过期)
- 添加完整的单元测试
- 更新配置文件模板,添加缓存配置
- 更新文档和版本记录

版本: v0.5.1
This commit is contained in:
2026-03-29 21:10:28 +08:00
parent ceed482444
commit b71f76c8b3
15 changed files with 1545 additions and 7 deletions

53
internal/cache/cleanup.go vendored Normal file
View File

@@ -0,0 +1,53 @@
package cache
import (
"context"
"fmt"
"log"
)
// CleanupManager 缓存清理管理器
type CleanupManager struct {
cache Cache
}
// NewCleanupManager 创建清理管理器
func NewCleanupManager(cache Cache) *CleanupManager {
return &CleanupManager{
cache: cache,
}
}
// ClearAll 清空所有缓存
func (m *CleanupManager) ClearAll(ctx context.Context) error {
if err := m.cache.Clear(ctx); err != nil {
return fmt.Errorf("清空缓存失败: %w", err)
}
log.Println("缓存已清空")
return nil
}
// ClearByLanguage 清空指定语言对的缓存
func (m *CleanupManager) ClearByLanguage(ctx context.Context, fromLang, toLang string) error {
// 这个功能需要在SQLite实现中添加查询功能
// 目前先返回一个提示信息
return fmt.Errorf("按语言清理功能尚未实现")
}
// GetStats 获取缓存统计信息
func (m *CleanupManager) GetStats(ctx context.Context) (*CacheStats, error) {
stats, err := m.cache.Stats(ctx)
if err != nil {
return nil, fmt.Errorf("获取缓存统计失败: %w", err)
}
return stats, nil
}
// CleanupManual 手动清理
func (m *CleanupManager) CleanupManual(ctx context.Context) error {
if err := m.cache.Cleanup(ctx); err != nil {
return fmt.Errorf("手动清理失败: %w", err)
}
log.Println("缓存清理完成")
return nil
}