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 ¶
- type Batch
- func (b *Batch) Del(ctx context.Context, keys ...string)
- func (b *Batch) Discard()
- func (b *Batch) Exec(ctx context.Context) ([]redis.Cmder, error)
- func (b *Batch) Exists(ctx context.Context, keys ...string) *redis.IntCmd
- func (b *Batch) Expire(ctx context.Context, key string, ttl time.Duration)
- func (b *Batch) Get(ctx context.Context, key string) *redis.StringCmd
- func (b *Batch) HGet(ctx context.Context, key, field string) *redis.StringCmd
- func (b *Batch) HSet(ctx context.Context, key string, values ...any)
- func (b *Batch) Incr(ctx context.Context, key string) *redis.IntCmd
- func (b *Batch) IncrBy(ctx context.Context, key string, value int64) *redis.IntCmd
- func (b *Batch) Len() int
- func (b *Batch) Set(ctx context.Context, key string, value any, ttl time.Duration)
- type BloomFilter
- func (bf *BloomFilter) Add(ctx context.Context, item string) (bool, error)
- func (bf *BloomFilter) Exists(ctx context.Context, item string) (bool, error)
- func (bf *BloomFilter) Info(ctx context.Context) (map[string]any, error)
- func (bf *BloomFilter) MAdd(ctx context.Context, items ...string) ([]bool, error)
- func (bf *BloomFilter) MExists(ctx context.Context, items ...string) ([]bool, error)
- type Client
- func (c *Client) Client() redis.UniversalClient
- func (c *Client) Close() error
- func (c *Client) Decr(ctx context.Context, key string) *redis.IntCmd
- func (c *Client) DecrBy(ctx context.Context, key string, value int64) *redis.IntCmd
- func (c *Client) Del(ctx context.Context, keys ...string) *redis.IntCmd
- func (c *Client) Eval(ctx context.Context, script string, keys []string, args ...any) *redis.Cmd
- func (c *Client) EvalRO(ctx context.Context, script string, keys []string, args ...any) *redis.Cmd
- func (c *Client) EvalSha(ctx context.Context, sha1 string, keys []string, args ...any) *redis.Cmd
- func (c *Client) EvalShaRO(ctx context.Context, sha1 string, keys []string, args ...any) *redis.Cmd
- func (c *Client) Exists(ctx context.Context, keys ...string) *redis.IntCmd
- func (c *Client) Expire(ctx context.Context, key string, expiration time.Duration) *redis.BoolCmd
- func (c *Client) Get(ctx context.Context, key string) *redis.StringCmd
- func (c *Client) HDel(ctx context.Context, key string, fields ...string) *redis.IntCmd
- func (c *Client) HGet(ctx context.Context, key, field string) *redis.StringCmd
- func (c *Client) HGetAll(ctx context.Context, key string) *redis.MapStringStringCmd
- func (c *Client) HSet(ctx context.Context, key string, values ...any) *redis.IntCmd
- func (c *Client) Incr(ctx context.Context, key string) *redis.IntCmd
- func (c *Client) IncrBy(ctx context.Context, key string, value int64) *redis.IntCmd
- func (c *Client) LLen(ctx context.Context, key string) *redis.IntCmd
- func (c *Client) LPop(ctx context.Context, key string) *redis.StringCmd
- func (c *Client) LPush(ctx context.Context, key string, values ...any) *redis.IntCmd
- func (c *Client) LRange(ctx context.Context, key string, start, stop int64) *redis.StringSliceCmd
- func (c *Client) NewBatch() *Batch
- func (c *Client) NewBloomFilter(ctx context.Context, key string, errorRate float64, capacity int64) (*BloomFilter, error)
- func (c *Client) NewCounter(key string) *Counter
- func (c *Client) Ping(ctx context.Context) *redis.StatusCmd
- func (c *Client) Pipeline() redis.Pipeliner
- func (c *Client) Publish(ctx context.Context, channel string, message any) *redis.IntCmd
- func (c *Client) RPop(ctx context.Context, key string) *redis.StringCmd
- func (c *Client) RPush(ctx context.Context, key string, values ...any) *redis.IntCmd
- func (c *Client) SAdd(ctx context.Context, key string, members ...any) *redis.IntCmd
- func (c *Client) SIsMember(ctx context.Context, key string, member any) *redis.BoolCmd
- func (c *Client) SMembers(ctx context.Context, key string) *redis.StringSliceCmd
- func (c *Client) SRem(ctx context.Context, key string, members ...any) *redis.IntCmd
- func (c *Client) ScriptExists(ctx context.Context, hashes ...string) *redis.BoolSliceCmd
- func (c *Client) ScriptLoad(ctx context.Context, script string) *redis.StringCmd
- func (c *Client) Set(ctx context.Context, key string, value any, expiration time.Duration) *redis.StatusCmd
- func (c *Client) SetNX(ctx context.Context, key string, value any, expiration time.Duration) *redis.BoolCmd
- func (c *Client) Subscribe(ctx context.Context, channels ...string) *redis.PubSub
- func (c *Client) TxPipeline() redis.Pipeliner
- func (c *Client) ZAdd(ctx context.Context, key string, members ...redis.Z) *redis.IntCmd
- func (c *Client) ZCard(ctx context.Context, key string) *redis.IntCmd
- func (c *Client) ZRange(ctx context.Context, key string, start, stop int64) *redis.StringSliceCmd
- func (c *Client) ZRangeWithScores(ctx context.Context, key string, start, stop int64) *redis.ZSliceCmd
- func (c *Client) ZRem(ctx context.Context, key string, members ...any) *redis.IntCmd
- type Counter
- func (ct *Counter) Decr(ctx context.Context, delta int64) (int64, error)
- func (ct *Counter) DecrFloor(ctx context.Context, delta int64, floor int64) (int64, error)
- func (ct *Counter) Get(ctx context.Context) (int64, error)
- func (ct *Counter) Incr(ctx context.Context, delta int64) (int64, error)
- func (ct *Counter) IncrWithTTL(ctx context.Context, delta int64, ttl time.Duration) (int64, error)
- func (ct *Counter) Reset(ctx context.Context) error
- type RedisClientOption
- type RedisClientOptionFunc
- type RedisConfig
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 前缀转换。
type BloomFilter ¶
type BloomFilter struct {
// contains filtered or unexported fields
}
BloomFilter 是基于 RedisBloom 的布隆过滤器封装。 需要 Redis 服务器安装 RedisBloom 模块。
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) NewBloomFilter ¶
func (c *Client) NewBloomFilter(ctx context.Context, key string, errorRate float64, capacity int64) (*BloomFilter, error)
NewBloomFilter 创建布隆过滤器。 如果 key 不存在,会自动创建。
⚠️ key 已存在时**复用既有过滤器**:errorRate 与 capacity 以既有实例为准, 本次传入的参数不生效(Redis 的 BF.RESERVE 对已存在的 key 不覆盖)。 需要按新参数重建,请先 DEL 该 key。
参数:
- ctx: 上下文(支持超时/取消)
- key: 布隆过滤器的 key 名
- errorRate: 误判率(如 0.01 表示 1%);key 已存在时不生效
- capacity: 预计元素数量;key 已存在时不生效
func (*Client) Pipeline ¶
Pipeline 创建一个管道(批量发送命令,减少网络往返)。
注意:返回的 Pipeline 不会自动添加 key 前缀。 如需前缀处理,请使用 NewBatch()。
func (*Client) ScriptExists ¶
ScriptExists 检查脚本是否已缓存。
func (*Client) ScriptLoad ¶
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) TxPipeline ¶
TxPipeline 创建一个事务管道。
注意:返回的 Pipeline 不会自动添加 key 前缀。 如需前缀处理,请使用 NewBatch()。
type Counter ¶
type Counter struct {
// contains filtered or unexported fields
}
Counter 是分布式原子计数器。 基于 Redis INCR/DECR 实现,支持原子增减和过期。
func (*Counter) IncrWithTTL ¶
IncrWithTTL 原子增加并设置过期时间。 如果 key 已有 TTL,只增加不影响原有 TTL;如果 key 无 TTL,设置指定的 TTL。
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:" 前缀。