Documentation
¶
Overview ¶
包 cache 提供基于 Redis 的缓存管理能力,支持连接池、健康检查、 JSON 序列化与统计信息采集。
概述 ¶
本包封装 go-redis 客户端,为上层业务提供统一的缓存读写接口。 Manager 负责连接生命周期管理,包括初始化、健康检查与优雅关闭。 支持可选 TLS 加密连接,适用于生产环境安全要求。
核心类型 ¶
- Manager:缓存管理器,持有 Redis 客户端与连接池配置, 提供 Get/Set/Delete/Exists/Expire 等基础操作, 以及 GetJSON/SetJSON 便捷序列化方法。
- Config:缓存配置,包含地址、密码、连接池大小、默认 TTL、 TLS 开关与健康检查间隔等参数。
- Stats:缓存统计信息,包含命中率、键数量、内存使用与连接数。
主要能力 ¶
- 键值读写:支持字符串与 JSON 两种模式的缓存存取。
- 连接池管理:通过 PoolSize 与 MinIdleConns 控制连接复用。
- 健康检查:后台定时 Ping 检测,异常时通过 zap 日志告警。
- 优雅关闭:Close 方法安全释放底层 Redis 连接。
- 错误语义:提供 ErrCacheMiss 哨兵错误与 IsCacheMiss 判断函数。
Index ¶
- Variables
- func IsCacheMiss(err error) bool
- type Config
- type Manager
- func (m *Manager) Close() error
- func (m *Manager) Delete(ctx context.Context, keys ...string) error
- func (m *Manager) Exists(ctx context.Context, keys ...string) (int64, error)
- func (m *Manager) Expire(ctx context.Context, key string, ttl time.Duration) error
- func (m *Manager) Get(ctx context.Context, key string) (string, error)
- func (m *Manager) GetJSON(ctx context.Context, key string, dest any) error
- func (m *Manager) GetStats(ctx context.Context) (*Stats, error)
- func (m *Manager) Ping(ctx context.Context) error
- func (m *Manager) Set(ctx context.Context, key string, value string, ttl time.Duration) error
- func (m *Manager) SetJSON(ctx context.Context, key string, value any, ttl time.Duration) error
- type Stats
Constants ¶
This section is empty.
Variables ¶
View Source
var ErrCacheMiss = errors.New("cache miss")
ErrCacheMiss 缓存未命中错误
Functions ¶
Types ¶
type Config ¶
type Config struct {
// Redis 地址
Addr string `yaml:"addr" json:"addr"`
// 密码
Password string `yaml:"password" json:"password"`
// 数据库编号
DB int `yaml:"db" json:"db"`
// 默认过期时间
DefaultTTL time.Duration `yaml:"default_ttl" json:"default_ttl"`
// 最大重试次数
MaxRetries int `yaml:"max_retries" json:"max_retries"`
// 连接池大小
PoolSize int `yaml:"pool_size" json:"pool_size"`
// 最小空闲连接数
MinIdleConns int `yaml:"min_idle_conns" json:"min_idle_conns"`
// 是否启用 TLS
TLSEnabled bool `yaml:"tls_enabled" json:"tls_enabled"`
// 健康检查间隔
HealthCheckInterval time.Duration `yaml:"health_check_interval" json:"health_check_interval"`
}
Config 缓存配置
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager 缓存管理器
func NewManager ¶
NewManager 创建缓存管理器
Click to show internal directories.
Click to hide internal directories.