Skip to content

Comments

feat(cache): 添加本地内存缓存版本和 MessagePack 序列化器#30

Merged
ceyewan merged 1 commit intomainfrom
feat/cache-standalone-msgpack
Jan 3, 2026
Merged

feat(cache): 添加本地内存缓存版本和 MessagePack 序列化器#30
ceyewan merged 1 commit intomainfrom
feat/cache-standalone-msgpack

Conversation

@ceyewan
Copy link
Owner

@ceyewan ceyewan commented Jan 3, 2026

概述

cache 组件添加本地内存缓存版本(Standalone)和 MessagePack 序列化器支持,参考 ratelimit 的设计模式。

变更内容

1. 本地内存缓存 (cache/standalone.go)

基于高性能缓存库 otter v2 实现:

方法 支持 说明
Set/Get/Delete/Has/Expire 核心 Key-Value 操作
Hash (HSet/HGet/...) 返回 ErrNotSupported
ZSet (ZAdd/ZRange/...) 返回 ErrNotSupported
List (LPush/LPop/...) 返回 ErrNotSupported

关键设计

  • 使用 ExpiryWriting 策略,TTL 语义与 Redis 一致(读取不重置过期时间)
  • 默认容量 10000,可配置
  • 存储原始对象,无序列化开销

2. MessagePack 序列化器

新增 MessagePackSerializer

// 支持
New("msgpack")      -> MessagePackSerializer
NewMessagePack()    -> MessagePackSerializer

// 性能优势
// - 序列化速度:比 JSON 快 2-3 倍
// - 数据体积:比 JSON 小 20-30%

3. 统一配置入口 (cache/cache.go)

// 统一入口(根据 Mode 选择)
cache.New(&cache.Config{
    Mode: "standalone",  // 或 "distributed"
    Standalone: &cache.StandaloneConfig{Capacity: 10000},
}, cache.WithRedisConnector(conn))

// 本地缓存
cache.NewStandalone(&cache.StandaloneConfig{Capacity: 10000})

// Redis 缓存(兼容旧版)
cache.NewWithRedis(conn, &cache.Config{
    Prefix: "app:",
    Serializer: "msgpack",
})

使用场景

场景 推荐模式
单机部署 Standalone
二级缓存(本地+Redis) 两者组合
分布式集群 Distributed
测试环境 Standalone(无外部依赖)

测试

所有测试通过:

go test -v ./cache/... -run Standalone
PASS: TestCache_Standalone (1.00s)

Closes #29

🤖 Generated with Claude Code

## 新增功能

### 1. 本地内存缓存 (Standalone)
- 基于 `github.com/maypok86/otter/v2` 实现
- 支持 Key-Value 操作 (Set/Get/Delete/Has/Expire)
- Hash/ZSet/List 操作返回 "不支持" 错误
- 使用 `ExpiryWriting` 策略,TTL 语义与 Redis 一致
- 默认容量 10000,可配置

### 2. MessagePack 序列化器
- 实现 `MessagePackSerializer`
- 相比 JSON:序列化快 2-3 倍,数据体积小 20-30%
- 新增 `NewMessagePack()` 便捷构造函数

### 3. 统一配置入口
- `New(cfg)` 根据 `cfg.Mode` 选择模式
- `NewStandalone()` 创建本地缓存
- `NewWithRedis()` 创建 Redis 缓存(兼容旧版)

## 配置示例

```go
// 本地缓存
cache.NewStandalone(&cache.StandaloneConfig{Capacity: 10000})

// Redis 缓存
cache.NewWithRedis(conn, &cache.Config{
    Prefix: "app:",
    Serializer: "msgpack", // 新增
})

// 统一配置
cache.New(&cache.Config{
    Mode: "standalone",
    Standalone: &cache.StandaloneConfig{Capacity: 5000},
})
```

Closes #29

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@ceyewan ceyewan merged commit c195463 into main Jan 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] 为 cache 组件添加本地内存版本

1 participant