Help us shape the future of Go! Take the 2026 Go Developer Survey

redisx

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 6 Imported by: 0

README

redisx

Redis 全家桶——客户端封装/分布式缓存/分布式锁/分布式限流

⚠️ 原名 oekit/redis,v0.4.0 起更名 oekit/redisx(消除与 go-redis 的包名撞车与 /redis/redis 口吃);旧路径经 GitHub 重定向可拉取 ≤ v0.3.1

🌐 项目主页:https://oekit.github.io/ · 名称由来:Open Easy Kit(开源 · 易用 · 工具集合) 🤖 AI Agent:本仓规范与硬规则见 AGENTS.md;机器可读索引见 llms.txt(接口签名以源码为准)。

安装

go get github.com/oekit/redisx@v0.6.1

这个仓库做什么

redisx 是 Redis 全家桶:客户端封装(根包)、分布式缓存后端(cache)、 分布式锁(distlock)、分布式限流(ratelimit)。

组成

包 做什么
根包 Redis 客户端封装(NewClientFromConfig,原 redisx 子包上收)
cache pkg 缓存接口(pkg/cache)的 Redis 后端实现(原 redis/ 子包;行为契约由 pkg 的 cachetest 套件机器验证)
distlock 分布式锁
ratelimit 分布式限流——固定窗口 + 令牌桶(Lua 三态 + 故障本地兜底,存储抽象收 go-redis v9 的 redis.Scripter 接口)

快速使用

import "github.com/oekit/redisx"

cli, err := redisx.NewClientFromConfig(ctx, redisx.RedisConfig{ /* Addr/DB/Pool */ })

tracing 接入(显式装饰器,零注入默认):

import redisotel "github.com/oekit/tracing/redisotel"

_ = redisotel.InstrumentTracing(cli.Client()) // 无 SDK 时 noop

边界

  • 缓存接口定义在 pkg 的 cache 子包;本仓 cache 是其 Redis 后端 (import github.com/oekit/redisx/cache),行为契约由 data 的 cachetest 套件机器验证

规划

  • 新缓存后端(etcd/consul 等)落在 data 侧按其 cachetest 模板接入,本仓仅在需要时提供传输层封装
  • 两级缓存(Local + Redis 组合,含失效广播):单独立项

矩阵总览(21 活跃模块,自动生成)

模块 内容 矩阵内依赖
pkg 微工具集 21 合 1(errors/bloomx/contextx/collectionx/validator/stringx/slicex/enumx/convert/encoding/jsonrepair/httpjson/mathx/pathx/pagination/ptrx/timex/uidgen/cache/bufiox/strmap);cache(v0.4.0 起)含缓存接口 CacheAside + LocalCache/SingleFlightCache + cachetest 契约 + Checker;collectionx(v0.5.0 起)泛型容器 Set/Ring/Queue/SafeMap —
concurrency 并发与流控原语(async/gopool/group/singleflight/progress/syncx/ratelimit/retry)+ window 滑动窗口 / breaker 自适应熔断(规范哨兵 ErrCircuitOpen)/ shedding CPU 自适应降载 / batch 攒批执行器(满条数/满字节/窗口去重)/ timewheel 单级时间轮 —
logx 统一日志门面(多后端可替换 + Sink + caller 归属)+ 优雅关停;桥接子包 hlog/hertzlog/kitexlog 为嵌套模块按需引入 —
core 应用基建件(governance 治理 schema / config 配置加载 + default/env/range/options tag 校验 / lifecycle 契约 / network IP 工具 / version) logx
metrics Prometheus 门面 + 弹性指标族 core
tracing OpenTelemetry 追踪 + trace_id 真相源 logx
registry 注册发现核心 + Nacos 实现 + Nacos 配置源 + sdbridge core、logx
data 数据访问门面——复刻 ekit data/ 能力面:cache/rediscache/crud/distlock/gormx/redisx/timertask/cachetest 八子包 re-export(类型同一,实现住 pkg 与各子仓)+ cached 缓存读写编排(写后失效/事务提交后失效/查询缓存版本号失效/GetByIDs/bloom 防穿透)+ twolevel 两级缓存与跨实例失效广播(v0.7.0 起本仓唯二非 re-export 实现);all/ 聚合模块已废弃 retract concurrency、gormx、logx、pkg、redisx、timertask
gormx SQL/GORM 全家——连接池增强、框架无关 CRUD Service、仓储(原 oekit/gorm,v0.3.0 更名) logx、pkg
redisx Redis 全家——客户端封装(根包)、分布式缓存 cache/、分布式锁 distlock、分布式限流 ratelimit(Lua 三态 + 故障本地兜底) concurrency、logx、pkg
httpx HTTP 客户端 + 负载均衡——服务发现/熔断(规范哨兵 ErrCircuitOpen)/重试/指标/OTel 透传/一致性哈希(权重感知虚拟副本) concurrency、core、logx、metrics、registry、tracing
network 轻量网络客户端——WebSocket/NATS/MQ 抽象、连接与流工具、Octopus 推送 concurrency、logx、tracing
timertask 分片定时任务(FNV-1a、心跳续约) concurrency、logx
middleware Hertz 自研标准中间件栈 + contrib 桥接 + hmw + SheddingMiddleware 自适应降载 concurrency、core、logx、metrics、pkg、registry、tracing
nns NNS 服务治理客户端——provider 无关发现/配置/实例缓存 concurrency、core、logx、registry
nns-endpoint NNS 端点工厂——per-service 熔断、换实例重试、gRPC 池 concurrency、core、httpx、logx、metrics、nns、registry
bootstrap 应用生命周期引导——bootstrap.Run 骨架 + healthz concurrency、logx
hertz Hertz 运行时集成——日志桥接、生命周期、SSE/health/metrics、适配器、OTel、crudh/validatorh/versionh(原 handler 微库收编) bootstrap、concurrency、core、gormx、logx、metrics、middleware、nns、pkg、registry、tracing
kitex Kitex 生态——日志桥接、治理热更、生命周期、BizError 桥接、kitexotel、istio(xDS 动态熔断,原 istio 微库收编) bootstrap、concurrency、core、logx、metrics、nns、pkg、registry
workflow 组合式流程编排——串行/并行/异步/条件分支 + Hook AOP concurrency、logx
kitex-examples Kitex echo 示例——client/server + IDL + 治理配置 bootstrap、concurrency、core、kitex、logx、metrics、nns、pkg、registry、tracing

依赖严格自底向上;微库已合并为 pkg,旧微库仓已删除。

本仓在矩阵中的位置与依赖见上表「矩阵内依赖」列。历史沿革:源自 ekit 单体库 (git.enjoye.top/enjoydream/ekit v0.34.0,冻结维护),2026-10 拆分为独立 module。

License

MIT — 见 LICENSE

Documentation

Overview

Package redisx 提供 Redis 客户端封装。

所有 enjoydream 后端服务共享此包,统一封装:key 前缀管理。 零可观测性副作用:构造不注入任何 tracing;需要 OpenTelemetry span 时 用 github.com/oekit/tracing/redisotel 装饰器显式接入。

核心特性

  • key 前缀自动添加(prefix:key 格式)
  • 支持 redis.UniversalClient(兼容单机、集群、哨兵模式)
  • 提供 Client() 方法获取原生客户端(用于 distlock、tracing 接入等场景)

快速接入

从地址创建:

client, err := redisx.NewClientFromAddr("localhost:6379", "", 0,
    redisx.WithPrefix("myservice"),
)
if err != nil {
    log.Fatal(err)
}
defer client.Close()

从配置创建(支持集群):

opt := &redis.UniversalOptions{
    Addrs:    []string{"redis-1:6379", "redis-2:6379"},
    Password: "password",
    DB:       0,
}
client, err := redisx.NewClient(opt, redisx.WithPrefix("myservice"))

Key 前缀

所有操作的 key 会自动添加 "prefix:" 前缀:

client.Set(ctx, "user:123", value, 0)
// 实际存储的 key 为 "myservice:user:123"

原生客户端

需要原生 redis.UniversalClient 时(如 distlock、cache、tracing 接入等包):

locker := distlock.NewRedisLocker(client.Client(), distlock.WithPrefix("myservice"))
_ = redisotel.InstrumentTracing(client.Client()) // github.com/oekit/tracing/redisotel

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Batch

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

Batch 封装 Redis Pipeline 批量操作。 将多个命令打包发送,减少网络往返次数。 与直接使用 Pipeline 不同,Batch 自动处理 key 前缀转换。

func (*Batch) Del

func (b *Batch) Del(ctx context.Context, keys ...string)

Del 批量删除。

func (*Batch) Discard

func (b *Batch) Discard()

Discard 丢弃批量操作中的所有命令。

func (*Batch) Exec

func (b *Batch) Exec(ctx context.Context) ([]redis.Cmder, error)

Exec 执行所有批量操作,返回所有命令的结果。

func (*Batch) Exists

func (b *Batch) Exists(ctx context.Context, keys ...string) *redis.IntCmd

Exists 批量检查 key 存在。

func (*Batch) Expire

func (b *Batch) Expire(ctx context.Context, key string, ttl time.Duration)

Expire 批量设置过期时间。

func (*Batch) Get

func (b *Batch) Get(ctx context.Context, key string) *redis.StringCmd

Get 批量 Get 操作。

func (*Batch) HGet

func (b *Batch) HGet(ctx context.Context, key, field string) *redis.StringCmd

HGet 批量 Hash Get。

func (*Batch) HSet

func (b *Batch) HSet(ctx context.Context, key string, values ...any)

HSet 批量 Hash Set。

func (*Batch) Incr

func (b *Batch) Incr(ctx context.Context, key string) *redis.IntCmd

Incr 批量自增。

func (*Batch) IncrBy

func (b *Batch) IncrBy(ctx context.Context, key string, value int64) *redis.IntCmd

IncrBy 批量按增量自增。

func (*Batch) Len

func (b *Batch) Len() int

Len 返回批量操作中待执行的命令数量。

func (*Batch) Set

func (b *Batch) Set(ctx context.Context, key string, value any, ttl time.Duration)

Set 批量 Set 操作。

type BloomFilter

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

BloomFilter 是基于 RedisBloom 的布隆过滤器封装。 需要 Redis 服务器安装 RedisBloom 模块。

func (*BloomFilter) Add

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

Add 向布隆过滤器添加元素。 返回 true 表示元素可能是新添加的,false 表示元素已存在。

func (*BloomFilter) Exists

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

Exists 检查元素是否可能存在。 返回 true 表示元素可能存在(有误判率),false 表示元素一定不存在。

func (*BloomFilter) Info

func (bf *BloomFilter) Info(ctx context.Context) (map[string]any, error)

Info 获取布隆过滤器信息。 BF.INFO 返回交替的 key-value 数组,本方法将其解析为 map。

func (*BloomFilter) MAdd

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

MAdd 批量添加元素。 返回每个元素的结果:true 表示新添加,false 表示已存在。

func (*BloomFilter) MExists

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

MExists 批量检查元素是否存在。

type Client

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

Client 是带 key 前缀的 Redis 客户端封装。

func NewClient

func NewClient(opt *redis.UniversalOptions, opts ...RedisClientOptionFunc) (*Client, error)

NewClient 从 UniversalOptions 创建 Redis 客户端。

零可观测性副作用:不自动注入任何 tracing。需要 OpenTelemetry span 时 用装饰器显式接入(无 SDK 时 noop):

c, _ := redisx.NewClient(opt)
_ = redisotel.InstrumentTracing(c.Client()) // github.com/oekit/tracing/redisotel

func NewClientFromAddr

func NewClientFromAddr(addr, password string, db int, opts ...RedisClientOptionFunc) (*Client, error)

NewClientFromAddr 从地址字符串创建 Redis 客户端(便捷方法)。

func NewClientFromConfig

func NewClientFromConfig(ctx context.Context, cfg RedisConfig) (*Client, error)

NewClientFromConfig 从配置创建 Redis 客户端(构造后立即 Ping 验证连通性)。

用法:

client, err := redis.NewClientFromConfig(ctx, redis.RedisConfig{
    Host: cfg.Redis.Host, Port: cfg.Redis.Port,
    Password: cfg.Redis.Password, DB: cfg.Redis.DB,
})

func (*Client) Client

func (c *Client) Client() redis.UniversalClient

Client 返回底层 redis.UniversalClient(用于 distlock 等需要原生客户端的场景)。

func (*Client) Close

func (c *Client) Close() error

Close 关闭底层 Redis 连接。

func (*Client) Decr

func (c *Client) Decr(ctx context.Context, key string) *redis.IntCmd

Decr 将 key 的值减 1。

func (*Client) DecrBy

func (c *Client) DecrBy(ctx context.Context, key string, value int64) *redis.IntCmd

DecrBy 将 key 的值减少指定减量。

func (*Client) Del

func (c *Client) Del(ctx context.Context, keys ...string) *redis.IntCmd

Del 删除一个或多个 key。

func (*Client) Eval

func (c *Client) Eval(ctx context.Context, script string, keys []string, args ...any) *redis.Cmd

Eval 执行 Lua 脚本。

func (*Client) EvalRO

func (c *Client) EvalRO(ctx context.Context, script string, keys []string, args ...any) *redis.Cmd

EvalRO 执行只读 Lua 脚本。

func (*Client) EvalSha

func (c *Client) EvalSha(ctx context.Context, sha1 string, keys []string, args ...any) *redis.Cmd

EvalSha 通过 SHA1 执行已缓存的 Lua 脚本。

func (*Client) EvalShaRO

func (c *Client) EvalShaRO(ctx context.Context, sha1 string, keys []string, args ...any) *redis.Cmd

EvalShaRO 通过 SHA1 执行已缓存的只读 Lua 脚本。

func (*Client) Exists

func (c *Client) Exists(ctx context.Context, keys ...string) *redis.IntCmd

Exists 检查 key 是否存在。

func (*Client) Expire

func (c *Client) Expire(ctx context.Context, key string, expiration time.Duration) *redis.BoolCmd

Expire 设置 key 的过期时间。

func (*Client) Get

func (c *Client) Get(ctx context.Context, key string) *redis.StringCmd

Get 获取 key 的值。

func (*Client) HDel

func (c *Client) HDel(ctx context.Context, key string, fields ...string) *redis.IntCmd

HDel 删除 hash 中的一个或多个字段。

func (*Client) HGet

func (c *Client) HGet(ctx context.Context, key, field string) *redis.StringCmd

HGet 获取 hash 中指定字段的值。

func (*Client) HGetAll

func (c *Client) HGetAll(ctx context.Context, key string) *redis.MapStringStringCmd

HGetAll 获取 hash 中所有字段和值。

func (*Client) HSet

func (c *Client) HSet(ctx context.Context, key string, values ...any) *redis.IntCmd

HSet 设置 hash 中的一个或多个字段。

func (*Client) Incr

func (c *Client) Incr(ctx context.Context, key string) *redis.IntCmd

Incr 将 key 的值加 1。

func (*Client) IncrBy

func (c *Client) IncrBy(ctx context.Context, key string, value int64) *redis.IntCmd

IncrBy 将 key 的值增加指定增量。

func (*Client) LLen

func (c *Client) LLen(ctx context.Context, key string) *redis.IntCmd

LLen 获取列表长度。

func (*Client) LPop

func (c *Client) LPop(ctx context.Context, key string) *redis.StringCmd

LPop 移除并返回列表头部元素。

func (*Client) LPush

func (c *Client) LPush(ctx context.Context, key string, values ...any) *redis.IntCmd

LPush 将一个或多个值插入列表头部。

func (*Client) LRange

func (c *Client) LRange(ctx context.Context, key string, start, stop int64) *redis.StringSliceCmd

LRange 获取列表指定范围的元素。

func (*Client) NewBatch

func (c *Client) NewBatch() *Batch

NewBatch 创建一个批量操作实例。

func (*Client) NewBloomFilter

func (c *Client) NewBloomFilter(ctx context.Context, key string, errorRate float64, capacity int64) (*BloomFilter, error)

NewBloomFilter 创建布隆过滤器。 如果 key 不存在,会自动创建。

参数:

  • ctx: 上下文(支持超时/取消)
  • key: 布隆过滤器的 key 名
  • errorRate: 误判率(如 0.01 表示 1%)
  • capacity: 预计元素数量

func (*Client) NewCounter

func (c *Client) NewCounter(key string) *Counter

NewCounter 创建分布式计数器。

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) *redis.StatusCmd

Ping 测试连接。

func (*Client) Pipeline

func (c *Client) Pipeline() redis.Pipeliner

Pipeline 创建一个管道(批量发送命令,减少网络往返)。

注意:返回的 Pipeline 不会自动添加 key 前缀。 如需前缀处理,请使用 NewBatch()。

func (*Client) Publish

func (c *Client) Publish(ctx context.Context, channel string, message any) *redis.IntCmd

Publish 向频道发布消息。

func (*Client) RPop

func (c *Client) RPop(ctx context.Context, key string) *redis.StringCmd

RPop 移除并返回列表尾部元素。

func (*Client) RPush

func (c *Client) RPush(ctx context.Context, key string, values ...any) *redis.IntCmd

RPush 将一个或多个值插入列表尾部。

func (*Client) SAdd

func (c *Client) SAdd(ctx context.Context, key string, members ...any) *redis.IntCmd

SAdd 向集合添加一个或多个成员。

func (*Client) SIsMember

func (c *Client) SIsMember(ctx context.Context, key string, member any) *redis.BoolCmd

SIsMember 判断成员是否在集合中。

func (*Client) SMembers

func (c *Client) SMembers(ctx context.Context, key string) *redis.StringSliceCmd

SMembers 获取集合所有成员。

func (*Client) SRem

func (c *Client) SRem(ctx context.Context, key string, members ...any) *redis.IntCmd

SRem 从集合移除一个或多个成员。

func (*Client) ScriptExists

func (c *Client) ScriptExists(ctx context.Context, hashes ...string) *redis.BoolSliceCmd

ScriptExists 检查脚本是否已缓存。

func (*Client) ScriptLoad

func (c *Client) ScriptLoad(ctx context.Context, script string) *redis.StringCmd

ScriptLoad 将脚本加载到脚本缓存。

func (*Client) Set

func (c *Client) Set(ctx context.Context, key string, value any, expiration time.Duration) *redis.StatusCmd

Set 设置 key 的值。

func (*Client) SetNX

func (c *Client) SetNX(ctx context.Context, key string, value any, expiration time.Duration) *redis.BoolCmd

SetNX 仅当 key 不存在时设置。

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, channels ...string) *redis.PubSub

Subscribe 订阅一个或多个频道。

func (*Client) TxPipeline

func (c *Client) TxPipeline() redis.Pipeliner

TxPipeline 创建一个事务管道。

注意:返回的 Pipeline 不会自动添加 key 前缀。 如需前缀处理,请使用 NewBatch()。

func (*Client) ZAdd

func (c *Client) ZAdd(ctx context.Context, key string, members ...redis.Z) *redis.IntCmd

ZAdd 向有序集合添加一个或多个成员。

func (*Client) ZCard

func (c *Client) ZCard(ctx context.Context, key string) *redis.IntCmd

ZCard 获取有序集合的成员数。

func (*Client) ZRange

func (c *Client) ZRange(ctx context.Context, key string, start, stop int64) *redis.StringSliceCmd

ZRange 获取有序集合指定范围的成员。

func (*Client) ZRangeWithScores

func (c *Client) ZRangeWithScores(ctx context.Context, key string, start, stop int64) *redis.ZSliceCmd

ZRangeWithScores 获取有序集合指定范围的成员(含分数)。

func (*Client) ZRem

func (c *Client) ZRem(ctx context.Context, key string, members ...any) *redis.IntCmd

ZRem 从有序集合移除一个或多个成员。

type Counter

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

Counter 是分布式原子计数器。 基于 Redis INCR/DECR 实现,支持原子增减和过期。

func (*Counter) Decr

func (ct *Counter) Decr(ctx context.Context, delta int64) (int64, error)

Decr 原子减少并返回新值。 注意:Redis DECR 允许结果为负数。如需下界保护,使用 DecrFloor。

func (*Counter) DecrFloor

func (ct *Counter) DecrFloor(ctx context.Context, delta int64, floor int64) (int64, error)

DecrFloor 原子减少并返回新值,结果不低于 floor(默认 0)。 适用于配额、限流等不允许负数的场景。

func (*Counter) Get

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

Get 获取当前值。key 不存在时返回 0。

func (*Counter) Incr

func (ct *Counter) Incr(ctx context.Context, delta int64) (int64, error)

Incr 原子增加并返回新值。

func (*Counter) IncrWithTTL

func (ct *Counter) IncrWithTTL(ctx context.Context, delta int64, ttl time.Duration) (int64, error)

IncrWithTTL 原子增加并设置过期时间。 如果 key 已有 TTL,只增加不影响原有 TTL;如果 key 无 TTL,设置指定的 TTL。

func (*Counter) Reset

func (ct *Counter) Reset(ctx context.Context) error

Reset 重置计数器(删除 key)。

type RedisClientOption

type RedisClientOption struct {
	Prefix string
}

RedisClientOption 配置 Client 的可选参数。

type RedisClientOptionFunc

type RedisClientOptionFunc func(*RedisClientOption)

RedisClientOptionFunc 配置函数类型。

func WithPrefix

func WithPrefix(prefix string) RedisClientOptionFunc

WithPrefix 设置 key 前缀。 所有操作的 key 会自动添加 "prefix:" 前缀。

type RedisConfig

type RedisConfig struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Password string `yaml:"password"`
	DB       int    `yaml:"db"`
}

RedisConfig 是 Redis 连接配置,可直接从 YAML 反序列化。

Directories

Path Synopsis
Package cache 提供基于 go-redis 的 Cache[T] 分布式缓存实现。
Package cache 提供基于 go-redis 的 Cache[T] 分布式缓存实现。
Package distlock 提供分布式锁门面。
Package distlock 提供分布式锁门面。
Package ratelimit 提供基于 Redis 的分布式限流器。
Package ratelimit 提供基于 Redis 的分布式限流器。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL