rueidistpl

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

rueidistpl

基于 rueidis的 封装,方便结构使用

Go Reference

rueidistpl 是 Rueidis 的业务友好薄封装:调用方使用简洁的类型化 API,底层缓存、Redis 命令和分布式锁仍分别由 gocache、Rueidis、rueidislock 实现。

安装

要求 Go 1.26.0 或更高版本:

go get github.com/lily0749labs/rueidistpl@v0.2.0

代码中统一使用下面的导入路径:

import "github.com/lily0749labs/rueidistpl"

能力概览

场景 对外 API 底层实现
TTL 对象缓存 NewCache[T] gocache Rueidis Store
单个 JSON 对象 NewValue[T] Redis String + JSON
Hash 对象表 NewHash[T] Rueidis Hash + JSON
对象排行榜 NewRanking[T] Hash + ZSet + 原子 Lua
计数器 rueidistpl.Counter GET/SET/INCRBY
字符串 List、Set rueidistpl.StringList、rueidistpl.StringSet Rueidis Builder
对象 List NewList[T] Redis List + JSON
对象 Set NewSet[T] Redis Set + JSON
稀疏对象 Array NewArray[T] Redis 8.8+ 原生 Array + JSON
位图 rueidistpl.Bitmap Redis String 位操作
地理位置 rueidistpl.Geo Redis Geo/ZSet
近似去重 rueidistpl.HyperLogLog Redis HyperLogLog
JSON 文档 NewJSONDocument[T] RedisJSON + JSONPath
时间序列 rueidistpl.TimeSeries RedisTimeSeries
向量集合 rueidistpl.VectorSet Redis 8.0+ Vector Set
Bloom/Cuckoo Filter rueidistpl.BloomFilter、rueidistpl.CuckooFilter RedisBloom
频率统计 rueidistpl.CountMinSketch、rueidistpl.TopK RedisBloom
分布统计 rueidistpl.TDigest RedisBloom t-digest
通用有序集合 rueidistpl.SortedSet Redis ZSet
消息流 NewStream[T] Redis Stream + JSON
发布订阅 NewPubSub[T] 普通、模式、Sharded Pub/Sub
幂等控制 rueidistpl.Idempotency SET NX PX
轻量延迟任务 NewDelayQueue[T] Hash + ZSet + 原子 Lua
分布式锁 rueidistpl.Redis.Lock、rueidistpl.Redis.TryLock rueidislock
特殊 Redis 命令 rueidistpl.Redis.Client() 原生 Rueidis Client

封装层只负责统一配置、JSON 转换、键命名和少量业务数据布局,不重新实现连接池、缓存一致性、锁续期或 Redis 命令协议。

所有返回 (T, error) 的单对象读取在 error != nil 时都会返回 T 的零值,避免暴露 JSON 部分解码结果;调用方仍应遵循 Go 的错误处理约定,不使用错误情况下的其他返回值。

创建客户端

redisClient, err := rueidistpl.New(rueidistpl.Config{
    ClientOption: rueidis.ClientOption{
        InitAddress: []string{"127.0.0.1:6379"},
        Password:    "",
    },
    KeyPrefix: "myapp",        // 所有业务 key 自动加 myapp:
    CacheTTL:  10*time.Minute, // 对象缓存默认 TTL
})
if err != nil {
    return err
}
defer redisClient.Close()

锁客户端按需创建:不调用锁 API 就不会额外建立连接。默认 KeyMajority: 2,即需要取得 2*2-1 个锁 key 中的两个;明确只使用单 Redis 实例且接受故障转移互斥窗口时,可以显式配置 KeyMajority: 1。KeyValidity 默认 5 秒、ExtendInterval 默认 2.5 秒;创建客户端时会拒绝小于 1ms 或不早于租约到期的续期间隔。LockerOption.ClientOption 由统一的 Config.ClientOption 覆盖,避免维护两份连接配置。

常用调用

结构化过期状态与跨 Slot 批量操作
expiration, err := redisClient.Expiration(ctx, "session:1")
if err != nil {
    return err
}
switch {
case !expiration.Exists:
    // key 不存在
case expiration.Persistent:
    // key 存在且永久保存
default:
    fmt.Printf("剩余时间:%s\n", expiration.TTL)
}

batch := redisClient.DeleteEach(ctx, "{account-1}:profile", "{account-2}:profile")
for _, item := range batch.Results {
    fmt.Printf("key=%s deleted=%t err=%v\n", item.Key, item.Deleted, item.Err)
}
if batch.Err != nil {
    // 部分失败时,batch.Deleted 和其他成功 Results 仍然有效。
    return batch.Err
}

ExpirationInfo 已将 PTTL/HPTTL 的 -1ms、-2ms 分别解释为 Persistent 和 Exists=false。除通用 Redis.Expiration 外,Value.Expiration 和 Redis 7.4+ 的 Hash.ExpirationField 也返回相同结构;原有 TTL/TTLField 继续保留以兼容旧代码。

DeleteEach、ExistsEach 会为每个 key 单独发送命令,输入可以位于不同 Redis Cluster Slot,返回明细顺序与输入一致。每次最多发送 512 条命令,context 取消后停止发送后续分块;批次级 Err 由失败项聚合而成,可使用 errors.Is 判断根因;原有 Delete/Exists 仍可使用,并在失败时返回已经确认的部分计数。

TTL 对象缓存
users := rueidistpl.NewCache[User](redisClient, "cache:user")

err := users.Set(ctx, "1", user)                  // 使用默认 TTL
err = users.Set(ctx, "2", user, 30*time.Minute) // 覆盖本次 TTL
user, err = users.Get(ctx, "1")
user, ttl, err := users.GetWithTTL(ctx, "1") // 同一快照中的对象与 Redis key TTL
err = users.Delete(ctx, "1")

Prefix() 可查看包含全局前缀的真实缓存命名空间。rueidistpl.IsNotFound(err) 同时识别 gocache 未命中和 Rueidis Redis Nil,可统一用于 Cache、Value、Hash、List、Ranking 等单值读取。

GetWithTTL 通过一次 Lua 原子读取对象和 PTTL,绕过客户端缓存,返回毫秒精度的 Redis key 剩余时间;-1ms 表示不过期。该方法需要 EVALSHA/EVAL 权限。对象不存在时返回可由 IsNotFound 判断的错误,发生错误时对象和 TTL 都返回零值。

Rueidis Store 的过期精度为秒;小于 1 秒的正 TTL 会自动提升为 1 秒。

不需要 gocache,只想用一个 String 保存 JSON 对象时:

profile := rueidistpl.NewValue[User](redisClient, "profile:1")
created, err := profile.SetNX(ctx, user, time.Hour)
user, err = profile.Get(ctx)
ttl, err := profile.TTL(ctx)
expiration, err := profile.Expiration(ctx)
consumed, err := profile.GetDelete(ctx) // 原子读取并删除,Redis 6.2+
Hash 对象表
users := rueidistpl.NewHash[User](redisClient, "users")

err := users.Set(ctx, "1", user)
err = users.SetMany(ctx, map[string]User{"1": user1, "2": user2})
user, err := users.Get(ctx, "1")
all, err := users.All(ctx)
deleted, err := users.Delete(ctx, "1")

还支持 SetNX、GetMany、Keys、Values 和游标式 Scan。SetMany 会按 field 字典序构造命令,使日志和执行顺序保持稳定。IncrementInt、IncrementFloat 用于保存 JSON 数字的 field;ExpireField、TTLField、ExpirationField、PersistField 需要 Redis 7.4+。

对象排行榜
ranking := rueidistpl.NewRanking[User](redisClient, "ranking")

err := ranking.Upsert(ctx, "user-1", 100, user)
top, err := ranking.Top(ctx, 10)
page, err := ranking.Page(ctx, 20, 10) // offset=20,读取接下来的 10 项
removed, err := ranking.Remove(ctx, "user-1")

排行榜的 ZSet 只保存稳定 ID,对象保存在 Hash,因此更新对象不会产生重复成员。两个键自动使用相同的 Redis Cluster hash tag,Upsert 和 Remove 通过 Lua 原子更新,Get 和 Range 也在单次 Lua 中读取一致快照,避免并发更新时组合出跨时刻数据。Upsert 会在执行 Lua 前拒绝 NaN 分数,避免 HSET 成功后 ZADD 才失败。

大排行榜优先使用 Page(ctx, offset, limit):offset 从零开始,limit 必须在 [1, MaxRankingPageSize] 内,目前最多 1000 项。参数无效或排名下标溢出时返回 ErrInvalidRankingPage。各页内部是原子快照,但并发更新可能使不同页之间出现重复或遗漏。兼容接口 Range 保留负下标和全量读取能力,调用方应限制读取范围。

计数器、List、Set、ZSet
count, err := redisClient.Counter("visits").Increment(ctx)

events := redisClient.StringList("events")
_, err = events.PushRight(ctx, "created", "paid")
items, err := events.Range(ctx, 0, -1)

jobs := rueidistpl.NewList[Job](redisClient, "jobs")
_, err = jobs.PushRight(ctx, job1, job2)
job, err := jobs.PopLeft(ctx)

tags := redisClient.StringSet("tags")
_, err = tags.Add(ctx, "go", "redis")
contains, err := tags.Contains(ctx, "rueidis")
tagPage, err := tags.Scan(ctx, 0, "go*", 100)

onlineUsers := rueidistpl.NewSet[User](redisClient, "online-users")
_, err = onlineUsers.Add(ctx, user1, user2)
containsUser, err := onlineUsers.Contains(ctx, user1)
users, err := onlineUsers.Members(ctx)
userPage, err := onlineUsers.Scan(ctx, 0, "", 100)

scores := redisClient.SortedSet("scores")
err = scores.Add(ctx, "alice", 100)
score, err := scores.Increment(ctx, "alice", 10)
top, err := scores.ReverseRange(ctx, 0, 9)

redisClient.List 保留为 StringList 的简写;保存结构体时使用 NewList[T]。StringSet 用于原始字符串,NewSet[T] 用于 JSON 对象;两者都提供游标式 Scan,大集合应优先分批扫描而不是一次调用 Members。泛型 Set 的 pattern 匹配原始 JSON 字符串,不是结构化字段查询。对象是否相同也由 JSON 字节串决定,自定义 MarshalJSON 应保证输出稳定。

Counter、StringList、StringSet、Value、Hash、泛型 List/Set、SortedSet 和 Stream 都可通过 Key() 查看真实 Redis key;Cache 和 Pub/Sub 则使用 Prefix() 查看命名空间。

SortedSet 只保存字符串 member;需要同时保存对象内容时使用 NewRanking[T]。两种 ZSet 封装都拒绝 Redis 不接受的 NaN,正负无穷仍可作为合法分数边界。

Redis 8.8+ 原生 Array
users := rueidistpl.NewArray[User](redisClient, "users-by-index")

// 连续写入,以及按任意下标构造稀疏数组。
_, err := users.Set(ctx, 0, user1, user2)
_, err = users.SetMany(ctx, map[int64]User{10: user10, 1000: user1000})

// ARMGET/ARGETRANGE 保留空槽;Exists=false 时 Value 是 User 零值。
items, err := users.GetMany(ctx, 0, 9, 10)
rangeItems, err := users.Range(ctx, 10, 0) // start>end 时倒序

// ARSCAN 只返回非空槽,适合扫描很稀疏的下标范围。
usedItems, err := users.Scan(ctx, 0, 1000, 100)

// 游标式追加和固定窗口 Ring。
_, err = users.Insert(ctx, user1, user2)
nextIndex, err := users.Next(ctx)
positioned, err := users.Seek(ctx, 100)
_, err = users.Ring(ctx, 1000, user3)

ArrayItem[T] 同时返回 Index、Exists 和强类型 Value,因此合法的对象零值不会与 Redis Array 空槽混淆。Len 返回“最高使用下标 + 1”的逻辑长度,Count 返回非空槽数;另有 LastItems、Delete、DeleteRanges 和 Clear。Scan 同时兼容 Redis 8.10.0 RESP3 的嵌套 pair 响应和命令文档描述的扁平 pair 响应。

LastItems 跳过 Redis 返回的空槽,合法的对象零值和 JSON null 仍会保留。count 限制 Redis 检查的槽位数,因此结果可能少于 count;需要保留空槽状态时使用 Range 或 GetMany。

该封装保存的是 JSON 字符串,覆盖常用的强类型结构操作。按原始字符串执行的 ARGREP、数值/位聚合 AROP 和运维信息 ARINFO 不在泛型层重复抽象,可通过 redisClient.Client().B() 的 Rueidis 强类型 Builder 直接调用。Array 命令从 Redis 8.8.0 才提供;连接旧版本不会影响其他结构,但调用 Array 方法会返回 Redis 未知命令错误。

Bitmap、Geo 与 HyperLogLog
active := redisClient.Bitmap("active-users")
_, err := active.Set(ctx, userID, true)
enabled, err := active.Get(ctx, userID)
activeCount, err := active.Count(ctx)

cities := redisClient.Geo("cities")
_, err = cities.Add(ctx, rueidistpl.GeoPoint{
    Member: "shanghai", Longitude: 121.4737, Latitude: 31.2304,
})
nearby, err := cities.SearchRadiusByMember(
    ctx, "shanghai", 10, rueidistpl.GeoKilometers,
    rueidistpl.GeoSearchOptions{Count: 20},
)

visitors := redisClient.HyperLogLog("daily-visitors:{2026-08-23}")
_, err = visitors.Add(ctx, "user-1", "user-2")
estimated, err := visitors.Count(ctx)

Bitmap 提供位读写、位区间统计、位查找、BITOP 和单值 BITFIELD_RO;Geo 提供批量坐标、距离、半径搜索、删除和计数;HyperLogLog 提供添加、联合计数和合并。Bitmap.Combine、HyperLogLog.CountWith/MergeFrom 涉及多个 key,在 Cluster 中调用方仍需确保 key 使用相同 hash tag。

JSON 文档、TimeSeries 与 Vector Set
profile := rueidistpl.NewJSONDocument[User](redisClient, "profile:1")
err := profile.Set(ctx, user)
err = profile.SetPath(ctx, "$.name", "Alice")
user, err = profile.Get(ctx)

temperature := redisClient.TimeSeries("temperature:s1")
err = temperature.Create(ctx, rueidistpl.TimeSeriesOptions{
    Retention: 24*time.Hour,
    Labels:    map[string]string{"sensor": "s1"},
})
_, err = temperature.AddNow(ctx, 21.5)
samples, err := temperature.RangeAll(ctx, 100)

products := redisClient.VectorSet("products")
_, err = products.Add(ctx, "p1", []float64{1, 0.5, -1})
matches, err := products.Search(ctx, []float64{1, 0.4, -1},
    rueidistpl.VectorSearchOptions{Count: 10})

JSONDocument[T] 的根读写保持强类型,局部 JSONPath 读取返回 json.RawMessage,不会丢失多匹配结果。TimeSeries 覆盖创建、写入、最新值、正反向范围、增减和区间删除。VectorSet 使用可读的 VALUES 向量参数,覆盖属性、相似搜索、维度、成员判断与删除;VSIM WITHSCORES 同时兼容 RESP3 Map 和 RESP2 Array 响应,并稳定按相似度降序返回。

Redis 8 标准发行版已内置 JSON、TimeSeries 和概率结构;Redis 7.x 等旧版需要安装相应模块。Vector Set 从 Redis 8.0 提供,其中 VectorSet.Contains 使用的 VISMEMBER 需要 Redis 8.2+。

概率数据结构
bloom := redisClient.BloomFilter("seen-orders")
err := bloom.Reserve(ctx, 0.01, 1_000_000)
_, err = bloom.Add(ctx, orderID)
possiblySeen, err := bloom.Exists(ctx, orderID)

frequency := redisClient.CountMinSketch("page-views")
err = frequency.InitByProbability(ctx, 0.01, 0.001)
counts, err := frequency.Increment(ctx,
    rueidistpl.CountMinIncrement{Item: "/home", Delta: 1},
)

latency := redisClient.TDigest("request-latency")
err = latency.Create(ctx, 100)
err = latency.Add(ctx, 12.5, 20, 31.2)
percentiles, err := latency.Quantiles(ctx, 0.5, 0.95, 0.99)

另有支持删除和重复计数的 CuckooFilter,以及返回结构化挤出结果和带计数榜单的 TopK。这些结构都是近似算法:Bloom/Cuckoo 的 true 可能是假阳性,CMS/TopK/t-digest 返回估算值;需要精确集合、计数或排序时应继续使用 Set、Hash/Counter 或 ZSet。

Stream
orders := rueidistpl.NewStream[Order](redisClient, "orders")
err := orders.CreateGroup(ctx, "billing", "0")
id, err := orders.AddMaxLen(ctx, order, 100_000) // MAXLEN ~ 近似限容

entries, err := orders.ReadGroup(ctx, "billing", "worker-1", 20)
// 业务处理成功后确认
_, err = orders.Ack(ctx, "billing", entries[0].ID)

// 定时接管崩溃 worker 长时间未确认的消息
claimed, err := orders.AutoClaim(ctx, "billing", "worker-2", 30*time.Second, "0-0", 100)

groups, err := orders.Groups(ctx)
consumers, err := orders.Consumers(ctx, "billing")
err = orders.SetGroupID(ctx, "billing", "0-0") // 重放时调整投递位置

还提供 Range、Read、ReadBlock、Pending、Claim、TrimMaxLen、DeleteConsumer、DeleteGroup 和 Delete。Claim/AutoClaim 的最小空闲时间不接受负数,正的亚毫秒值会提升为 1ms。AutoClaim 需要 Redis 6.2+,DeletedIDs 只会由 Redis 7.0+ 返回。

Groups 和 Consumers 基于 XINFO 返回强类型运维状态。EntriesReadKnown、LagKnown、InactiveKnown 用于区分真实零值与 Redis 旧版本或当前状态无法提供数据的情况。SetGroupID 可用于重放或跳过历史消息,但不会清理已有 Pending。

AddMaxLen 和 TrimMaxLen 使用 MAXLEN ~ 近似裁剪,换取比精确裁剪更稳定的写入性能,实际长度可能暂时略超过阈值。每条消息统一存放在名为 data 的 JSON field 中;需要多字段原始消息时直接使用 Rueidis。

消费组提供至少一次而不是恰好一次交付。每个并发 worker 必须使用唯一 consumer name,在业务副作用成功后再 Ack,并通过业务唯一约束处理“副作用成功、ACK 前宕机”产生的重复。还应定期处理 Pending、限制重试次数并把毒消息送入死信队列。

Pub/Sub
notifications := rueidistpl.NewPubSub[Notification](redisClient, "notifications")

go func() {
    _ = notifications.Subscribe(ctx, func(message rueidistpl.PubSubMessage[Notification]) error {
        return handle(message.Value)
    }, "created")
}()

_, err := notifications.Publish(ctx, "created", notification)

Subscribe 会阻塞到 context 取消、连接失败或 handler 返回错误;另有 SubscribePattern、SubscribeShard 和 PublishShard。Pub/Sub 是可能丢消息的至多一次通知机制;订单、任务等需要确认与重放的数据必须使用 Stream 或专用消息队列。

幂等与轻量延迟任务
first, err := redisClient.Idempotency("payments").Run(
    ctx, paymentID, 24*time.Hour,
    func(ctx context.Context) error { return charge(ctx, paymentID) },
)

queue := rueidistpl.NewDelayQueue[Job](redisClient, "email-jobs")
err = queue.Schedule(ctx, job.ID, time.Now().Add(5*time.Minute), job)
jobs, err := queue.Claim(ctx, 30*time.Second, 100)
for _, job := range jobs {
    if err := sendEmail(ctx, job.Value); err != nil {
        _, _ = queue.Nack(ctx, job.ID, job.Token, time.Now().Add(time.Minute))
        continue
    }
    acked, err := queue.Ack(ctx, job.ID, job.Token)
    if err != nil || !acked {
        // ACK 结果不确定或租约已经失效,按业务 ID 核对副作用。
    }
}

Idempotency.Run 为每次执行写入随机所有权令牌,按 TTL 的三分之一自动续租,并把续租失败通过业务 context 和 ErrIdempotencyLeaseLost 暴露出来;成功后重新设置完整 TTL,失败时只删除仍属于本次执行的标记。它避免同一时刻的重复执行,但不能替代数据库唯一约束、事务 outbox 或下游幂等接口。

DelayQueue.Claim 使用 Redis 服务端时间领取任务,并通过 visibility timeout 自动恢复崩溃 worker 的任务。每次领取都有独立 token,旧 worker 不能 ACK、NACK 或续租后来重新投递的任务;长任务应在租约到期前调用 Extend。Schedule 同一 ID 会覆盖旧载荷并使旧 token 失效。单次 limit 不得超过 MaxDelayQueuePollBatch(1000)。

旧的 DelayQueue.Poll 仍保留至多一次语义:它会在返回前删除任务,进程崩溃或响应丢失会永久丢任务,只能用于允许丢失的轻量通知。需要重试次数、死信、生产者结果核对等完整能力时优先使用 Stream 或专用任务队列。

分布式锁
err := redisClient.WithFencedLock(ctx, "settle-order", func(lockCtx context.Context, token int64) error {
    // 下游表保存最大 token,并通过 WHERE fencing_token < token 拒绝旧持有者。
    return settleOrder(lockCtx, orderID, token)
})

普通非关键任务可以使用 WithLock;需要手动管理生命周期时使用 Lock/TryLock,并始终监听它们返回的 lockCtx。WithLock 和 WithFencedLock 会在 handler 返回后再次检查租约,非调用方取消导致的锁丢失返回 ErrLockLost。LockFenced/TryLockFenced 提供手动版本。

fencing 计数器不会过期,不能删除;下游资源必须原子拒绝旧 token,仅生成 token 而不校验没有保护作用。Redis 异步复制故障转移仍可能丢失最新计数值,因此资金、库存等严格一致资源最好使用其主数据库生成并校验 fencing token。所有 handler 都必须响应收到的 context,库无法强制停止忽略取消的外部调用。

分布式部署检查清单
  • 所有同一环境实例使用完全相同的 KeyPrefix,不同环境和租户使用不同前缀;不要留空后共享同一 Redis。
  • 锁、幂等和关键状态读取走主节点;把读命令发送到副本会失去读后写一致性。
  • 每次调用设置 context deadline,节点统一 NTP 时间;绝对时间调度仍由调用方时间决定。
  • Stream handler、DelayQueue handler 和外部接口按稳定业务 ID 幂等;Redis 与数据库之间没有自动分布式事务。
  • 在目标部署上测试主从切换、网络分区、续租失败、worker 宕机和 Pending 恢复,不只测试健康拓扑。

原生命令出口

封装未覆盖的命令直接使用 Rueidis,不需要继续扩充工具类:

key := redisClient.Key("stream:orders")
result := redisClient.Client().Do(ctx, redisClient.Client().B().Xlen().Key(key).Build())

版本要求

最低支持 Go 1.26.0。生产环境建议使用所选 Go 系列的最新安全补丁版本。

Redis 版本边界
功能 最低 Redis 版本
基础 String/Hash/List/Set/ZSet、缓存、普通 Stream 6.2(项目默认基线)
Value.GetDelete、Stream.AutoClaim 6.2
Sharded Pub/Sub、AutoClaimResult.DeletedIDs、XINFO entries-read/lag 7.0
XINFO Consumer inactive 7.2
Hash field ExpireField/TTLField/PersistField 7.4
Bitmap、Geo、HyperLogLog 6.2 基线内可用
JSONDocument、TimeSeries、Bloom/Cuckoo/CMS/TopK/TDigest Redis 8 标准版;旧版需要对应模块
Vector Set 基础操作与相似搜索 8.0
VectorSet.Contains (VISMEMBER) 8.2
原生 Array:NewArray[T] 的全部方法 8.8

项目保持 Redis 6.2 基础能力兼容,并将 Redis 8.10.0 作为当前已验证的最高版本。不使用高版本便利 API 时,其他封装不会主动发送这些新命令;这里的“最高版本”表示已验证上限,不会主动拒绝后续 Redis 版本。

部署拓扑
拓扑 支持情况 说明
Standalone 支持 可使用全部符合 Redis 版本要求的封装
Cluster 支持核心路由 跨 Slot 批量操作会逐 key 路由;组合结构自动使用 hash tag
Sentinel 复用 Rueidis 通过 ClientOption.Sentinel 配置连接和认证

Cluster 中,DeleteEach 和 ExistsEach 会逐 key 路由,可以接收跨 Slot 输入。Ranking 和 DelayQueue 会自动让内部 key 共用 Slot。Bitmap.Combine、HyperLogLog.CountWith/MergeFrom 等 Redis 原生多 key 命令仍要求调用方在逻辑 key 中使用相同 {hash-tag}。

组合结构保留普通命名空间原有的键名。如果包含全局前缀的命名空间首次出现的花括号是空 {},生成的 hash tag 会前置,避免 Redis 忽略后面的 tag。此前在单机 Redis 中使用这类特殊命名空间的项目,升级时应根据 Keys() 返回的新键名迁移已有数据;其他命名空间不受影响。

升级建议
  • v0.x 阶段的补丁版本保持公开 API 兼容;次版本可能调整 API,并在更新日志中说明迁移方式。
  • 升级 rueidistpl 前阅读 CHANGELOG.md,重点关注返回值语义、最低 Redis 版本和 key 组织变化。
  • 升级 Redis 或变更 Cluster 部署前,应在目标版本和拓扑上验证高版本命令、节点公布地址、TLS/认证、跨 Slot 路由和 hash tag。
从 v0.1.x 升级到 v0.2.0
  • 将 Go 工具链升级到 1.26.0 或更高版本。
  • 统一检查所有锁使用方的 LockerOption.KeyMajority:默认值已从 1 调整为 2。需要保留原配置时显式设置为 1,并评估 Redis 故障转移时的互斥风险。
  • Cache.GetWithTTL 改为返回毫秒精度的 Redis 服务端 TTL,需要 EVALSHA/EVAL 权限;检查依赖原客户端缓存 TTL 的调用方。
  • 如果命名空间首次出现的花括号为空 {},按 Keys() 返回的新键名迁移 Ranking、DelayQueue 等组合结构的已有数据。

测试

go test -race -cover ./...
go vet ./...

集成测试默认跳过;使用带原生 Array 命令的 Redis 8.8+ 专用实例,通过 Unix socket 显式启用:

RUEIDISTPL_REDIS_SOCKET=/path/to/redis.sock go test -race -cover ./...

集成测试会在独立 key 前缀下写入测试数据,并在结束时清理这些 key。

examples/ 和 examples/redis8/ 分别演示核心能力与 Redis 8 高版本结构,可用 go run ./examples 和 go run ./examples/redis8 运行。核心 TCP 集成测试使用 RUEIDISTPL_INTEGRATION=1,原生 Array 测试使用 RUEIDISTPL_ARRAY_INTEGRATION=1,连接地址及认证通过 REDIS_ADDR 和 REDIS_PASSWORD 配置。

检查工具由 go.mod 的 tool 指令固定,可执行 go tool staticcheck ./... 与 go tool govulncheck ./...。Go 1.26.0 用于最低版本兼容测试;漏洞扫描应使用当前安全补丁工具链。

Documentation

Overview

Package rueidistpl 在 Rueidis、gocache 和 rueidislock 之上提供面向业务的轻量封装。

包内统一处理 Redis 连接配置、key 前缀、JSON 编解码和常用数据结构,包括 Bitmap、Geo、 HyperLogLog、Redis 8 的 JSON/TimeSeries/Vector Set/概率结构,以及 Redis 8.8+ 原生稀疏 Array,同时保留 Redis.Client 原生出口。连接管理、客户端缓存和分布式锁续期仍由成熟的 上游库负责,本包不重复实现 Redis 协议、连接池或锁算法。

Index

Constants

View Source
const MaxDelayQueuePollBatch int64 = 1000

MaxDelayQueuePollBatch 是 Poll 和 Claim 允许的最大单次任务数。 该上限同时约束 Lua unpack 参数量、Redis 执行时间和网络响应大小。

View Source
const MaxRankingPageSize int64 = 1000

MaxRankingPageSize 限制 Page 单次读取的条目数,避免一次 Lua 处理过大的排行榜。

Variables

View Source
var (
	// ErrArrayValuesRequired 表示 ARINSERT/ARRING 缺少 Redis 要求的至少一个 value。
	ErrArrayValuesRequired = errors.New("rueidistpl: array requires at least one value")
	// ErrInvalidArrayRingSize 表示 ARRING 的窗口大小不是正数。
	ErrInvalidArrayRingSize = errors.New("rueidistpl: array ring size must be positive")
)
View Source
var (
	// ErrInvalidBitOffset 表示位偏移为负数。
	ErrInvalidBitOffset = errors.New("rueidistpl: bit offset must not be negative")
	// ErrInvalidBitmapOperation 表示 BITOP 操作不是 AND、OR、XOR 或 NOT。
	ErrInvalidBitmapOperation = errors.New("rueidistpl: invalid bitmap operation")
)
View Source
var (
	// ErrInvalidBloomErrorRate 表示 Bloom Filter 误判率不在 (0,1) 范围内。
	ErrInvalidBloomErrorRate = errors.New("rueidistpl: bloom filter error rate must be between 0 and 1")
	// ErrInvalidBloomCapacity 表示 Bloom Filter 预计容量不是正数。
	ErrInvalidBloomCapacity = errors.New("rueidistpl: bloom filter capacity must be positive")
)
View Source
var (
	// ErrClosed 表示 Redis 门面已经关闭,不能再创建或获取锁客户端。
	ErrClosed = errors.New("rueidistpl: redis client is closed")
	// ErrInvalidLockerConfig 表示锁续期间隔不足以在租约过期前安全续期。
	ErrInvalidLockerConfig = errors.New("rueidistpl: invalid locker configuration")
	// ErrLockLost 表示业务执行期间已失去分布式锁租约。
	ErrLockLost = errors.New("rueidistpl: distributed lock lease lost")
	// ErrNilLockHandler 表示 WithLock 或 WithFencedLock 没有收到业务函数。
	ErrNilLockHandler = errors.New("rueidistpl: lock handler must not be nil")
)
View Source
var (
	// ErrInvalidCountMinDimensions 表示宽度或深度不是正数。
	ErrInvalidCountMinDimensions = errors.New("rueidistpl: count-min sketch width and depth must be positive")
	// ErrInvalidCountMinProbability 表示误差率或失败概率不在 (0,1) 范围内。
	ErrInvalidCountMinProbability = errors.New("rueidistpl: count-min sketch error rate and probability must be between 0 and 1")
	// ErrInvalidCountMinIncrement 表示增量不是正数。
	ErrInvalidCountMinIncrement = errors.New("rueidistpl: count-min sketch increment must be positive")
)
View Source
var (
	// ErrInvalidGeoCoordinate 表示经纬度超出 Redis GEO 接受范围。
	ErrInvalidGeoCoordinate = errors.New("rueidistpl: invalid geo coordinate")
	// ErrInvalidGeoUnit 表示距离单位不是 m、km、ft 或 mi。
	ErrInvalidGeoUnit = errors.New("rueidistpl: invalid geo unit")
	// ErrInvalidGeoRadius 表示搜索半径不是正数。
	ErrInvalidGeoRadius = errors.New("rueidistpl: geo radius must be positive")
)
View Source
var (
	// ErrInvalidTDigestCompression 表示压缩参数不是正数。
	ErrInvalidTDigestCompression = errors.New("rueidistpl: t-digest compression must be positive")
	// ErrInvalidTDigestValue 表示输入样本或查询值不是有限数。
	ErrInvalidTDigestValue = errors.New("rueidistpl: t-digest value must be finite")
	// ErrInvalidTDigestQuantile 表示分位点不在 [0,1] 范围内。
	ErrInvalidTDigestQuantile = errors.New("rueidistpl: t-digest quantile must be between 0 and 1")
)
View Source
var (
	// ErrInvalidTimeSeriesRetention 表示保留时间不能为负数。
	ErrInvalidTimeSeriesRetention = errors.New("rueidistpl: time series retention must not be negative")
	// ErrInvalidTimeSeriesValue 表示样本值是 NaN 或无穷大。
	ErrInvalidTimeSeriesValue = errors.New("rueidistpl: time series value must be finite")
)
View Source
var (
	// ErrInvalidTopK 表示跟踪的 Top-K 数量不是正数。
	ErrInvalidTopK = errors.New("rueidistpl: top-k size must be positive")
	// ErrInvalidTopKOptions 表示 width、depth 或 decay 配置无效。
	ErrInvalidTopKOptions = errors.New("rueidistpl: invalid top-k options")
)
View Source
var (
	// ErrVectorRequired 表示向量至少需要一个维度。
	ErrVectorRequired = errors.New("rueidistpl: vector must not be empty")
	// ErrInvalidVectorValue 表示向量包含 NaN 或无穷大。
	ErrInvalidVectorValue = errors.New("rueidistpl: vector values must be finite")
)
View Source
var ErrDelayQueuePollLimit = errors.New("rueidistpl: delay queue poll limit exceeds maximum batch size")

ErrDelayQueuePollLimit 表示 Poll 或 Claim 的 limit 超过了安全批次上限。

View Source
var ErrEmptyChannels = errors.New("rueidistpl: at least one channel is required")

ErrEmptyChannels 表示订阅时没有提供任何 channel 或 pattern。

View Source
var ErrHyperLogLogSourcesRequired = errors.New("rueidistpl: hyperloglog merge requires at least one source")

ErrHyperLogLogSourcesRequired 表示 PFMERGE 没有提供任何来源 key。

View Source
var ErrIdempotencyLeaseLost = errors.New("rueidistpl: idempotency lease lost")

ErrIdempotencyLeaseLost 表示 Run 执行期间幂等标记已过期、被替换或无法续租。 收到该错误时不能假设业务未执行,调用方应依靠下游唯一约束或业务状态进行核对。

View Source
var ErrInvalidBatchResponse = errors.New("rueidistpl: invalid batch response")

ErrInvalidBatchResponse 表示 Rueidis 返回的批量结果数量或单 key 状态值不符合命令约定。

View Source
var ErrInvalidCuckooCapacity = errors.New("rueidistpl: cuckoo filter capacity must be positive")

ErrInvalidCuckooCapacity 表示 Cuckoo Filter 预计容量不是正数。

View Source
var ErrInvalidExpiration = errors.New("rueidistpl: expiration must be greater than zero")

ErrInvalidExpiration 表示要求过期的操作收到零值或负数 TTL。

View Source
var ErrInvalidExpirationResponse = errors.New("rueidistpl: invalid expiration response")

ErrInvalidExpirationResponse 表示 Redis 返回了 PTTL/HPTTL 约定之外的负数状态码。

View Source
var ErrInvalidMinIdle = errors.New("rueidistpl: stream minimum idle time must not be negative")

ErrInvalidMinIdle 表示 XCLAIM 收到了负数最小空闲时间。

View Source
var ErrInvalidRankingPage = errors.New("rueidistpl: invalid ranking page")

ErrInvalidRankingPage 表示分页偏移为负数、页大小不在 [1, MaxRankingPageSize] 内或下标溢出。

View Source
var ErrInvalidScore = errors.New("rueidistpl: sorted set score must not be NaN")

ErrInvalidScore 表示 ZSet 操作收到了 Redis 不接受的 NaN 分数。 正负无穷是 Redis 支持的合法边界,因此不会触发该错误。

View Source
var ErrInvalidStreamMaxLen = errors.New("rueidistpl: stream maximum length must be positive")

ErrInvalidStreamMaxLen 表示 Stream 最大长度不是正数。

View Source
var ErrRankingScoreMissing = errors.New("rueidistpl: ranking object has no score")

ErrRankingScoreMissing 表示 Hash 中存在排行榜对象,但对应 ZSet 分数已经缺失。

View Source
var ErrRankingValueMissing = errors.New("rueidistpl: ranking member has no object value")

ErrRankingValueMissing 表示 ZSet 中存在排行榜 ID,但对应 Hash 对象已经缺失。

View Source
var ErrStreamDataMissing = errors.New("rueidistpl: stream entry has no data field")

ErrStreamDataMissing 表示消息不是由本封装写入,缺少约定的 data 字段。

Functions

func IsNotFound

func IsNotFound(err error) bool

IsNotFound 统一判断 gocache 缓存未命中和 Rueidis Redis Nil。 因此可用于 Cache、Value、Hash、List、Ranking 等单值读取 API。

Types

type Array

type Array[T any] struct {
	// contains filtered or unexported fields
}

Array 使用 Redis 8.8+ 原生 Array 保存 JSON 对象。 Array 可以高效表示稀疏下标;连接 Redis 8.6 及以下版本时,调用这些方法会收到未知命令错误。

func NewArray

func NewArray[T any](redis *Redis, key string) *Array[T]

NewArray 创建保存 JSON 对象的 Redis 8.8+ Array,并自动应用全局 key 前缀。

func (*Array[T]) Clear

func (array *Array[T]) Clear(ctx context.Context) error

Clear 删除整个 Array key。

func (*Array[T]) Count

func (array *Array[T]) Count(ctx context.Context) (int64, error)

Count 返回非空槽位数。

func (*Array[T]) Delete

func (array *Array[T]) Delete(ctx context.Context, indices ...int64) (int64, error)

Delete 删除指定下标的非空槽位并返回实际删除数;空输入返回 0。

func (*Array[T]) DeleteRanges

func (array *Array[T]) DeleteRanges(ctx context.Context, ranges ...ArrayRange) (int64, error)

DeleteRanges 删除一个或多个下标闭区间并返回实际删除数;空输入返回 0。

func (*Array[T]) Get

func (array *Array[T]) Get(ctx context.Context, index int64) (T, error)

Get 返回指定下标的对象。 key 或槽位不存在时返回 Rueidis Nil 错误,其他错误同样返回 T 的零值。

func (*Array[T]) GetMany

func (array *Array[T]) GetMany(ctx context.Context, indices ...int64) ([]ArrayItem[T], error)

GetMany 按传入顺序批量读取下标,并通过 Exists 明确区分空槽与 T 的零值。 空输入返回已初始化的空切片且不访问 Redis。

func (*Array[T]) Insert

func (array *Array[T]) Insert(ctx context.Context, values ...T) (int64, error)

Insert 从内部插入游标开始连续追加对象,并返回最后写入的下标。 可用 Next 查看游标、Seek 调整游标;空输入返回 ErrArrayValuesRequired。

func (*Array[T]) Key

func (array *Array[T]) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*Array[T]) LastItems

func (array *Array[T]) LastItems(ctx context.Context, count int64, reverse bool) ([]T, error)

LastItems 返回最近插入的最多 count 个对象。 reverse=false 按从旧到新的插入顺序返回,reverse=true 按从新到旧返回;count 非正时返回空切片。 count 限制 Redis 检查的槽位数,空槽会被跳过,因此实际返回的对象数可能更少。 需要保留空槽状态时使用 Range 或 GetMany。

func (*Array[T]) Len

func (array *Array[T]) Len(ctx context.Context) (int64, error)

Len 返回逻辑长度,即最高使用下标加一;稀疏数组的 Len 可能大于 Count。

func (*Array[T]) Next

func (array *Array[T]) Next(ctx context.Context) (int64, error)

Next 返回下一次 Insert/Ring 将使用的下标。 插入游标溢出时 Redis 返回 Nil,此方法返回 0 和对应错误。

func (*Array[T]) Range

func (array *Array[T]) Range(ctx context.Context, start, end int64) ([]ArrayItem[T], error)

Range 返回 start 到 end 的闭区间;start>end 时按下标倒序返回。 Redis 的空槽不会被丢弃,而是表示为 Exists=false 的 ArrayItem。

func (*Array[T]) Ring

func (array *Array[T]) Ring(ctx context.Context, size int64, values ...T) (int64, error)

Ring 按固定窗口大小循环写入对象,并返回最后写入的下标。 size 必须为正数,values 不能为空;缩小 size 时 Redis 会截断超出窗口的槽位。

func (*Array[T]) Scan

func (array *Array[T]) Scan(ctx context.Context, start, end, limit int64) ([]ArrayItem[T], error)

Scan 只返回 start 到 end 闭区间内的非空槽位,start>end 时按下标倒序扫描。 limit 大于 0 时限制最多返回的槽位数,非正值表示不添加 LIMIT。

func (*Array[T]) Seek

func (array *Array[T]) Seek(ctx context.Context, index int64) (bool, error)

Seek 设置 Insert/Ring 的下一个写入下标,并返回 key 是否存在。

func (*Array[T]) Set

func (array *Array[T]) Set(ctx context.Context, start int64, values ...T) (int64, error)

Set 从 start 开始连续写入对象,返回原先为空、此次新建的槽位数。 空输入返回 0 且不访问 Redis。

func (*Array[T]) SetMany

func (array *Array[T]) SetMany(ctx context.Context, values map[int64]T) (int64, error)

SetMany 按任意下标批量写入对象,返回原先为空、此次新建的槽位数。 为使命令和测试可复现,下标会按升序发送;空 map 返回 0 且不访问 Redis。

type ArrayItem

type ArrayItem[T any] struct {
	Index  int64
	Exists bool
	Value  T
}

ArrayItem 表示 Redis Array 的一个下标。 Exists=false 表示该下标是空槽,此时 Value 保持 T 的零值。

type ArrayRange

type ArrayRange struct {
	Start int64
	End   int64
}

ArrayRange 表示 ARDELRANGE 使用的下标闭区间。

type AutoClaimResult

type AutoClaimResult[T any] struct {
	// NextStart 是下一次扫描时应传入的起始 ID;返回 0-0 表示本轮扫描结束。
	NextStart string
	// Entries 是本次转移到新消费者名下的消息。
	Entries []StreamEntry[T]
	// DeletedIDs 是在 Pending 列表中但已从 Stream 删除的 ID;Redis 7.0 起才会返回。
	DeletedIDs []string
}

AutoClaimResult 是 XAUTOCLAIM 的强类型返回值。

type Bitmap

type Bitmap struct {
	// contains filtered or unexported fields
}

Bitmap 使用 Redis String 的位操作保存布尔状态集合。

func (*Bitmap) BitFieldGet

func (bitmap *Bitmap) BitFieldGet(ctx context.Context, encoding string, offset int64) (int64, error)

BitFieldGet 将 String 中的一段位按 Redis BITFIELD 编码读取为整数。 encoding 使用 Redis 原生格式,例如 i8、u16;复杂的批量和溢出策略应直接使用 Rueidis Builder。

func (*Bitmap) Clear

func (bitmap *Bitmap) Clear(ctx context.Context) error

Clear 删除整个位图 key。

func (*Bitmap) Combine

func (bitmap *Bitmap) Combine(ctx context.Context, operation BitmapOperation, destination string, additionalSources ...string) (int64, error)

Combine 将当前位图和 additionalSources 做位运算,结果写入逻辑 destination key,并返回结果字节数。 operation 支持 AND、OR、XOR 和 NOT;NOT 只能使用当前位图,不能提供 additionalSources。 Redis Cluster 要求 destination、当前 key 和所有 source 位于同一 slot。

func (*Bitmap) Count

func (bitmap *Bitmap) Count(ctx context.Context) (int64, error)

Count 返回整个位图中值为 1 的位数。

func (*Bitmap) CountBits

func (bitmap *Bitmap) CountBits(ctx context.Context, start, end int64) (int64, error)

CountBits 返回位下标闭区间内值为 1 的位数。

func (*Bitmap) Get

func (bitmap *Bitmap) Get(ctx context.Context, offset int64) (bool, error)

Get 返回 offset 对应的位。

func (*Bitmap) Key

func (bitmap *Bitmap) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*Bitmap) Position

func (bitmap *Bitmap) Position(ctx context.Context, value bool) (int64, error)

Position 返回整个位图中第一个等于 value 的位下标;未找到时返回 -1。

func (*Bitmap) PositionBits

func (bitmap *Bitmap) PositionBits(ctx context.Context, value bool, start, end int64) (int64, error)

PositionBits 返回位下标闭区间内第一个等于 value 的位下标;未找到时返回 -1。

func (*Bitmap) Set

func (bitmap *Bitmap) Set(ctx context.Context, offset int64, value bool) (bool, error)

Set 设置 offset 对应的位并返回修改前的值。

type BitmapOperation

type BitmapOperation string

BitmapOperation 表示 BITOP 支持的经典位运算。

const (
	BitmapAnd BitmapOperation = "AND"
	BitmapOr  BitmapOperation = "OR"
	BitmapXor BitmapOperation = "XOR"
	BitmapNot BitmapOperation = "NOT"
)

type BloomFilter

type BloomFilter struct {
	// contains filtered or unexported fields
}

BloomFilter 封装 RedisBloom 的 Bloom Filter 常用操作。 它适合空间敏感且允许少量假阳性的存在性判断。

func (*BloomFilter) Add

func (filter *BloomFilter) Add(ctx context.Context, item string) (bool, error)

Add 添加元素;至少一个位从 0 变成 1 时返回 true。 未 Reserve 时 Redis 会使用默认配置自动创建过滤器。

func (*BloomFilter) AddMany

func (filter *BloomFilter) AddMany(ctx context.Context, items ...string) ([]bool, error)

AddMany 批量添加并返回与输入顺序一一对应的变化结果;空输入不发送命令。

func (*BloomFilter) Card

func (filter *BloomFilter) Card(ctx context.Context) (int64, error)

Card 返回成功加入过滤器的近似唯一元素数。

func (*BloomFilter) Clear

func (filter *BloomFilter) Clear(ctx context.Context) error

Clear 删除整个过滤器。

func (*BloomFilter) Exists

func (filter *BloomFilter) Exists(ctx context.Context, item string) (bool, error)

Exists 判断元素可能存在时返回 true;true 可能是假阳性,false 一定表示不存在。

func (*BloomFilter) ExistsMany

func (filter *BloomFilter) ExistsMany(ctx context.Context, items ...string) ([]bool, error)

ExistsMany 批量判断并保持输入顺序;空输入不发送命令。

func (*BloomFilter) Key

func (filter *BloomFilter) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*BloomFilter) Reserve

func (filter *BloomFilter) Reserve(ctx context.Context, errorRate float64, capacity int64) error

Reserve 按目标误判率和预计容量显式创建过滤器。

type Cache

type Cache[T any] struct {
	// contains filtered or unexported fields
}

Cache 是基于 gocache Rueidis Store 的 JSON 对象缓存。

func NewCache

func NewCache[T any](redis *Redis, prefix string) *Cache[T]

NewCache 创建按业务 ID 分项存储的 TTL 对象缓存。 最终 key 形式为“全局前缀:prefix:id”。

func (*Cache[T]) Delete

func (cache *Cache[T]) Delete(ctx context.Context, key string) error

Delete 删除指定业务 ID 的缓存对象。

func (*Cache[T]) Get

func (cache *Cache[T]) Get(ctx context.Context, key string) (T, error)

Get 读取并反序列化对象;缓存未命中可通过 IsNotFound 判断。 发生任何错误时返回 T 的零值。

func (*Cache[T]) GetWithTTL

func (cache *Cache[T]) GetWithTTL(ctx context.Context, key string) (T, time.Duration, error)

GetWithTTL 原子读取对象及 Redis key 的剩余 TTL,精度为毫秒,不使用客户端缓存。 -1ms 表示对象不过期;未命中可用 IsNotFound 判断;发生错误时对象和 TTL 都返回零值。

func (*Cache[T]) Prefix

func (cache *Cache[T]) Prefix() string

Prefix 返回应用全局前缀后的真实缓存 key 前缀。

func (*Cache[T]) Set

func (cache *Cache[T]) Set(ctx context.Context, key string, value T, ttl ...time.Duration) error

Set 写入对象。省略 ttl 时使用 Config.CacheTTL。

type ClaimedDelayed added in v0.2.0

type ClaimedDelayed[T any] struct {
	Delayed[T]
	Token string
}

ClaimedDelayed 是通过 Claim 取得、等待 ACK 或 NACK 的任务。 Token 是本次领取的所有权凭证;旧 worker 的 token 不能确认后来重新投递的同一任务。

type Config

type Config struct {
	// ClientOption 是 Rueidis 原生连接配置,例如地址、认证、集群和连接池参数。
	ClientOption rueidis.ClientOption
	// KeyPrefix 会自动添加到本包管理的全部业务 key 前面。
	KeyPrefix string
	// CacheTTL 是 NewCache[T] 的默认过期时间,非正值使用 10 分钟。
	CacheTTL time.Duration
	// ClientSideCacheTTL 控制 gocache Rueidis Store 的客户端缓存时间。
	ClientSideCacheTTL time.Duration
	// LockerOption 配置 rueidislock;其中 ClientOption 会统一使用上面的连接配置。
	LockerOption rueidislock.LockerOption
}

Config 复用 Rueidis 与 rueidislock 的原生配置,只补充模板需要的缓存默认值。

type CountMinIncrement

type CountMinIncrement struct {
	Item  string
	Delta int64
}

CountMinIncrement 是一个元素及其正整数增量。

type CountMinSketch

type CountMinSketch struct {
	// contains filtered or unexported fields
}

CountMinSketch 封装 RedisBloom 的 Count-Min Sketch 高频计数操作。

func (*CountMinSketch) Clear

func (sketch *CountMinSketch) Clear(ctx context.Context) error

Clear 删除整个草图。

func (*CountMinSketch) Increment

func (sketch *CountMinSketch) Increment(ctx context.Context, increments ...CountMinIncrement) ([]int64, error)

Increment 批量增加元素计数,并返回与输入顺序对应的新估算值;空输入不发送命令。

func (*CountMinSketch) InitByDimensions

func (sketch *CountMinSketch) InitByDimensions(ctx context.Context, width, depth int64) error

InitByDimensions 按宽度和深度显式初始化草图。

func (*CountMinSketch) InitByProbability

func (sketch *CountMinSketch) InitByProbability(ctx context.Context, errorRate, probability float64) error

InitByProbability 按误差率和失败概率显式初始化草图。

func (*CountMinSketch) Key

func (sketch *CountMinSketch) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*CountMinSketch) Query

func (sketch *CountMinSketch) Query(ctx context.Context, items ...string) ([]int64, error)

Query 批量查询估算计数并保持输入顺序;空输入不发送命令。

type Counter

type Counter struct {
	// contains filtered or unexported fields
}

Counter 是使用 Redis String 实现的 int64 原子计数器。

func (*Counter) Add

func (counter *Counter) Add(ctx context.Context, delta int64) (int64, error)

Add 原子增加 delta,并返回增加后的值;delta 可以为负数。

func (*Counter) Delete

func (counter *Counter) Delete(ctx context.Context) error

Delete 删除计数器。

func (*Counter) Get

func (counter *Counter) Get(ctx context.Context) (int64, error)

Get 返回当前计数值。

func (*Counter) Increment

func (counter *Counter) Increment(ctx context.Context) (int64, error)

Increment 原子加一并返回新值。

func (*Counter) Key

func (counter *Counter) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*Counter) Set

func (counter *Counter) Set(ctx context.Context, value int64) error

Set 覆盖当前计数值。

type CuckooFilter

type CuckooFilter struct {
	// contains filtered or unexported fields
}

CuckooFilter 封装 RedisBloom 的 Cuckoo Filter 常用操作。 相比 Bloom Filter,它支持删除元素和统计同一元素的插入次数。

func (*CuckooFilter) Add

func (filter *CuckooFilter) Add(ctx context.Context, item string) (bool, error)

Add 添加元素;未 Reserve 时 Redis 会使用默认配置自动创建过滤器。

func (*CuckooFilter) AddNX

func (filter *CuckooFilter) AddNX(ctx context.Context, item string) (bool, error)

AddNX 仅当元素被判断为不存在时添加;由于概率结构可能假阳性,false 不保证元素确实已插入过。

func (*CuckooFilter) Clear

func (filter *CuckooFilter) Clear(ctx context.Context) error

Clear 删除整个过滤器。

func (*CuckooFilter) Count

func (filter *CuckooFilter) Count(ctx context.Context, item string) (int64, error)

Count 返回元素大约被添加了多少次。

func (*CuckooFilter) Delete

func (filter *CuckooFilter) Delete(ctx context.Context, item string) (bool, error)

Delete 删除一次元素指纹,实际删除时返回 true。

func (*CuckooFilter) Exists

func (filter *CuckooFilter) Exists(ctx context.Context, item string) (bool, error)

Exists 判断元素可能存在时返回 true。

func (*CuckooFilter) ExistsMany

func (filter *CuckooFilter) ExistsMany(ctx context.Context, items ...string) ([]bool, error)

ExistsMany 批量判断并保持输入顺序;空输入不发送命令。

func (*CuckooFilter) Key

func (filter *CuckooFilter) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*CuckooFilter) Reserve

func (filter *CuckooFilter) Reserve(ctx context.Context, capacity int64) error

Reserve 按预计容量显式创建过滤器。

type DelayQueue

type DelayQueue[T any] struct {
	// contains filtered or unexported fields
}

DelayQueue 是基于 Hash + ZSet 的延迟队列。 Claim 提供可见性超时与 ACK/NACK;兼容入口 Poll 仍是取出即删除的至多一次语义。

func NewDelayQueue

func NewDelayQueue[T any](redis *Redis, namespace string) *DelayQueue[T]

NewDelayQueue 创建延迟队列;内部 key 自动使用相同的 Redis Cluster hash tag。

func (*DelayQueue[T]) Ack added in v0.2.0

func (queue *DelayQueue[T]) Ack(ctx context.Context, id, token string) (bool, error)

Ack 按所有权 token 确认任务完成,并永久删除载荷;token 已失效时返回 false。

func (*DelayQueue[T]) Claim added in v0.2.0

func (queue *DelayQueue[T]) Claim(ctx context.Context, visibilityTimeout time.Duration, limit int64) ([]ClaimedDelayed[T], error)

Claim 使用 Redis 服务端时间领取到期任务,并设置 visibilityTimeout。 worker 崩溃后,租约到期的任务会在后续 Claim 中自动重新投递;成功必须调用 Ack,失败可调用 Nack。 网络错误意味着领取结果不确定,调用方应等待租约到期,不能立即无条件重试同一批业务副作用。

func (*DelayQueue[T]) Clear

func (queue *DelayQueue[T]) Clear(ctx context.Context) error

Clear 删除队列的载荷、调度、处理中任务和所有权记录。

func (*DelayQueue[T]) Extend added in v0.2.0

func (queue *DelayQueue[T]) Extend(ctx context.Context, id, token string, visibilityTimeout time.Duration) (bool, error)

Extend 按所有权 token 延长尚未到期的处理租约;租约已失效时返回 false。

func (*DelayQueue[T]) InFlight added in v0.2.0

func (queue *DelayQueue[T]) InFlight(ctx context.Context) (int64, error)

InFlight 返回正在处理、尚未 ACK/NACK 的任务数量。

func (*DelayQueue[T]) Keys

func (queue *DelayQueue[T]) Keys() (valuesKey, scoresKey string)

Keys 返回内部载荷 Hash 和调度 ZSet 的真实 key,主要用于监控和清理。

func (*DelayQueue[T]) Len

func (queue *DelayQueue[T]) Len(ctx context.Context) (int64, error)

Len 返回当前等待调度的任务数量。

func (*DelayQueue[T]) Nack added in v0.2.0

func (queue *DelayQueue[T]) Nack(ctx context.Context, id, token string, dueAt time.Time) (bool, error)

Nack 按所有权 token 将任务重新调度到 dueAt;token 已失效时返回 false。

func (*DelayQueue[T]) Poll

func (queue *DelayQueue[T]) Poll(ctx context.Context, now time.Time, limit int64) ([]Delayed[T], error)

Poll 原子取出并删除不晚于 now 的任务。 limit 不得超过 MaxDelayQueuePollBatch;由于是至多一次语义,被取出后即使 JSON 解码失败,任务也已从 Redis 删除。

func (*DelayQueue[T]) ReliableKeys added in v0.2.0

func (queue *DelayQueue[T]) ReliableKeys() (processingKey, claimsKey string)

ReliableKeys 返回可靠消费额外使用的处理中 ZSet 和所有权 Hash。

func (*DelayQueue[T]) Remove

func (queue *DelayQueue[T]) Remove(ctx context.Context, id string) (bool, error)

Remove 原子删除任务载荷和调度记录;任务存在时返回 true。

func (*DelayQueue[T]) Schedule

func (queue *DelayQueue[T]) Schedule(ctx context.Context, id string, dueAt time.Time, value T) error

Schedule 原子保存任务载荷和执行时间;相同 ID 会覆盖之前的任务。

type Delayed

type Delayed[T any] struct {
	// ID 是调度时指定的稳定任务标识;重复调度相同 ID 会覆盖原任务。
	ID string
	// DueAt 是任务原定执行时间,精度为毫秒。
	DueAt time.Time
	// Value 是反序列化后的任务载荷。
	Value T
}

Delayed 表示从延迟队列取出的到期任务。

type DeleteBatchResult

type DeleteBatchResult struct {
	Results []DeleteKeyResult
	Deleted int64
	Err     error
}

DeleteBatchResult 同时保留逐 key 状态、成功删除总数和聚合错误。 即使 Err 非空,Results 中其他成功项和 Deleted 仍然有效。

type DeleteKeyResult

type DeleteKeyResult struct {
	Key     string
	Deleted bool
	Err     error
}

DeleteKeyResult 记录 DeleteEach 中一个逻辑 key 的执行结果。

type ExistsBatchResult

type ExistsBatchResult struct {
	Results  []ExistsKeyResult
	Existing int64
	Err      error
}

ExistsBatchResult 同时保留逐 key 状态、实际存在总数和聚合错误。 即使 Err 非空,Results 中其他成功项和 Existing 仍然有效。

type ExistsKeyResult

type ExistsKeyResult struct {
	Key    string
	Exists bool
	Err    error
}

ExistsKeyResult 记录 ExistsEach 中一个逻辑 key 的存在状态。

type ExpirationInfo

type ExpirationInfo struct {
	Exists     bool
	Persistent bool
	TTL        time.Duration
}

ExpirationInfo 是已经解释过 Redis 特殊 TTL 状态的结构化结果。

Exists=false 表示 key 或 field 不存在;Persistent=true 表示对象存在但没有过期时间; 只有 Exists=true 且 Persistent=false 时,TTL 才表示剩余有效期。

type Geo

type Geo struct {
	// contains filtered or unexported fields
}

Geo 是 Redis Geospatial 索引的便利封装。

func (*Geo) Add

func (geo *Geo) Add(ctx context.Context, points ...GeoPoint) (int64, error)

Add 添加或更新地理位置,并返回新增成员数;空输入返回 0。

func (*Geo) Clear

func (geo *Geo) Clear(ctx context.Context) error

Clear 删除整个 GEO key。

func (*Geo) Distance

func (geo *Geo) Distance(ctx context.Context, member1, member2 string, unit GeoUnit) (float64, error)

Distance 返回两个成员之间按 unit 表示的距离;成员不存在时返回 Rueidis Nil。

func (*Geo) Key

func (geo *Geo) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*Geo) Len

func (geo *Geo) Len(ctx context.Context) (int64, error)

Len 返回地理位置成员数。

func (*Geo) Position

func (geo *Geo) Position(ctx context.Context, member string) (GeoPosition, error)

Position 返回单个成员坐标;成员不存在时 Exists=false。

func (*Geo) Positions

func (geo *Geo) Positions(ctx context.Context, members ...string) ([]GeoPosition, error)

Positions 按输入顺序返回成员坐标,并通过 Exists 区分不存在成员;空输入返回空切片。

func (*Geo) Remove

func (geo *Geo) Remove(ctx context.Context, members ...string) (int64, error)

Remove 删除成员并返回实际删除数;空输入返回 0。

func (*Geo) SearchRadius

func (geo *Geo) SearchRadius(ctx context.Context, longitude, latitude, radius float64, unit GeoUnit, options GeoSearchOptions) ([]GeoSearchResult, error)

SearchRadius 以经纬度为圆心搜索,并始终返回成员、距离和坐标。

func (*Geo) SearchRadiusByMember

func (geo *Geo) SearchRadiusByMember(ctx context.Context, member string, radius float64, unit GeoUnit, options GeoSearchOptions) ([]GeoSearchResult, error)

SearchRadiusByMember 以已有 member 为圆心搜索,并始终返回成员、距离和坐标。

type GeoPoint

type GeoPoint struct {
	Member    string
	Longitude float64
	Latitude  float64
}

GeoPoint 是待写入的地理位置。

type GeoPosition

type GeoPosition struct {
	Member    string
	Exists    bool
	Longitude float64
	Latitude  float64
}

GeoPosition 是一个成员的位置;Exists=false 表示成员不存在。

type GeoSearchOptions

type GeoSearchOptions struct {
	// Count 大于 0 时限制结果数。
	Count int64
	// Any 允许 Redis 在找到足够结果后提前停止;只有 Count>0 时有效。
	Any bool
	// Desc 为 true 时按距离从远到近返回,默认从近到远。
	Desc bool
}

GeoSearchOptions 控制半径搜索的数量和顺序。

type GeoSearchResult

type GeoSearchResult struct {
	Member    string
	Distance  float64
	Longitude float64
	Latitude  float64
}

GeoSearchResult 是带距离和坐标的 GEOSEARCH 结果。

type GeoUnit

type GeoUnit string

GeoUnit 是 Redis GEO 距离单位。

const (
	GeoMeters     GeoUnit = "m"
	GeoKilometers GeoUnit = "km"
	GeoFeet       GeoUnit = "ft"
	GeoMiles      GeoUnit = "mi"
)

type Hash

type Hash[T any] struct {
	// contains filtered or unexported fields
}

Hash 使用 Redis Hash 保存 JSON 对象,field 通常使用稳定业务 ID。

func NewHash

func NewHash[T any](redis *Redis, key string) *Hash[T]

NewHash 创建 field 到 JSON 对象的类型化映射。

func (*Hash[T]) All

func (hash *Hash[T]) All(ctx context.Context) (map[string]T, error)

All 返回 Hash 中的全部 field 和对象,适合数据量明确较小的场景。

func (*Hash[T]) Clear

func (hash *Hash[T]) Clear(ctx context.Context) error

Clear 删除整个 Hash key。

func (*Hash[T]) Delete

func (hash *Hash[T]) Delete(ctx context.Context, fields ...string) (int64, error)

Delete 删除一个或多个 field,并返回实际删除数量。

func (*Hash[T]) Exists

func (hash *Hash[T]) Exists(ctx context.Context, field string) (bool, error)

Exists 判断 field 是否存在。

func (*Hash[T]) ExpirationField

func (hash *Hash[T]) ExpirationField(ctx context.Context, field string) (ExpirationInfo, error)

ExpirationField 返回结构化 field 过期状态,避免调用方自行解释 HPTTL 的 -1ms/-2ms。

func (*Hash[T]) ExpireField

func (hash *Hash[T]) ExpireField(ctx context.Context, field string, ttl time.Duration) (bool, error)

ExpireField 设置单个 Hash field 的 TTL,需要 Redis 7.4+。

func (*Hash[T]) Get

func (hash *Hash[T]) Get(ctx context.Context, field string) (T, error)

Get 读取并反序列化单个 field;field 不存在时返回 Redis Nil 错误。 发生任何错误时返回 T 的零值。

func (*Hash[T]) GetMany

func (hash *Hash[T]) GetMany(ctx context.Context, fields ...string) (map[string]T, error)

GetMany 返回存在的 field;不存在的 field 不写入结果 map。

func (*Hash[T]) IncrementFloat

func (hash *Hash[T]) IncrementFloat(ctx context.Context, field string, delta float64) (float64, error)

IncrementFloat 原子增加浮点 field,并返回增加后的值。

func (*Hash[T]) IncrementInt

func (hash *Hash[T]) IncrementInt(ctx context.Context, field string, delta int64) (int64, error)

IncrementInt 和 IncrementFloat 适用于保存数字字符串的独立 Hash field。

func (*Hash[T]) Key

func (hash *Hash[T]) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*Hash[T]) Keys

func (hash *Hash[T]) Keys(ctx context.Context) ([]string, error)

Keys 返回全部 field;大 Hash 应优先使用 Scan,避免单次返回过多数据。

func (*Hash[T]) Len

func (hash *Hash[T]) Len(ctx context.Context) (int64, error)

Len 返回 field 数量。

func (*Hash[T]) PersistField

func (hash *Hash[T]) PersistField(ctx context.Context, field string) (bool, error)

PersistField 移除单个 field 的过期时间,需要 Redis 7.4+。

func (*Hash[T]) Scan

func (hash *Hash[T]) Scan(ctx context.Context, cursor uint64, pattern string, count int64) (HashScan[T], error)

Scan 分批扫描 Hash。pattern 为空表示不过滤,count 非正时默认使用 100。 count 是 Redis 的数量提示,不保证每批严格返回该数量。

func (*Hash[T]) Set

func (hash *Hash[T]) Set(ctx context.Context, field string, value T) error

Set 新增或覆盖单个 field。

func (*Hash[T]) SetMany

func (hash *Hash[T]) SetMany(ctx context.Context, values map[string]T) error

SetMany 使用一次 HSET 按 field 字典序批量新增或覆盖;空 map 不发送命令。

func (*Hash[T]) SetNX

func (hash *Hash[T]) SetNX(ctx context.Context, field string, value T) (bool, error)

SetNX 仅在 field 不存在时写入,写入成功返回 true。

func (*Hash[T]) TTLField

func (hash *Hash[T]) TTLField(ctx context.Context, field string) (time.Duration, error)

TTLField 返回 HPTTL;-1ms 表示不过期,-2ms 表示 field 不存在。

func (*Hash[T]) Values

func (hash *Hash[T]) Values(ctx context.Context) ([]T, error)

Values 返回全部对象但不包含 field;大 Hash 应优先使用 Scan。

type HashScan

type HashScan[T any] struct {
	// Cursor 为下一次扫描使用的游标;返回 0 表示扫描完成。
	Cursor uint64
	// Values 是本批次 field 到对象的映射。
	Values map[string]T
}

HashScan 表示一次 HSCAN 的游标和本批对象。

type HyperLogLog

type HyperLogLog struct {
	// contains filtered or unexported fields
}

HyperLogLog 是 Redis 近似去重计数结构。

func (*HyperLogLog) Add

func (hyperLogLog *HyperLogLog) Add(ctx context.Context, elements ...string) (bool, error)

Add 添加元素并返回内部估算是否发生变化;空输入返回 false。

func (*HyperLogLog) Clear

func (hyperLogLog *HyperLogLog) Clear(ctx context.Context) error

Clear 删除整个 HyperLogLog key。

func (*HyperLogLog) Count

func (hyperLogLog *HyperLogLog) Count(ctx context.Context) (int64, error)

Count 返回当前 HyperLogLog 的近似基数。

func (*HyperLogLog) CountWith

func (hyperLogLog *HyperLogLog) CountWith(ctx context.Context, others ...string) (int64, error)

CountWith 返回当前 HyperLogLog 与其他逻辑 key 合并后的近似基数,但不写入结果。 Redis Cluster 要求所有 key 位于同一 slot。

func (*HyperLogLog) Key

func (hyperLogLog *HyperLogLog) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*HyperLogLog) MergeFrom

func (hyperLogLog *HyperLogLog) MergeFrom(ctx context.Context, sources ...string) error

MergeFrom 将一个或多个逻辑来源 key 合并到当前 HyperLogLog。 Redis Cluster 要求目标和来源 key 位于同一 slot。

type Idempotency

type Idempotency struct {
	// contains filtered or unexported fields
}

Idempotency 使用 SET NX PX 记录已接收的业务 ID。

func (*Idempotency) Exists

func (idempotency *Idempotency) Exists(ctx context.Context, id string) (bool, error)

Exists 判断业务 ID 的幂等标记是否仍然有效。

func (*Idempotency) Forget

func (idempotency *Idempotency) Forget(ctx context.Context, id string) error

Forget 主动删除幂等标记,使相同 ID 可以再次执行。

func (*Idempotency) Run

func (idempotency *Idempotency) Run(ctx context.Context, id string, ttl time.Duration, fn func(context.Context) error) (bool, error)

Run 仅为首次出现的 ID 执行 fn,并在执行期间按 ttl/3 自动续租。 fn 必须使用收到的 context;续租失败时该 context 会以 ErrIdempotencyLeaseLost 为 cause 取消。 fn 成功后会把标记有效期重新设置为完整 ttl;fn 失败时只删除本次持有的标记以允许重试。 Redis 幂等标记不能替代数据库唯一约束,也不提供跨 Redis 与外部系统的恰好一次事务。

func (*Idempotency) Try

func (idempotency *Idempotency) Try(ctx context.Context, id string, ttl time.Duration) (bool, error)

Try 首次写入返回 true;ID 已存在返回 false。

type JSONDocument

type JSONDocument[T any] struct {
	// contains filtered or unexported fields
}

JSONDocument 使用 RedisJSON 保存一个可按 JSONPath 局部读写的强类型文档。 Redis 8 已内置 RedisJSON;旧版 Redis 需要单独安装 RedisJSON 模块。

func NewJSONDocument

func NewJSONDocument[T any](redis *Redis, key string) *JSONDocument[T]

NewJSONDocument 创建强类型 JSON 文档并自动应用全局 key 前缀。

func (*JSONDocument[T]) Clear

func (document *JSONDocument[T]) Clear(ctx context.Context) error

Clear 删除整个 JSON 文档。

func (*JSONDocument[T]) DeletePath

func (document *JSONDocument[T]) DeletePath(ctx context.Context, path string) (int64, error)

DeletePath 删除路径匹配的值,并返回实际删除数量。

func (*JSONDocument[T]) Exists

func (document *JSONDocument[T]) Exists(ctx context.Context) (bool, error)

Exists 判断整个 JSON 文档是否存在。

func (*JSONDocument[T]) Get

func (document *JSONDocument[T]) Get(ctx context.Context) (T, error)

Get 读取并反序列化根文档;文档不存在时返回 T 的零值和 Redis Nil。

func (*JSONDocument[T]) GetPath

func (document *JSONDocument[T]) GetPath(ctx context.Context, path string) (json.RawMessage, error)

GetPath 返回指定 JSONPath 的原始 JSON。 使用以 $ 开头的 JSONPath 时,RedisJSON 会返回匹配结果数组,调用方可按需要再解码。

func (*JSONDocument[T]) Key

func (document *JSONDocument[T]) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*JSONDocument[T]) MergePath

func (document *JSONDocument[T]) MergePath(ctx context.Context, path string, value any) error

MergePath 按 RFC 7396 JSON Merge Patch 语义合并指定路径。

func (*JSONDocument[T]) Set

func (document *JSONDocument[T]) Set(ctx context.Context, value T) error

Set 新增或覆盖根文档。

func (*JSONDocument[T]) SetNX

func (document *JSONDocument[T]) SetNX(ctx context.Context, value T) (bool, error)

SetNX 仅在文档不存在时写入根文档,写入成功返回 true。

func (*JSONDocument[T]) SetPath

func (document *JSONDocument[T]) SetPath(ctx context.Context, path string, value any) error

SetPath 将 value 编码成 JSON 后写入指定 JSONPath。

func (*JSONDocument[T]) SetXX

func (document *JSONDocument[T]) SetXX(ctx context.Context, value T) (bool, error)

SetXX 仅在文档已存在时覆盖根文档,写入成功返回 true。

type List

type List[T any] struct {
	// contains filtered or unexported fields
}

List 使用 Redis List 保存 JSON 对象。

func NewList

func NewList[T any](redis *Redis, key string) *List[T]

NewList 创建保存 JSON 对象的 Redis List。

func (*List[T]) Clear

func (list *List[T]) Clear(ctx context.Context) error

Clear 删除整个列表 key。

func (*List[T]) Index

func (list *List[T]) Index(ctx context.Context, index int64) (T, error)

Index 返回指定下标的对象,负数下标遵循 Redis 语义;错误时返回 T 的零值。

func (*List[T]) Key

func (list *List[T]) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*List[T]) Len

func (list *List[T]) Len(ctx context.Context) (int64, error)

Len 返回列表长度。

func (*List[T]) PopLeft

func (list *List[T]) PopLeft(ctx context.Context) (T, error)

PopLeft 从左侧弹出并反序列化一个对象;空列表返回 Redis Nil 错误,错误时返回 T 的零值。

func (*List[T]) PopRight

func (list *List[T]) PopRight(ctx context.Context) (T, error)

PopRight 从右侧弹出并反序列化一个对象;空列表返回 Redis Nil 错误,错误时返回 T 的零值。

func (*List[T]) PushLeft

func (list *List[T]) PushLeft(ctx context.Context, values ...T) (int64, error)

PushLeft 将对象序列化后从左侧压入,并返回列表新长度。

func (*List[T]) PushRight

func (list *List[T]) PushRight(ctx context.Context, values ...T) (int64, error)

PushRight 将对象序列化后从右侧压入,并返回列表新长度。

func (*List[T]) Range

func (list *List[T]) Range(ctx context.Context, start, stop int64) ([]T, error)

Range 返回下标闭区间内的对象,stop=-1 表示列表末尾。

func (*List[T]) Remove

func (list *List[T]) Remove(ctx context.Context, count int64, value T) (int64, error)

Remove 删除 count 个与 value JSON 表示完全相同的元素。

func (*List[T]) Set

func (list *List[T]) Set(ctx context.Context, index int64, value T) error

Set 覆盖指定下标的对象;下标越界时返回 Redis 错误。

func (*List[T]) Trim

func (list *List[T]) Trim(ctx context.Context, start, stop int64) error

Trim 只保留下标闭区间内的对象。

type PendingEntry

type PendingEntry struct {
	// ID 是 Redis Stream 消息 ID。
	ID string
	// Consumer 是当前持有该 Pending 消息的消费者。
	Consumer string
	// Idle 是距离上次投递经过的时间。
	Idle time.Duration
	// Deliveries 是累计投递次数。
	Deliveries int64
}

PendingEntry 描述消费组中一条尚未 ACK 的消息。

type PubSub

type PubSub[T any] struct {
	// contains filtered or unexported fields
}

PubSub 为消息提供 JSON 编解码和统一 channel 前缀。

func NewPubSub

func NewPubSub[T any](redis *Redis, namespace string) *PubSub[T]

NewPubSub 创建具有统一 channel 命名空间和 JSON 编解码的发布订阅门面。

func (*PubSub[T]) Prefix

func (pubsub *PubSub[T]) Prefix() string

Prefix 返回应用全局前缀后的真实 channel 命名空间。

func (*PubSub[T]) Publish

func (pubsub *PubSub[T]) Publish(ctx context.Context, channel string, value T) (int64, error)

Publish 发布普通 Pub/Sub 消息,并返回当前接收该消息的订阅者数量。

func (*PubSub[T]) PublishShard

func (pubsub *PubSub[T]) PublishShard(ctx context.Context, channel string, value T) (int64, error)

PublishShard 发布 Redis Cluster Sharded Pub/Sub 消息。

func (*PubSub[T]) Subscribe

func (pubsub *PubSub[T]) Subscribe(ctx context.Context, handler func(PubSubMessage[T]) error, channels ...string) error

Subscribe 阻塞直到 ctx 取消、连接失败或 handler 返回错误。

func (*PubSub[T]) SubscribePattern

func (pubsub *PubSub[T]) SubscribePattern(ctx context.Context, handler func(PubSubMessage[T]) error, patterns ...string) error

SubscribePattern 按模式订阅,例如传入 "order:*"。

func (*PubSub[T]) SubscribeShard

func (pubsub *PubSub[T]) SubscribeShard(ctx context.Context, handler func(PubSubMessage[T]) error, channels ...string) error

SubscribeShard 使用 Redis Cluster Sharded Pub/Sub。

type PubSubMessage

type PubSubMessage[T any] struct {
	// Channel 是去掉命名空间前缀后的逻辑 channel。
	Channel string
	// Pattern 是模式订阅命中的逻辑 pattern;普通订阅时为空。
	Pattern string
	// Value 是消息体反序列化后的业务对象。
	Value T
}

PubSubMessage 是已经完成 JSON 解码和逻辑 channel 去前缀的消息。

type Ranked

type Ranked[T any] struct {
	// ID 是稳定业务标识,同时作为 ZSet member 和 Hash field。
	ID string
	// Score 是用于倒序排名的分数。
	Score float64
	// Value 是与 ID 对应的业务对象。
	Value T
}

Ranked 是包含业务 ID、分数和对象内容的排行榜条目。

type Ranking

type Ranking[T any] struct {
	// contains filtered or unexported fields
}

Ranking 使用 Hash 保存对象、ZSet 保存稳定 ID 与分数。 两个键使用同一 Redis Cluster hash tag,Upsert 和 Remove 由 Lua 原子执行。

func NewRanking

func NewRanking[T any](redis *Redis, namespace string) *Ranking[T]

NewRanking 创建对象排行榜。内部两个 key 自动使用相同的 Cluster hash tag。

func (*Ranking[T]) Clear

func (ranking *Ranking[T]) Clear(ctx context.Context) error

Clear 删除内部 Hash 和 ZSet。

func (*Ranking[T]) Get

func (ranking *Ranking[T]) Get(ctx context.Context, id string) (Ranked[T], error)

Get 原子读取指定 ID 的对象和当前分数;ID 完全不存在时返回 Redis Nil 错误。

func (*Ranking[T]) Keys

func (ranking *Ranking[T]) Keys() (valuesKey, scoresKey string)

Keys 返回内部对象 Hash 和分数 ZSet 的真实 key,主要用于监控和清理。

func (*Ranking[T]) Len

func (ranking *Ranking[T]) Len(ctx context.Context) (int64, error)

Len 返回排行榜成员数量。

func (*Ranking[T]) Page added in v0.2.0

func (ranking *Ranking[T]) Page(ctx context.Context, offset, limit int64) ([]Ranked[T], error)

Page 从零基 offset 开始按分数降序读取 limit 项;每页最多 MaxRankingPageSize 项。 每页内部是同一时刻的快照;并发更新时不同页之间可能出现重复或遗漏。

func (*Ranking[T]) Range

func (ranking *Ranking[T]) Range(ctx context.Context, start, stop int64) ([]Ranked[T], error)

Range 按分数降序返回零基排名闭区间内的对象,支持 Redis 的负下标。 该兼容接口不限制返回条目数;大排行榜应使用 Page 控制单次 Lua 的工作量。

func (*Ranking[T]) Remove

func (ranking *Ranking[T]) Remove(ctx context.Context, id string) (bool, error)

Remove 原子删除对象和分数,实际删除排行榜成员时返回 true。

func (*Ranking[T]) Top

func (ranking *Ranking[T]) Top(ctx context.Context, limit int64) ([]Ranked[T], error)

Top 按分数降序返回前 limit 项;limit 非正时返回空切片。

func (*Ranking[T]) Upsert

func (ranking *Ranking[T]) Upsert(ctx context.Context, id string, score float64, value T) error

Upsert 原子新增或更新对象及其分数。

type Redis

type Redis struct {
	// contains filtered or unexported fields
}

Redis 统一管理业务客户端、JSON 缓存和按需创建的分布式锁客户端。

func New

func New(config Config) (*Redis, error)

New 创建统一 Redis 门面。只有首次使用锁时才会建立 rueidislock 专用客户端。

func (*Redis) Bitmap

func (redis *Redis) Bitmap(key string) *Bitmap

Bitmap 创建位图并自动应用全局 key 前缀。

func (*Redis) BloomFilter

func (redis *Redis) BloomFilter(key string) *BloomFilter

BloomFilter 创建过滤器并自动应用全局 key 前缀。

func (*Redis) Client

func (redis *Redis) Client() rueidis.Client

Client 返回原生 Rueidis 客户端,用于模板未覆盖的命令。

func (*Redis) Close

func (redis *Redis) Close()

Close 关闭业务客户端,以及已经按需创建的锁客户端。

func (*Redis) CountMinSketch

func (redis *Redis) CountMinSketch(key string) *CountMinSketch

CountMinSketch 创建草图并自动应用全局 key 前缀。

func (*Redis) Counter

func (redis *Redis) Counter(key string) *Counter

Counter 创建计数器并自动应用全局 key 前缀。

func (*Redis) CuckooFilter

func (redis *Redis) CuckooFilter(key string) *CuckooFilter

CuckooFilter 创建过滤器并自动应用全局 key 前缀。

func (*Redis) Delete

func (redis *Redis) Delete(ctx context.Context, keys ...string) (int64, error)

Delete 删除一个或多个逻辑 key,并返回实际删除的 key 数量。 多个 key 分别发送 DEL,因此在 Redis Cluster 中不要求这些 key 位于同一 slot。 部分失败时返回已确认的删除数量和聚合错误;需要逐 key 明细时使用 DeleteEach。

func (*Redis) DeleteEach

func (redis *Redis) DeleteEach(ctx context.Context, keys ...string) DeleteBatchResult

DeleteEach 逐 key 执行 DEL,返回与输入顺序一致的明细。 每个 key 使用独立命令,因此可以安全处理 Redis Cluster 中跨 Slot 的输入。 大批次会分块执行;某个 key 失败不会阻止后续 key,ctx 取消后不再发送后续分块。

func (*Redis) Exists

func (redis *Redis) Exists(ctx context.Context, keys ...string) (int64, error)

Exists 返回实际存在的逻辑 key 数量;多个 key 会分别查询以兼容 Redis Cluster。 部分失败时返回已确认的存在数量和聚合错误;需要逐 key 明细时使用 ExistsEach。

func (*Redis) ExistsEach

func (redis *Redis) ExistsEach(ctx context.Context, keys ...string) ExistsBatchResult

ExistsEach 逐 key 执行 EXISTS,返回与输入顺序一致的明细。 每个 key 使用独立命令,因此可以安全处理 Redis Cluster 中跨 Slot 的输入。 大批次会分块执行;某个 key 失败不会阻止后续 key,ctx 取消后不再发送后续分块。

func (*Redis) Expiration

func (redis *Redis) Expiration(ctx context.Context, key string) (ExpirationInfo, error)

Expiration 返回逻辑 key 的结构化过期状态,调用方无需再解释 PTTL 的 -1ms/-2ms。

func (*Redis) FencingKey added in v0.2.0

func (redis *Redis) FencingKey(name string) string

FencingKey 返回某个锁名对应的 fencing 计数器 key。 该 key 不应删除或设置过期时间,否则 token 可能倒退。

func (*Redis) Geo

func (redis *Redis) Geo(key string) *Geo

Geo 创建地理位置集合并自动应用全局 key 前缀。

func (*Redis) GetString

func (redis *Redis) GetString(ctx context.Context, key string) (string, error)

GetString 读取普通字符串,并自动应用全局 key 前缀。

func (*Redis) Has

func (redis *Redis) Has(ctx context.Context, key string) (bool, error)

Has 判断单个逻辑 key 是否存在。

func (*Redis) HyperLogLog

func (redis *Redis) HyperLogLog(key string) *HyperLogLog

HyperLogLog 创建近似去重计数器并自动应用全局 key 前缀。

func (*Redis) Idempotency

func (redis *Redis) Idempotency(namespace string) *Idempotency

Idempotency 创建带独立 key 命名空间的幂等控制器。

func (*Redis) Key

func (redis *Redis) Key(key string) string

Key 返回应用前缀处理后的真实 Redis key。

func (*Redis) List

func (redis *Redis) List(key string) *StringList

List 是 StringList 的兼容简写。

func (*Redis) Lock

func (redis *Redis) Lock(ctx context.Context, name string) (context.Context, context.CancelFunc, error)

Lock 等待获得自动续期的分布式锁。

func (*Redis) LockFenced added in v0.2.0

func (redis *Redis) LockFenced(ctx context.Context, name string) (context.Context, int64, context.CancelFunc, error)

LockFenced 等待获得锁,并生成一个单调递增的 fencing token。 下游资源必须持久化并拒绝小于等于已见最大值的 token,才能阻止失去租约的旧持有者继续写入。

func (*Redis) Ping

func (redis *Redis) Ping(ctx context.Context) error

Ping 检查 Redis 业务连接是否可用。

func (*Redis) SetString

func (redis *Redis) SetString(ctx context.Context, key, value string, ttl ...time.Duration) error

SetString 写入字符串;可选 ttl,省略或不大于零时不过期,小于 1ms 的正值提升为 1ms。

func (*Redis) SortedSet

func (redis *Redis) SortedSet(key string) *SortedSet

SortedSet 创建通用字符串有序集合。

func (*Redis) StringList

func (redis *Redis) StringList(key string) *StringList

StringList 返回保存原始字符串的 List;对象列表使用 NewList[T]。

func (*Redis) StringSet

func (redis *Redis) StringSet(key string) *StringSet

StringSet 创建字符串集合并自动应用全局 key 前缀。

func (*Redis) TDigest

func (redis *Redis) TDigest(key string) *TDigest

TDigest 创建摘要并自动应用全局 key 前缀。

func (*Redis) TimeSeries

func (redis *Redis) TimeSeries(key string) *TimeSeries

TimeSeries 创建时间序列并自动应用全局 key 前缀。

func (*Redis) TopK

func (redis *Redis) TopK(key string) *TopK

TopK 创建草图并自动应用全局 key 前缀。

func (*Redis) TryLock

func (redis *Redis) TryLock(ctx context.Context, name string) (context.Context, context.CancelFunc, error)

TryLock 只尝试一次;锁已被占用时返回 rueidislock.ErrNotLocked。

func (*Redis) TryLockFenced added in v0.2.0

func (redis *Redis) TryLockFenced(ctx context.Context, name string) (context.Context, int64, context.CancelFunc, error)

TryLockFenced 只尝试一次获取锁,并在成功后生成 fencing token。

func (*Redis) VectorSet

func (redis *Redis) VectorSet(key string) *VectorSet

VectorSet 创建向量集合并自动应用全局 key 前缀。

func (*Redis) WithFencedLock added in v0.2.0

func (redis *Redis) WithFencedLock(ctx context.Context, name string, fn func(context.Context, int64) error) error

WithFencedLock 持有带 fencing token 的锁执行 fn,并在 fn 返回时释放锁。

func (*Redis) WithLock added in v0.2.0

func (redis *Redis) WithLock(ctx context.Context, name string, fn func(context.Context) error) error

WithLock 持锁执行 fn,并在 fn 返回时释放锁。 fn 必须使用收到的 lockCtx;若续租失败,即使 fn 返回 nil,本方法也会返回 ErrLockLost。

type ScoredMember

type ScoredMember struct {
	// Member 是稳定的字符串成员。
	Member string
	// Score 用于排序,Redis 按 float64 保存。
	Score float64
}

ScoredMember 表示 ZSet 的字符串成员及其分数。

type Set

type Set[T any] struct {
	// contains filtered or unexported fields
}

Set 使用 Redis Set 保存 JSON 对象,适合去重、成员判断和无序集合。 Redis 以 JSON 字节串判断成员是否相同;自定义 MarshalJSON 时应保证同一业务值的输出稳定。

func NewSet

func NewSet[T any](redis *Redis, key string) *Set[T]

NewSet 创建保存 JSON 对象的类型化 Redis Set。

func (*Set[T]) Add

func (set *Set[T]) Add(ctx context.Context, values ...T) (int64, error)

Add 添加一个或多个对象,返回实际新增的成员数;空输入返回 0 且不访问 Redis。

func (*Set[T]) Clear

func (set *Set[T]) Clear(ctx context.Context) error

Clear 删除整个 Set key。

func (*Set[T]) Contains

func (set *Set[T]) Contains(ctx context.Context, value T) (bool, error)

Contains 判断 JSON 表示完全相同的对象是否存在。

func (*Set[T]) Key

func (set *Set[T]) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*Set[T]) Len

func (set *Set[T]) Len(ctx context.Context) (int64, error)

Len 返回集合成员数。

func (*Set[T]) Members

func (set *Set[T]) Members(ctx context.Context) ([]T, error)

Members 返回全部强类型成员,顺序不固定;大集合应使用 Rueidis SSCAN Builder 分批扫描。

func (*Set[T]) Remove

func (set *Set[T]) Remove(ctx context.Context, values ...T) (int64, error)

Remove 删除 JSON 表示完全相同的对象,返回实际删除数;空输入返回 0。

func (*Set[T]) Scan

func (set *Set[T]) Scan(ctx context.Context, cursor uint64, pattern string, count int64) (SetScan[T], error)

Scan 分批扫描泛型 Set。pattern 为空时不过滤,count 非正时默认为 100。 pattern 匹配的是成员的原始 JSON 字符串,不是 Go 字段或结构化 JSON 查询。 count 是 Redis 的数量提示,实际返回条数可能不同。

type SetScan

type SetScan[T any] struct {
	// Cursor 是下一次扫描使用的游标;返回 0 表示扫描完成。
	Cursor uint64
	// Values 是本批已完成 JSON 解码的成员,Redis Set 不保证顺序。
	Values []T
}

SetScan 表示一次泛型 Set 游标扫描结果。

type SortedSet

type SortedSet struct {
	// contains filtered or unexported fields
}

SortedSet 是 member 为字符串的通用 Redis ZSet。

func (*SortedSet) Add

func (set *SortedSet) Add(ctx context.Context, member string, score float64) error

Add 新增成员或覆盖已有成员的分数。

func (*SortedSet) AddMany

func (set *SortedSet) AddMany(ctx context.Context, members ...ScoredMember) error

AddMany 使用一次 ZADD 批量新增或更新成员。

func (*SortedSet) Clear

func (set *SortedSet) Clear(ctx context.Context) error

Clear 删除整个 ZSet key。

func (*SortedSet) Increment

func (set *SortedSet) Increment(ctx context.Context, member string, delta float64) (float64, error)

Increment 原子增加成员分数,并返回增加后的分数。

func (*SortedSet) Key

func (set *SortedSet) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*SortedSet) Len

func (set *SortedSet) Len(ctx context.Context) (int64, error)

Len 返回成员数量。

func (*SortedSet) PopMax

func (set *SortedSet) PopMax(ctx context.Context, count int64) ([]ScoredMember, error)

PopMax 原子弹出分数最高的 count 个成员。

func (*SortedSet) PopMin

func (set *SortedSet) PopMin(ctx context.Context, count int64) ([]ScoredMember, error)

PopMin 原子弹出分数最低的 count 个成员。

func (*SortedSet) Range

func (set *SortedSet) Range(ctx context.Context, start, stop int64) ([]ScoredMember, error)

Range 按分数升序返回排名闭区间内的成员及分数。

func (*SortedSet) RangeByScore

func (set *SortedSet) RangeByScore(ctx context.Context, min, max float64, offset, count int64) ([]ScoredMember, error)

RangeByScore 按分数升序查询,min/max 为闭区间;可使用 math.Inf 表示无穷。

func (*SortedSet) Rank

func (set *SortedSet) Rank(ctx context.Context, member string) (int64, error)

Rank 返回成员按分数升序排列的零基排名。

func (*SortedSet) Remove

func (set *SortedSet) Remove(ctx context.Context, members ...string) (int64, error)

Remove 删除成员并返回实际删除数量。

func (*SortedSet) RemoveByScore

func (set *SortedSet) RemoveByScore(ctx context.Context, min, max float64) (int64, error)

RemoveByScore 删除闭区间分数内的成员,可使用 math.Inf 表示无穷。

func (*SortedSet) ReverseRange

func (set *SortedSet) ReverseRange(ctx context.Context, start, stop int64) ([]ScoredMember, error)

ReverseRange 按分数降序返回排名闭区间内的成员及分数。

func (*SortedSet) ReverseRank

func (set *SortedSet) ReverseRank(ctx context.Context, member string) (int64, error)

ReverseRank 返回成员按分数降序排列的零基排名。

func (*SortedSet) Score

func (set *SortedSet) Score(ctx context.Context, member string) (float64, error)

Score 返回成员分数;成员不存在时返回 Redis Nil 错误。

type Stream

type Stream[T any] struct {
	// contains filtered or unexported fields
}

Stream 使用单个 data field 保存 JSON 对象。

func NewStream

func NewStream[T any](redis *Redis, key string) *Stream[T]

NewStream 创建将业务对象统一编码到 data 字段的类型化 Stream。

func (*Stream[T]) Ack

func (stream *Stream[T]) Ack(ctx context.Context, group string, ids ...string) (int64, error)

Ack 确认消费成功,并返回从 Pending 列表中移除的消息数。

func (*Stream[T]) Add

func (stream *Stream[T]) Add(ctx context.Context, value T) (string, error)

Add 使用 Redis 自动生成的 ID 添加消息,并返回消息 ID。

func (*Stream[T]) AddMaxLen

func (stream *Stream[T]) AddMaxLen(ctx context.Context, value T, maxLen int64) (string, error)

AddMaxLen 使用 Redis 自动生成的 ID 添加消息,并以 MAXLEN ~ 近似裁剪 Stream。 近似裁剪通常比精确裁剪更高效,但长度可能暂时略大于 maxLen。

func (*Stream[T]) AddWithID

func (stream *Stream[T]) AddWithID(ctx context.Context, id string, value T) (string, error)

AddWithID 使用调用方指定的消息 ID 添加消息。

func (*Stream[T]) AddWithIDMaxLen

func (stream *Stream[T]) AddWithIDMaxLen(ctx context.Context, id string, value T, maxLen int64) (string, error)

AddWithIDMaxLen 使用指定 ID 添加消息,并以 MAXLEN ~ 近似裁剪 Stream。

func (*Stream[T]) AutoClaim

func (stream *Stream[T]) AutoClaim(ctx context.Context, group, consumer string, minIdle time.Duration, start string, count int64) (AutoClaimResult[T], error)

AutoClaim 扫描 Pending 列表,将空闲时间不少于 minIdle 的消息自动转移给 consumer。 start 为空时从 0-0 开始;count 非正时默认每次处理 100 条。该命令需要 Redis 6.2+。

func (*Stream[T]) Claim

func (stream *Stream[T]) Claim(ctx context.Context, group, consumer string, minIdle time.Duration, ids ...string) ([]StreamEntry[T], error)

Claim 将空闲时间不少于 minIdle 的 Pending 消息转移给 consumer。 minIdle 不能为负;小于 1ms 的正值提升为 1ms,零值表示立即允许转移。

func (*Stream[T]) Clear

func (stream *Stream[T]) Clear(ctx context.Context) error

Clear 删除整个 Stream,包括其消费组状态。

func (*Stream[T]) Consumers

func (stream *Stream[T]) Consumers(ctx context.Context, group string) ([]StreamConsumerInfo, error)

Consumers 返回指定消费组的全部消费者状态。

func (*Stream[T]) CreateGroup

func (stream *Stream[T]) CreateGroup(ctx context.Context, group, startID string) error

CreateGroup 创建消费组;组已存在时也返回 nil。

func (*Stream[T]) Delete

func (stream *Stream[T]) Delete(ctx context.Context, ids ...string) (int64, error)

Delete 从 Stream 中永久删除消息,并返回实际删除数量。

func (*Stream[T]) DeleteConsumer

func (stream *Stream[T]) DeleteConsumer(ctx context.Context, group, consumer string) (int64, error)

DeleteConsumer 从消费组中删除消费者,返回被一并丢弃的 Pending 消息数。 调用前应先确认或转移该消费者的 Pending 消息,避免消息失去归属。

func (*Stream[T]) DeleteGroup

func (stream *Stream[T]) DeleteGroup(ctx context.Context, group string) (bool, error)

DeleteGroup 删除消费组及其 Pending 状态,返回该消费组是否存在并被删除。

func (*Stream[T]) Groups

func (stream *Stream[T]) Groups(ctx context.Context) ([]StreamGroupInfo, error)

Groups 返回 Stream 的全部消费组状态,包含 Pending 数和可用时的 lag。

func (*Stream[T]) Key

func (stream *Stream[T]) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*Stream[T]) Len

func (stream *Stream[T]) Len(ctx context.Context) (int64, error)

Len 返回 Stream 中的消息数量。

func (*Stream[T]) Pending

func (stream *Stream[T]) Pending(ctx context.Context, group string, count int64) ([]PendingEntry, error)

Pending 返回消费组中最多 count 条待确认消息及其消费者、空闲时间和投递次数。

func (*Stream[T]) Range

func (stream *Stream[T]) Range(ctx context.Context, start, end string, count int64) ([]StreamEntry[T], error)

Range 按 ID 闭区间读取消息;count 非正表示不添加 COUNT 限制。

func (*Stream[T]) Read

func (stream *Stream[T]) Read(ctx context.Context, afterID string, count int64) ([]StreamEntry[T], error)

Read 从 afterID 之后非阻塞读取消息;count 非正时默认读取 100 条。

func (*Stream[T]) ReadBlock

func (stream *Stream[T]) ReadBlock(ctx context.Context, afterID string, count int64, block time.Duration) ([]StreamEntry[T], error)

ReadBlock 最多阻塞 block 等待消息;block 非正时退化为非阻塞 Read,小于 1ms 的正值提升为 1ms。

func (*Stream[T]) ReadGroup

func (stream *Stream[T]) ReadGroup(ctx context.Context, group, consumer string, count int64) ([]StreamEntry[T], error)

ReadGroup 读取尚未投递给其他消费者的新消息。

func (*Stream[T]) ReadGroupFrom

func (stream *Stream[T]) ReadGroupFrom(ctx context.Context, group, consumer, startID string, count int64, block time.Duration) ([]StreamEntry[T], error)

ReadGroupFrom 可读取新消息(startID 为 ">")或当前消费者的 Pending 消息。 block 小于 1ms 的正值提升为 1ms,避免 Redis 将 BLOCK 0 解释为无限等待。

func (*Stream[T]) SetGroupID

func (stream *Stream[T]) SetGroupID(ctx context.Context, group, id string) error

SetGroupID 修改消费组的最后投递 ID,可用于重放或跳过历史消息。 该操作不会清理已有 Pending 消息,调用前应确认业务重放语义。

func (*Stream[T]) TrimMaxLen

func (stream *Stream[T]) TrimMaxLen(ctx context.Context, maxLen int64) (int64, error)

TrimMaxLen 使用 XTRIM MAXLEN ~ 近似裁剪 Stream,返回被删除的消息数。

type StreamConsumerInfo

type StreamConsumerInfo struct {
	// Name 是消费者名称。
	Name string
	// Pending 是归属该消费者且尚未 ACK 的消息数。
	Pending int64
	// Idle 是距离该消费者最后一次交互的时间。
	Idle time.Duration
	// Inactive 是距离该消费者最后一次成功投递的时间,Redis 7.2+ 提供。
	Inactive time.Duration
	// InactiveKnown 表示当前 Redis 响应是否包含 Inactive。
	InactiveKnown bool
}

StreamConsumerInfo 描述 XINFO CONSUMERS 返回的单个消费者状态。

type StreamEntry

type StreamEntry[T any] struct {
	// ID 是 Redis Stream 消息 ID。
	ID string
	// Value 是 data 字段中的业务对象。
	Value T
}

StreamEntry 表示一条已经完成 JSON 解码的 Stream 消息。

type StreamGroupInfo

type StreamGroupInfo struct {
	// Name 是消费组名称。
	Name string
	// Consumers 是该组已知消费者数。
	Consumers int64
	// Pending 是已投递但尚未 ACK 的消息数。
	Pending int64
	// LastDeliveredID 是最后一条已投递消息的 ID。
	LastDeliveredID string
	// EntriesRead 是 Redis 估算的已读取消息数。
	EntriesRead int64
	// EntriesReadKnown 表示 Redis 是否能给出 EntriesRead。
	EntriesReadKnown bool
	// Lag 是尚未投递给该组的消息数。
	Lag int64
	// LagKnown 表示 Redis 是否能给出 Lag。
	LagKnown bool
}

StreamGroupInfo 描述 XINFO GROUPS 返回的消费组运行状态。

type StringList

type StringList struct {
	// contains filtered or unexported fields
}

StringList 是直接保存字符串的 Redis List。

func (*StringList) Clear

func (list *StringList) Clear(ctx context.Context) error

Clear 删除整个列表 key。

func (*StringList) Key

func (list *StringList) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*StringList) Len

func (list *StringList) Len(ctx context.Context) (int64, error)

Len 返回列表长度。

func (*StringList) PopLeft

func (list *StringList) PopLeft(ctx context.Context) (string, error)

PopLeft 从左侧弹出一个字符串;空列表返回 Redis Nil 错误。

func (*StringList) PopRight

func (list *StringList) PopRight(ctx context.Context) (string, error)

PopRight 从右侧弹出一个字符串;空列表返回 Redis Nil 错误。

func (*StringList) PushLeft

func (list *StringList) PushLeft(ctx context.Context, values ...string) (int64, error)

PushLeft 从左侧压入字符串,并返回列表新长度。

func (*StringList) PushRight

func (list *StringList) PushRight(ctx context.Context, values ...string) (int64, error)

PushRight 从右侧压入字符串,并返回列表新长度。

func (*StringList) Range

func (list *StringList) Range(ctx context.Context, start, stop int64) ([]string, error)

Range 按 Redis LRANGE 的闭区间下标返回元素,stop=-1 表示列表末尾。

func (*StringList) Trim

func (list *StringList) Trim(ctx context.Context, start, stop int64) error

Trim 只保留下标闭区间内的元素。

type StringSet

type StringSet struct {
	// contains filtered or unexported fields
}

StringSet 是 member 为字符串的 Redis Set。

func (*StringSet) Add

func (set *StringSet) Add(ctx context.Context, members ...string) (int64, error)

Add 添加成员并返回实际新增数量。

func (*StringSet) Clear

func (set *StringSet) Clear(ctx context.Context) error

Clear 删除整个集合 key。

func (*StringSet) Contains

func (set *StringSet) Contains(ctx context.Context, member string) (bool, error)

Contains 判断 member 是否存在。

func (*StringSet) Key

func (set *StringSet) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*StringSet) Len

func (set *StringSet) Len(ctx context.Context) (int64, error)

Len 返回集合成员数量。

func (*StringSet) Members

func (set *StringSet) Members(ctx context.Context) ([]string, error)

Members 返回全部成员;Redis Set 不保证返回顺序。

func (*StringSet) Remove

func (set *StringSet) Remove(ctx context.Context, members ...string) (int64, error)

Remove 删除成员并返回实际删除数量。

func (*StringSet) Scan

func (set *StringSet) Scan(ctx context.Context, cursor uint64, pattern string, count int64) (StringSetScan, error)

Scan 分批扫描字符串 Set。pattern 为空时不过滤,count 非正时默认为 100。

type StringSetScan

type StringSetScan struct {
	// Cursor 是下一次扫描使用的游标;返回 0 表示扫描完成。
	Cursor uint64
	// Members 是本批字符串成员。
	Members []string
}

StringSetScan 表示一次字符串 Set 游标扫描结果。

type TDigest

type TDigest struct {
	// contains filtered or unexported fields
}

TDigest 封装 RedisBloom 的 t-digest 分布统计操作。

func (*TDigest) Add

func (digest *TDigest) Add(ctx context.Context, values ...float64) error

Add 批量加入样本;空输入不发送命令。

func (*TDigest) CDF

func (digest *TDigest) CDF(ctx context.Context, values ...float64) ([]float64, error)

CDF 返回每个值在估算累积分布中的比例。

func (*TDigest) Clear

func (digest *TDigest) Clear(ctx context.Context) error

Clear 删除整个 t-digest key。

func (*TDigest) Create

func (digest *TDigest) Create(ctx context.Context, compression int64) error

Create 按压缩参数创建摘要;压缩值越高通常精度和内存占用越高。

func (*TDigest) Key

func (digest *TDigest) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*TDigest) Max

func (digest *TDigest) Max(ctx context.Context) (float64, error)

Max 返回摘要中的最大样本。

func (*TDigest) Min

func (digest *TDigest) Min(ctx context.Context) (float64, error)

Min 返回摘要中的最小样本。

func (*TDigest) Quantiles

func (digest *TDigest) Quantiles(ctx context.Context, quantiles ...float64) ([]float64, error)

Quantiles 批量查询分位点对应值,并保持输入顺序;空输入不发送命令。

func (*TDigest) Rank

func (digest *TDigest) Rank(ctx context.Context, values ...float64) ([]int64, error)

Rank 返回小于各值的估算样本数量。

func (*TDigest) Reset

func (digest *TDigest) Reset(ctx context.Context) error

Reset 清空摘要中的样本但保留摘要配置。

func (*TDigest) ReverseRank

func (digest *TDigest) ReverseRank(ctx context.Context, values ...float64) ([]int64, error)

ReverseRank 返回大于各值的估算样本数量。

func (*TDigest) TrimmedMean

func (digest *TDigest) TrimmedMean(ctx context.Context, lowerQuantile, upperQuantile float64) (float64, error)

TrimmedMean 返回 lowerQuantile 到 upperQuantile 区间内的截尾平均值。

type TimeSeries

type TimeSeries struct {
	// contains filtered or unexported fields
}

TimeSeries 封装 RedisTimeSeries 的常用单序列操作。 Redis 8 已内置 RedisTimeSeries;旧版 Redis 需要单独安装模块。

func (*TimeSeries) Add

func (series *TimeSeries) Add(ctx context.Context, timestamp int64, value float64) (int64, error)

Add 写入指定毫秒时间戳的样本,并返回 Redis 最终使用的时间戳。

func (*TimeSeries) AddNow

func (series *TimeSeries) AddNow(ctx context.Context, value float64) (int64, error)

AddNow 由 Redis 生成当前毫秒时间戳,并返回最终时间戳。

func (*TimeSeries) Clear

func (series *TimeSeries) Clear(ctx context.Context) error

Clear 删除整个时间序列。

func (*TimeSeries) Create

func (series *TimeSeries) Create(ctx context.Context, options TimeSeriesOptions) error

Create 显式创建时间序列。直接调用 Add 时 Redis 也可以按默认配置自动创建。

func (*TimeSeries) Decrement

func (series *TimeSeries) Decrement(ctx context.Context, delta float64) (int64, error)

Decrement 原子减少最新值;序列为空时从零开始减少,并返回新样本时间戳。

func (*TimeSeries) DeleteRange

func (series *TimeSeries) DeleteRange(ctx context.Context, start, end int64) (int64, error)

DeleteRange 删除毫秒时间戳闭区间内的样本,并返回删除数量。

func (*TimeSeries) Get

func (series *TimeSeries) Get(ctx context.Context) (TimeSeriesSample, error)

Get 返回时间戳最大的最新样本;序列不存在或没有样本时返回 Redis Nil。

func (*TimeSeries) Increment

func (series *TimeSeries) Increment(ctx context.Context, delta float64) (int64, error)

Increment 原子增加最新值;序列为空时从 delta 开始,并返回新样本时间戳。

func (*TimeSeries) Key

func (series *TimeSeries) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*TimeSeries) Range

func (series *TimeSeries) Range(ctx context.Context, start, end int64, count int64) ([]TimeSeriesSample, error)

Range 返回毫秒时间戳闭区间内按时间升序排列的样本;count 非正时不限制数量。

func (*TimeSeries) RangeAll

func (series *TimeSeries) RangeAll(ctx context.Context, count int64) ([]TimeSeriesSample, error)

RangeAll 返回整个时间序列;count 非正时不限制数量。

func (*TimeSeries) ReverseRange

func (series *TimeSeries) ReverseRange(ctx context.Context, start, end int64, count int64) ([]TimeSeriesSample, error)

ReverseRange 返回毫秒时间戳闭区间内按时间降序排列的样本;count 非正时不限制数量。

type TimeSeriesOptions

type TimeSeriesOptions struct {
	// Retention 为零表示永久保留;负数无效。
	Retention time.Duration
	// Labels 用于查询和聚合;写入命令会按名称排序以保证稳定。
	Labels map[string]string
}

TimeSeriesOptions 配置时间序列的保留时间和标签。

type TimeSeriesSample

type TimeSeriesSample struct {
	Timestamp int64
	Value     float64
}

TimeSeriesSample 是一个毫秒时间戳及其浮点样本值。

type TopK

type TopK struct {
	// contains filtered or unexported fields
}

TopK 封装 RedisBloom 的 Top-K 高频元素追踪操作。

func (*TopK) Add

func (top *TopK) Add(ctx context.Context, items ...string) ([]TopKAddResult, error)

Add 批量添加元素,并逐项说明是否有旧元素被挤出;空输入不发送命令。

func (*TopK) Clear

func (top *TopK) Clear(ctx context.Context) error

Clear 删除整个 Top-K 草图。

func (*TopK) Count

func (top *TopK) Count(ctx context.Context, items ...string) ([]int64, error)

Count 批量返回元素的估算计数并保持输入顺序;空输入不发送命令。

func (*TopK) Key

func (top *TopK) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*TopK) List

func (top *TopK) List(ctx context.Context) ([]TopKItem, error)

List 返回当前 Top-K 元素及估算计数,顺序由 Redis 保持。

func (*TopK) Query

func (top *TopK) Query(ctx context.Context, items ...string) ([]bool, error)

Query 批量判断元素当前是否属于 Top-K;空输入不发送命令。

func (*TopK) Reserve

func (top *TopK) Reserve(ctx context.Context, size int64) error

Reserve 使用 Redis 默认精度参数初始化 Top-K 草图。

func (*TopK) ReserveWithOptions

func (top *TopK) ReserveWithOptions(ctx context.Context, size int64, options TopKOptions) error

ReserveWithOptions 使用完整精度参数初始化 Top-K 草图。

type TopKAddResult

type TopKAddResult struct {
	Item      string
	Kicked    string
	HasKicked bool
}

TopKAddResult 表示一次添加及可能被 Top-K 列表挤出的元素。

type TopKItem

type TopKItem struct {
	Item  string
	Count int64
}

TopKItem 是一个高频元素及其估算计数。

type TopKOptions

type TopKOptions struct {
	Width int64
	Depth int64
	Decay float64
}

TopKOptions 配置 Top-K 草图的精度和衰减。

type Value

type Value[T any] struct {
	// contains filtered or unexported fields
}

Value 使用单个 Redis String 保存 JSON 对象,不经过 gocache。

func NewValue

func NewValue[T any](redis *Redis, key string) *Value[T]

NewValue 创建使用单个 Redis String 保存的类型化 JSON 值。

func (*Value[T]) Delete

func (value *Value[T]) Delete(ctx context.Context) (bool, error)

Delete 删除该值;实际删除成功返回 true。

func (*Value[T]) Exists

func (value *Value[T]) Exists(ctx context.Context) (bool, error)

Exists 判断该值是否存在。

func (*Value[T]) Expiration

func (value *Value[T]) Expiration(ctx context.Context) (ExpirationInfo, error)

Expiration 返回结构化过期状态,避免调用方自行解释 TTL 的 -1ms/-2ms。

func (*Value[T]) Expire

func (value *Value[T]) Expire(ctx context.Context, ttl time.Duration) (bool, error)

Expire 为已存在的值设置过期时间;key 不存在时返回 false。

func (*Value[T]) Get

func (value *Value[T]) Get(ctx context.Context) (T, error)

Get 读取并反序列化 JSON 对象;key 不存在时返回 Rueidis 的 Redis Nil 错误。 发生任何错误时返回 T 的零值。

func (*Value[T]) GetDelete

func (value *Value[T]) GetDelete(ctx context.Context) (T, error)

GetDelete 原子读取并删除对象;key 不存在时返回 Redis Nil 错误。 该命令需要 Redis 6.2+;发生任何错误时返回 T 的零值。

func (*Value[T]) Key

func (value *Value[T]) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*Value[T]) Set

func (value *Value[T]) Set(ctx context.Context, data T, ttl ...time.Duration) error

Set 写入对象;省略或传入非正 ttl 时不过期。

func (*Value[T]) SetNX

func (value *Value[T]) SetNX(ctx context.Context, data T, ttl time.Duration) (bool, error)

SetNX 仅在 key 不存在时写入对象。

func (*Value[T]) TTL

func (value *Value[T]) TTL(ctx context.Context) (time.Duration, error)

TTL 返回 PTTL;-1ms 表示不过期,-2ms 表示 key 不存在。

type VectorMatch

type VectorMatch struct {
	Member string
	Score  float64
}

VectorMatch 是一个相似元素及其余弦相似度分数。

type VectorSearchOptions

type VectorSearchOptions struct {
	// Count 是最多返回数量,非正时默认返回 10 个。
	Count int64
	// Filter 是针对元素属性的 Redis Vector Set 过滤表达式;为空表示不过滤。
	Filter string
}

VectorSearchOptions 配置向量相似度搜索。

type VectorSet

type VectorSet struct {
	// contains filtered or unexported fields
}

VectorSet 封装 Redis 8.0+ 原生 Vector Set 的常用操作。

func (*VectorSet) Add

func (set *VectorSet) Add(ctx context.Context, member string, vector []float64) (bool, error)

Add 新增或更新元素向量;新增返回 true,更新已有元素返回 false。

func (*VectorSet) AttributesRaw

func (set *VectorSet) AttributesRaw(ctx context.Context, member string) (json.RawMessage, error)

AttributesRaw 返回元素属性的原始 JSON;元素不存在时返回 Redis Nil。

func (*VectorSet) Card

func (set *VectorSet) Card(ctx context.Context) (int64, error)

Card 返回集合中的元素数量。

func (*VectorSet) Clear

func (set *VectorSet) Clear(ctx context.Context) error

Clear 删除整个向量集合。

func (*VectorSet) ClearAttributes

func (set *VectorSet) ClearAttributes(ctx context.Context, member string) (bool, error)

ClearAttributes 清空元素属性;元素存在时返回 true。

func (*VectorSet) Contains

func (set *VectorSet) Contains(ctx context.Context, member string) (bool, error)

Contains 判断元素是否存在,需要 Redis 8.2+。

func (*VectorSet) Dimension

func (set *VectorSet) Dimension(ctx context.Context) (int64, error)

Dimension 返回向量维度;key 不存在时返回零。

func (*VectorSet) Key

func (set *VectorSet) Key() string

Key 返回应用全局前缀后的真实 Redis key。

func (*VectorSet) Remove

func (set *VectorSet) Remove(ctx context.Context, member string) (bool, error)

Remove 删除元素,实际删除时返回 true。

func (*VectorSet) Search

func (set *VectorSet) Search(ctx context.Context, vector []float64, options VectorSearchOptions) ([]VectorMatch, error)

Search 按给定向量返回相似元素,结果按相似度从高到低排列。

func (*VectorSet) SearchByMember

func (set *VectorSet) SearchByMember(ctx context.Context, member string, options VectorSearchOptions) ([]VectorMatch, error)

SearchByMember 使用已有元素的向量搜索相似元素。

func (*VectorSet) SetAttributes

func (set *VectorSet) SetAttributes(ctx context.Context, member string, attributes any) (bool, error)

SetAttributes 将对象编码为 JSON 后设置为元素属性;元素存在时返回 true。

func (*VectorSet) Vector

func (set *VectorSet) Vector(ctx context.Context, member string) ([]float64, error)

Vector 返回元素的近似向量;元素不存在时返回 Redis Nil。

Directories

Path Synopsis
redis8 command
Command redis8 展示 Redis 8.10 中 JSON、TimeSeries、Vector Set、Array 和概率结构的便利 API。
Command redis8 展示 Redis 8.10 中 JSON、TimeSeries、Vector Set、Array 和概率结构的便利 API。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址