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

View File

@@ -3,6 +3,17 @@
## 项目概述
YOYO是一个命令行翻译工具使用Go语言编写采用面向对象设计模式。它通过调用在线大模型API结合不同的Prompt配置实现多样化的翻译特色。
## 开发流程
1. AI接手项目后先阅读 `AGENTS.md` `changelog.md` `taolun.md` `memory.md`,无需读整个项目的所有文件;
2. 每次开始执行操作前,先更新 `taolun.md`
3. 执行完开发后,更新 `changelog.md` `memory.md` `AGENTS.md`;
4. 最后,执行 git 操作,发布本地的 版本号,而先不提交远程;
## 文档规范
- 讨论的内容:只应该保存在 `taolun.md``changelod.md`中,根据 文档该写什么该链接什么,分门别类的放置
- 不应该再创建其他任何 md 类说明文件。
## OOP设计模式
### 核心类设计
@@ -24,6 +35,32 @@ YOYO是一个命令行翻译工具使用Go语言编写采用面向对象
### 1. 全局配置类 (Config)
负责读取YAML配置文件提供默认值。
### 2. 缓存类 (Cache)
负责本地缓存管理减少API调用。
```go
// internal/cache/cache.go
package cache
// Cache 缓存接口
type Cache interface {
Get(ctx context.Context, key string) (*CacheEntry, error)
Set(ctx context.Context, entry *CacheEntry) error
Delete(ctx context.Context, key string) error
Clear(ctx context.Context) error
Stats(ctx context.Context) (*CacheStats, error)
Cleanup(ctx context.Context) error
Close() error
}
```
**缓存功能特点**:
- **存储层**: 使用SQLite数据库
- **缓存键**: 基于原文+语言对的SHA256哈希
- **清理策略**: 组合策略(数量限制+时间过期)
- **异步保存**: 不阻塞翻译结果返回
- **自动清理**: 定时清理过期缓存
```go
// internal/config/config.go
package config
@@ -405,6 +442,12 @@ yoyo/
│ ├── translator/ # 核心翻译
│ │ ├── translator.go
│ │ └── prompt.go
│ ├── cache/ # 本地缓存
│ │ ├── cache.go # 缓存接口
│ │ ├── sqlite.go # SQLite实现
│ │ ├── key.go # 缓存键生成
│ │ ├── cleanup.go # 缓存清理
│ │ └── cache_test.go # 单元测试
│ └── prompt/ # Prompt管理
├── pkg/ # 公共工具
├── configs/ # 配置文件目录
@@ -456,6 +499,13 @@ prompts:
creative: "你是一位富有创造力的翻译家,请用优美流畅的语言翻译以下内容。"
academic: "你是一位学术翻译专家,请用严谨的学术语言翻译以下内容。"
simple: "请用简单易懂的语言翻译以下内容。"
# 缓存配置
cache:
enabled: true # 是否启用缓存
max_records: 10000 # 最大缓存记录数
expire_days: 30 # 缓存过期天数
db_path: "~/.config/yoyo/cache.db" # 缓存数据库文件路径
```
## 开发顺序建议
@@ -611,6 +661,17 @@ go run ./cmd/yoyo "This is translation content..."
# 指定翻译模式
./yoyo --mode=technical "API documentation text"
# 管道功能(与其他命令行工具联合使用)
cat file.txt | ./yoyo # 翻译文件内容
echo "Hello" | ./yoyo --lang=cn # 翻译命令输出
./yoyo "Hello" | grep "你好" # 与其他命令组合
cat file.txt | ./yoyo -q # 静默模式,只输出翻译结果
# 缓存管理命令
./yoyo cache clear # 清空翻译缓存
./yoyo cache stats # 查看缓存统计信息
./yoyo cache cleanup # 清理过期缓存
```
## 代码风格指南
@@ -821,4 +882,4 @@ yoyo onboard --force # 强制重新配置
- [Effective Go](https://go.dev/doc/effective_go)
- [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments)
- [Go Style Guide](https://google.github.io/styleguide/go/)
- [Survey库文档](https://github.com/AlecAivazis/survey)
- [Survey库文档](https://github.com/AlecAivazis/survey)