backend

package
v0.0.0-...-3470e27 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const NilMarker = "__GO_CACHE_NIL__"

NilMarker 空值标记,用于缓存穿透保护(导出供其他包使用)

Variables

View Source
var (
	ErrEmptyName      = &BackendError{Code: "EMPTY_NAME", Message: "缓存名称不能为空"}
	ErrInvalidMaxSize = &BackendError{Code: "INVALID_MAX_SIZE", Message: "最大容量必须大于 0"}
)
View Source
var BackendRegistry = make(map[string]BackendFactory)

BackendRegistry 后端注册表

Functions

func Register

func Register(name string, factory BackendFactory)

Register 注册缓存后端实现

func ValidateConfig

func ValidateConfig(config *CacheConfig) error

ValidateConfig 验证配置

Types

type BackendError

type BackendError struct {
	Code    string
	Message string
}

错误定义

func (*BackendError) Error

func (e *BackendError) Error() string

type BackendFactory

type BackendFactory func(config *CacheConfig) (CacheBackend, error)

BackendFactory 后端工厂函数类型

func GetFactory

func GetFactory(name string) (BackendFactory, bool)

GetFactory 获取后端工厂

type CacheBackend

type CacheBackend interface {
	Get(ctx context.Context, key string) (interface{}, bool, error)
	Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
	Close() error
	Stats() *CacheStats
}

CacheBackend 缓存后端接口(本地定义避免循环导入)

type CacheConfig

type CacheConfig struct {
	Name           string
	MaxSize        int64
	DefaultTTL     time.Duration
	MaxTTL         time.Duration
	EvictionPolicy string
}

CacheConfig 缓存配置

func DefaultCacheConfig

func DefaultCacheConfig(name string) *CacheConfig

DefaultCacheConfig 默认配置

type CacheInvalidator

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

CacheInvalidator 缓存失效广播器

func NewCacheInvalidator

func NewCacheInvalidator(config *CacheInvalidatorConfig) (*CacheInvalidator, error)

NewCacheInvalidator 创建缓存失效广播器

func (*CacheInvalidator) Broadcast

func (ci *CacheInvalidator) Broadcast(key string) error

Broadcast 广播缓存失效消息

func (*CacheInvalidator) BroadcastWithCache

func (ci *CacheInvalidator) BroadcastWithCache(cacheName, key string) error

BroadcastWithCache 广播带缓存名称的失效消息

func (*CacheInvalidator) Channel

func (ci *CacheInvalidator) Channel() string

Channel 获取频道名称

func (*CacheInvalidator) Close

func (ci *CacheInvalidator) Close() error

Close 关闭广播器

func (*CacheInvalidator) IsClosed

func (ci *CacheInvalidator) IsClosed() bool

IsClosed 检查是否已关闭

func (*CacheInvalidator) OnInvalidation

func (ci *CacheInvalidator) OnInvalidation(handler func(key string))

OnInvalidation 注册失效回调(非阻塞)

func (*CacheInvalidator) Subscribe

func (ci *CacheInvalidator) Subscribe(callback func(key string))

Subscribe 订阅缓存失效消息(阻塞式)

func (*CacheInvalidator) SubscribeWithContext

func (ci *CacheInvalidator) SubscribeWithContext(ctx context.Context, callback func(key string)) error

SubscribeWithContext 带上下文的订阅(可取消)

type CacheInvalidatorConfig

type CacheInvalidatorConfig struct {
	Addr        string        // Redis 地址
	Password    string        // Redis 密码
	DB          int           // Redis 数据库
	Channel     string        // Pub/Sub 频道名称
	DialTimeout time.Duration // 连接超时
	ReadTimeout time.Duration // 读取超时
}

CacheInvalidatorConfig 缓存失效广播器配置

func DefaultCacheInvalidatorConfig

func DefaultCacheInvalidatorConfig() *CacheInvalidatorConfig

DefaultCacheInvalidatorConfig 默认配置

type CacheItem

type CacheItem struct {
	Value      interface{}
	ExpiresAt  time.Time
	CreatedAt  time.Time
	LastAccess time.Time
}

CacheItem 缓存项

func (*CacheItem) IsExpired

func (i *CacheItem) IsExpired() bool

type CacheStats

type CacheStats struct {
	Hits, Misses, Sets, Deletes, Evictions, Size, MaxSize int64
	HitRate                                               float64
}

CacheStats 缓存统计

type DefaultKeyBuilder

type DefaultKeyBuilder struct {
	Separator string
	Prefix    string
}

DefaultKeyBuilder 默认键构建器

func NewDefaultKeyBuilder

func NewDefaultKeyBuilder(separator, prefix string) *DefaultKeyBuilder

func (*DefaultKeyBuilder) Build

func (kb *DefaultKeyBuilder) Build(parts ...string) string

type HybridBackend

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

HybridBackend 混合缓存后端(L1+L2 两级缓存) L1: 本地 Memory 缓存(快速访问) L2: Redis 缓存(分布式共享)

func NewHybridBackend

func NewHybridBackend(config *HybridConfig) (*HybridBackend, error)

NewHybridBackend 创建混合缓存后端

func (*HybridBackend) Close

func (h *HybridBackend) Close() error

Close 关闭缓存后端

func (*HybridBackend) Delete

func (h *HybridBackend) Delete(ctx context.Context, key string) error

Delete 删除缓存值(同时删除 L1 和 L2)

func (*HybridBackend) Get

func (h *HybridBackend) Get(ctx context.Context, key string) (interface{}, bool, error)

Get 获取缓存值(L1 → L2 级联查询)

func (*HybridBackend) GetHybridStats

func (h *HybridBackend) GetHybridStats() *HybridStats

GetHybridStats 获取混合缓存详细统计

func (*HybridBackend) GetL1

func (h *HybridBackend) GetL1() *MemoryBackend

GetL1 获取 L1 缓存(用于高级操作)

func (*HybridBackend) GetL2

func (h *HybridBackend) GetL2() *RedisBackend

GetL2 获取 L2 缓存(用于高级操作)

func (*HybridBackend) Set

func (h *HybridBackend) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set 设置缓存值(同时写入 L1 和 L2)

func (*HybridBackend) Stats

func (h *HybridBackend) Stats() *CacheStats

Stats 获取缓存统计信息

type HybridConfig

type HybridConfig struct {
	L1Config       *CacheConfig  // L1 配置
	L2Config       *RedisConfig  // L2 配置
	L1WriteBackTTL time.Duration // L1 回写 TTL(默认 5 分钟)
}

HybridConfig 混合缓存配置

func DefaultHybridConfig

func DefaultHybridConfig() *HybridConfig

DefaultHybridConfig 默认混合缓存配置

type HybridStats

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

HybridStats 混合缓存统计

type InvalidationMessage

type InvalidationMessage struct {
	CacheName string `json:"cache_name"`
	Key       string `json:"key"`
	Timestamp int64  `json:"timestamp"`
}

InvalidationMessage 失效消息

func UnmarshalInvalidationMessage

func UnmarshalInvalidationMessage(data []byte) (*InvalidationMessage, error)

UnmarshalInvalidationMessage 反序列化消息

func (*InvalidationMessage) Marshal

func (m *InvalidationMessage) Marshal() ([]byte, error)

Marshal 序列化消息

type KeyBuilder

type KeyBuilder interface {
	Build(parts ...string) string
}

KeyBuilder 键构建器

type MemoryBackend

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

MemoryBackend 内存缓存后端

func NewMemoryBackend

func NewMemoryBackend(config *CacheConfig) (*MemoryBackend, error)

func (*MemoryBackend) Close

func (m *MemoryBackend) Close() error

func (*MemoryBackend) Delete

func (m *MemoryBackend) Delete(ctx context.Context, key string) error

func (*MemoryBackend) Get

func (m *MemoryBackend) Get(ctx context.Context, key string) (interface{}, bool, error)

func (*MemoryBackend) Set

func (m *MemoryBackend) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

func (*MemoryBackend) Stats

func (m *MemoryBackend) Stats() *CacheStats

type RedisBackend

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

RedisBackend Redis 缓存后端实现

func NewRedisBackend

func NewRedisBackend(config *RedisConfig) (*RedisBackend, error)

NewRedisBackend 创建 Redis 后端实例

func (*RedisBackend) Clear

func (r *RedisBackend) Clear(ctx context.Context) error

Clear 清空所有缓存(危险操作)

func (*RedisBackend) Client

func (r *RedisBackend) Client() *redis.Client

Client 获取底层 Redis 客户端(用于高级操作)

func (*RedisBackend) Close

func (r *RedisBackend) Close() error

Close 关闭 Redis 连接

func (*RedisBackend) Delete

func (r *RedisBackend) Delete(ctx context.Context, key string) error

Delete 删除缓存值

func (*RedisBackend) Get

func (r *RedisBackend) Get(ctx context.Context, key string) (interface{}, bool, error)

Get 从 Redis 获取缓存值

func (*RedisBackend) Ping

func (r *RedisBackend) Ping(ctx context.Context) error

Ping 测试 Redis 连接

func (*RedisBackend) Set

func (r *RedisBackend) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set 设置缓存值

func (*RedisBackend) SetWithJitter

func (r *RedisBackend) SetWithJitter(ctx context.Context, key string, value interface{}, baseTTL time.Duration, jitterFactor float64) error

SetWithJitter 设置带随机 TTL 偏移的缓存值(防雪崩)

func (*RedisBackend) Stats

func (r *RedisBackend) Stats() *CacheStats

Stats 获取缓存统计信息

type RedisClusterBackend

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

RedisClusterBackend Redis Cluster 缓存后端实现

func NewRedisClusterBackend

func NewRedisClusterBackend(config *RedisClusterConfig) (*RedisClusterBackend, error)

NewRedisClusterBackend 创建 Redis Cluster 后端实例

func (*RedisClusterBackend) Clear

func (r *RedisClusterBackend) Clear(ctx context.Context) error

Clear 清空缓存(危险操作)

func (*RedisClusterBackend) Client

Client 获取底层 Cluster 客户端

func (*RedisClusterBackend) Close

func (r *RedisClusterBackend) Close() error

Close 关闭连接

func (*RedisClusterBackend) ClusterNodes

func (r *RedisClusterBackend) ClusterNodes(ctx context.Context) (string, error)

ClusterNodes 获取集群节点信息

func (*RedisClusterBackend) ClusterSlots

func (r *RedisClusterBackend) ClusterSlots(ctx context.Context) ([]redis.ClusterSlot, error)

ClusterSlots 获取集群槽位信息

func (*RedisClusterBackend) Delete

func (r *RedisClusterBackend) Delete(ctx context.Context, key string) error

Delete 删除缓存值

func (*RedisClusterBackend) Get

func (r *RedisClusterBackend) Get(ctx context.Context, key string) (interface{}, bool, error)

Get 从 Redis Cluster 获取缓存值

func (*RedisClusterBackend) Ping

Ping 测试连接

func (*RedisClusterBackend) Set

func (r *RedisClusterBackend) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set 设置缓存值

func (*RedisClusterBackend) SetWithJitter

func (r *RedisClusterBackend) SetWithJitter(ctx context.Context, key string, value interface{}, baseTTL time.Duration, jitterFactor float64) error

SetWithJitter 设置带随机 TTL 偏移的缓存值(防雪崩)

func (*RedisClusterBackend) Stats

func (r *RedisClusterBackend) Stats() *CacheStats

Stats 获取统计信息

type RedisClusterConfig

type RedisClusterConfig struct {
	Addrs         []string      // Cluster 节点地址列表
	Password      string        // Redis 密码
	DialTimeout   time.Duration // 连接超时
	ReadTimeout   time.Duration // 读取超时
	WriteTimeout  time.Duration // 写入超时
	PoolSize      int           // 连接池大小
	MinIdleConns  int           // 最小空闲连接
	MaxRetries    int           // 最大重试次数
	Prefix        string        // Key 前缀
	DefaultTTL    time.Duration // 默认 TTL
	MaxTTL        time.Duration // 最大 TTL
	RouteByPrefix bool          // 是否按前缀路由(高级特性)
	Serializer    string        // 序列化器类型:json, gob, msgpack
}

RedisClusterConfig Redis Cluster 配置

func DefaultRedisClusterConfig

func DefaultRedisClusterConfig() *RedisClusterConfig

DefaultRedisClusterConfig 默认 Cluster 配置

type RedisClusterStats

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

RedisClusterStats Cluster 统计信息

type RedisConfig

type RedisConfig struct {
	Addr         string        // Redis 地址,如 "localhost:6379"
	Password     string        // Redis 密码
	DB           int           // Redis 数据库编号
	Prefix       string        // Key 前缀
	DefaultTTL   time.Duration // 默认 TTL
	MaxTTL       time.Duration // 最大 TTL
	PoolSize     int           // 连接池大小
	MinIdleConns int           // 最小空闲连接
	MaxRetries   int           // 最大重试次数
	DialTimeout  time.Duration // 连接超时
	ReadTimeout  time.Duration // 读取超时
	WriteTimeout time.Duration // 写入超时
}

RedisConfig Redis 后端配置

func DefaultRedisConfig

func DefaultRedisConfig() *RedisConfig

DefaultRedisConfig 默认 Redis 配置

type RedisStats

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

RedisStats Redis 缓存统计

type StatsCounter

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

StatsCounter 统计计数器

func NewStatsCounter

func NewStatsCounter(maxSize int64) *StatsCounter

func (*StatsCounter) DecSize

func (c *StatsCounter) DecSize()

func (*StatsCounter) IncSize

func (c *StatsCounter) IncSize()

func (*StatsCounter) RecordDelete

func (c *StatsCounter) RecordDelete()

func (*StatsCounter) RecordEviction

func (c *StatsCounter) RecordEviction()

func (*StatsCounter) RecordHit

func (c *StatsCounter) RecordHit()

func (*StatsCounter) RecordMiss

func (c *StatsCounter) RecordMiss()

func (*StatsCounter) RecordSet

func (c *StatsCounter) RecordSet()

func (*StatsCounter) SetSize

func (c *StatsCounter) SetSize(s int64)

func (*StatsCounter) Snapshot

func (c *StatsCounter) Snapshot() *CacheStats

type TTLManager

type TTLManager struct {
	DefaultTTL, MaxTTL time.Duration
}

TTLManager TTL 管理器

func NewTTLManager

func NewTTLManager(defaultTTL, maxTTL time.Duration) *TTLManager

func (*TTLManager) Normalize

func (tm *TTLManager) Normalize(ttl time.Duration) time.Duration

Jump to

Keyboard shortcuts

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