cache

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2025 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package cache 提供缓存抽象层。

核心功能:

  • 多级缓存(内存 + Redis)
  • 缓存穿透/击穿/雪崩防护
  • 序列化策略(JSON/MessagePack)
  • 统计信息(命中率、键数量)

使用示例:

c := cache.NewRedis(client, cache.WithPrefix("app:"))
err := c.Set(ctx, "key", value, time.Hour)
err = c.Get(ctx, "key", &dest)

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound     = errors.New("cache: key not found")
	ErrNil          = errors.New("cache: nil value")
	ErrTypeMismatch = errors.New("cache: type mismatch")
)

预定义错误

Functions

This section is empty.

Types

type BatchCache

type BatchCache interface {
	Cache
	// MGet 批量获取
	MGet(ctx context.Context, keys []string) (map[string][]byte, error)
	// MSet 批量设置
	MSet(ctx context.Context, items map[string]any, ttl time.Duration) error
	// MDelete 批量删除
	MDelete(ctx context.Context, keys []string) error
}

BatchCache 批量操作接口

type Cache

type Cache interface {
	// Get 获取缓存
	Get(ctx context.Context, key string, dest any) error
	// Set 设置缓存
	Set(ctx context.Context, key string, value any, ttl time.Duration) error
	// Delete 删除缓存
	Delete(ctx context.Context, keys ...string) error
	// Exists 检查是否存在
	Exists(ctx context.Context, key string) (bool, error)
	// Close 关闭缓存
	Close() error
}

Cache 缓存接口

type JSONSerializer

type JSONSerializer struct{}

JSONSerializer JSON 序列化器

func (*JSONSerializer) Marshal

func (s *JSONSerializer) Marshal(v any) ([]byte, error)

func (*JSONSerializer) Unmarshal

func (s *JSONSerializer) Unmarshal(data []byte, v any) error

type LoadFunc

type LoadFunc func(ctx context.Context) (any, error)

LoadFunc 加载函数

type Loader

type Loader interface {
	Cache
	// GetOrLoad 获取或加载
	GetOrLoad(ctx context.Context, key string, dest any, loader LoadFunc, ttl time.Duration) error
}

Loader 带加载功能的缓存

type Memory

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

Memory 内存缓存

func NewMemory

func NewMemory(cfg MemoryConfig, opts ...Option) (*Memory, error)

NewMemory 创建内存缓存

func (*Memory) Close

func (m *Memory) Close() error

func (*Memory) Delete

func (m *Memory) Delete(ctx context.Context, keys ...string) error

func (*Memory) Exists

func (m *Memory) Exists(ctx context.Context, key string) (bool, error)

func (*Memory) Get

func (m *Memory) Get(ctx context.Context, key string, dest any) error

func (*Memory) Set

func (m *Memory) Set(ctx context.Context, key string, value any, ttl time.Duration) error

func (*Memory) Stats

func (m *Memory) Stats() Stats

type MemoryConfig

type MemoryConfig struct {
	MaxSize     int64 // 最大内存(字节)
	NumCounters int64 // 计数器数量
}

MemoryConfig 内存缓存配置

func DefaultMemoryConfig

func DefaultMemoryConfig() MemoryConfig

DefaultMemoryConfig 默认配置

type Metriced

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

Metriced 指标装饰器

func NewMetriced

func NewMetriced(cache Cache, name string, m *Metrics) *Metriced

NewMetriced 创建指标装饰器

func (*Metriced) Close

func (m *Metriced) Close() error

func (*Metriced) Delete

func (m *Metriced) Delete(ctx context.Context, keys ...string) error

func (*Metriced) Exists

func (m *Metriced) Exists(ctx context.Context, key string) (bool, error)

func (*Metriced) Get

func (m *Metriced) Get(ctx context.Context, key string, dest any) error

func (*Metriced) Set

func (m *Metriced) Set(ctx context.Context, key string, value any, ttl time.Duration) error

func (*Metriced) Unwrap

func (m *Metriced) Unwrap() Cache

func (*Metriced) UpdateHitRate

func (m *Metriced) UpdateHitRate()

UpdateHitRate 更新命中率指标

type Metrics

type Metrics struct {
	OpsTotal    observability.Counter
	OpsDuration observability.Histogram
	HitRate     observability.Gauge
}

Metrics 缓存指标

func NewMetrics

func NewMetrics(p observability.MetricsProvider) *Metrics

NewMetrics 创建缓存指标

type MsgpackSerializer

type MsgpackSerializer struct{}

MsgpackSerializer Msgpack 序列化器(更高效)

func (*MsgpackSerializer) Marshal

func (s *MsgpackSerializer) Marshal(v any) ([]byte, error)

func (*MsgpackSerializer) Unmarshal

func (s *MsgpackSerializer) Unmarshal(data []byte, v any) error

type MultiLevel

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

MultiLevel 多级缓存

func NewMultiLevel

func NewMultiLevel(cfg MultiLevelConfig, opts ...Option) *MultiLevel

NewMultiLevel 创建多级缓存

func NewMultiLevelCache

func NewMultiLevelCache(redisAddr, password string, db int) (*MultiLevel, error)

NewMultiLevelCache 便捷构造器

func (*MultiLevel) Close

func (m *MultiLevel) Close() error

func (*MultiLevel) Delete

func (m *MultiLevel) Delete(ctx context.Context, keys ...string) error

func (*MultiLevel) Exists

func (m *MultiLevel) Exists(ctx context.Context, key string) (bool, error)

func (*MultiLevel) Get

func (m *MultiLevel) Get(ctx context.Context, key string, dest any) error

func (*MultiLevel) GetOrLoad

func (m *MultiLevel) GetOrLoad(ctx context.Context, key string, dest any, loader LoadFunc, ttl time.Duration) error

GetOrLoad 获取或加载(防击穿)

func (*MultiLevel) L1

func (m *MultiLevel) L1() Cache

L1 返回 L1 缓存

func (*MultiLevel) L2

func (m *MultiLevel) L2() Cache

L2 返回 L2 缓存

func (*MultiLevel) Set

func (m *MultiLevel) Set(ctx context.Context, key string, value any, ttl time.Duration) error

func (*MultiLevel) Stats

func (m *MultiLevel) Stats() Stats

type MultiLevelConfig

type MultiLevelConfig struct {
	L1 Cache
	L2 Cache
}

MultiLevelConfig 多级缓存配置

type Option

type Option func(*Options)

Option 缓存选项

func WithDefaultTTL

func WithDefaultTTL(ttl time.Duration) Option

WithDefaultTTL 设置默认 TTL

func WithNullTTL

func WithNullTTL(ttl time.Duration) Option

WithNullTTL 设置空值缓存时间

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix 设置键前缀

func WithSerializer

func WithSerializer(s Serializer) Option

WithSerializer 设置序列化器

func WithStats

func WithStats() Option

WithStats 启用统计

type Options

type Options struct {
	Prefix      string
	Serializer  Serializer
	DefaultTTL  time.Duration
	NullTTL     time.Duration // 空值缓存时间(防穿透)
	EnableStats bool
}

Options 缓存配置

type Redis

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

Redis Redis 缓存

func NewRedis

func NewRedis(cfg RedisConfig, opts ...Option) *Redis

NewRedis 创建 Redis 缓存

func NewRedisFromClient

func NewRedisFromClient(client *redis.Client, opts ...Option) *Redis

NewRedisFromClient 从已有客户端创建

func (*Redis) Client

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

Client 返回底层 Redis 客户端

func (*Redis) Close

func (r *Redis) Close() error

func (*Redis) Delete

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

func (*Redis) Exists

func (r *Redis) Exists(ctx context.Context, key string) (bool, error)

func (*Redis) Get

func (r *Redis) Get(ctx context.Context, key string, dest any) error

func (*Redis) MDelete

func (r *Redis) MDelete(ctx context.Context, keys []string) error

MDelete 批量删除

func (*Redis) MGet

func (r *Redis) MGet(ctx context.Context, keys []string) (map[string][]byte, error)

MGet 批量获取

func (*Redis) MSet

func (r *Redis) MSet(ctx context.Context, items map[string]any, ttl time.Duration) error

MSet 批量设置

func (*Redis) Set

func (r *Redis) Set(ctx context.Context, key string, value any, ttl time.Duration) error

type RedisConfig

type RedisConfig struct {
	Addr         string
	Password     string
	DB           int
	PoolSize     int
	MinIdleConns int
}

RedisConfig Redis 配置

type Serializer

type Serializer interface {
	Marshal(v any) ([]byte, error)
	Unmarshal(data []byte, v any) error
}

Serializer 序列化器接口

type Stats

type Stats struct {
	Hits    int64   `json:"hits"`
	Misses  int64   `json:"misses"`
	HitRate float64 `json:"hit_rate"`
	Keys    int64   `json:"keys"`
	Size    int64   `json:"size"`
}

Stats 缓存统计

type StatsProvider

type StatsProvider interface {
	Stats() Stats
}

StatsProvider 统计提供者

Jump to

Keyboard shortcuts

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