This commit is contained in:
loveuer
2026-01-28 10:28:13 +08:00
parent 507a67e455
commit 3ee0c9c098
29 changed files with 2852 additions and 0 deletions

112
database/cache/README.md vendored Normal file
View File

@@ -0,0 +1,112 @@
# Cache Package
简洁的 Redis 兼容缓存接口,包含最常用的缓存操作。
## 接口说明
### Cache 核心方法
- `Set/Get/GetBytes/GetScan` - 存取值
- `Del` - 删除键
- `Exists` - 检查键是否存在
- `Expire/TTL` - 设置/获取过期时间
- `Inc/IncBy/Dec` - 原子递增递减
- `SetNX` - 不存在时设置
- `Keys` - 模式匹配查找键
- `Close` - 关闭连接
### Hash 操作方法
- `HSet/HGet` - 设置/获取字段值
- `HGetAll` - 获取所有字段值
- `HDel` - 删除字段
- `HExists` - 检查字段是否存在
- `HKeys` - 获取所有字段名
- `HLen` - 获取字段数量
- `HIncrBy` - 字段值原子递增
### 配置选项
- `Driver` - 驱动类型 (redis/memory)
- `Addr` - 连接地址
- `MasterAddr` - 主节点地址
- `ReplicaAddrs` - 副本节点地址列表
- `Password` - 密码
- `DB` - 数据库编号
- `ReadOnly` - 只读模式
- `Reconnect` - 是否启用自动重连(默认 true
- `ReconnectInterval` - 重连检测间隔(默认 10 秒)
- 连接池和超时配置
## 使用示例
### 基础 Redis 连接
```go
config := NewConfig("redis", "localhost:6379")
cache, err := Open(config)
if err != nil {
log.Fatal(err)
}
```
### Master-Replica 模式(读写分离)
```go
config := NewConfig("redis", "localhost:6379")
config.MasterAddr = "redis-master:6379"
config.ReplicaAddrs = []string{"redis-replica-1:6379", "redis-replica-2:6379"}
cache, err := Open(config)
// 读操作会自动使用 replica写操作使用 master
```
### Kubernetes Headless Service 模式
```go
// 自动解析 headless service 并实现读写分离
cache, err := NewRedisFromHeadlessService(
"my-redis-headless.default.svc.cluster.local:6379",
"password",
)
```
### 基础操作
```go
// 设置值
err = cache.Set(ctx, "key", "value", time.Hour)
// 获取值
val, err := cache.Get(ctx, "key")
// 原子递增
count, err := cache.IncBy(ctx, "counter", 1)
// Hash 操作
err = cache.HSet(ctx, "user:1", "name", "张三")
name, err := cache.HGet(ctx, "user:1", "name")
all, err := cache.HGetAll(ctx, "user:1")
```
### 读写分离说明
- **写操作** (Set, Del, Inc, HSet 等) → Master 节点
- **读操作** (Get, Exists, HGet, Keys 等) → Replica 节点
- **Headless Service** → 自动解析 Kubernetes Pod 地址
### 自动重连
- **默认启用**:每 10 秒检测一次连接状态
- **断线重连**:自动重新初始化连接
- **优雅关闭**Close() 时停止重连检测
```go
// 禁用自动重连
config := NewConfig("redis", "localhost:6379")
config.Reconnect = false
// 自定义重连间隔
config.Reconnect = true
config.ReconnectInterval = 5 * time.Second
```