cache

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2026 License: MIT Imports: 12 Imported by: 0

README

cache - 缓存组件

Go Reference

统一的缓存抽象层,支持 Redis 和 Memory 两种驱动。

特性

特性 Redis 驱动 Memory 驱动
Key-Value
Hash
Sorted Set
List
MSet/MGet

快速开始

Redis 驱动
redisConn, _ := connector.NewRedis(&cfg.Redis, connector.WithLogger(logger))
defer redisConn.Close()

cache, _ := cache.New(&cache.Config{
    Prefix:     "myapp:",
    Serializer: "json",
}, cache.WithRedisConnector(redisConn), cache.WithLogger(logger))

cache.Set(ctx, "user:1001", user, time.Hour)
cache.Get(ctx, "user:1001", &cachedUser)
Memory 驱动
cache, _ := cache.New(&cache.Config{
    Driver:     cache.DriverMemory,
    Standalone: &cache.StandaloneConfig{Capacity: 10000},
})

cache.Set(ctx, "key", "value", time.Minute)

核心 API

type Cache interface {
    // Key-Value
    Set(ctx, key, value, ttl) error
    Get(ctx, key, dest) error
    Delete(ctx, key) error
    Has(ctx, key) (bool, error)
    Expire(ctx, key, ttl) error

    // Hash (仅 Redis)
    HSet/HGet/HGetAll/HDel/HIncrBy(ctx, key, ...) error

    // Sorted Set (仅 Redis)
    ZAdd/ZRem/ZScore/ZRange/ZRevRange/ZRangeByScore(ctx, key, ...) error

    // List (仅 Redis)
    LPush/RPush/LPop/RPop/LRange/LPushCapped(ctx, key, ...) error

    // Batch (仅 Redis)
    MGet(ctx, keys, dest) error
    MSet(ctx, items, ttl) error

    Close() error
}

配置

type Config struct {
    Driver     DriverType        // redis | memory
    Prefix     string            // Key 前缀
    Serializer string            // json | msgpack
    Standalone *StandaloneConfig // memory 驱动配置
}

type StandaloneConfig struct {
    Capacity int // 最大条目数,默认 10000
}

测试

# 单元测试(无外部依赖)
go test -v ./cache -run Unit

# 集成测试(需要 Docker)
go test -v ./cache -run Integration

示例

参考 examples/cache/main.go

Documentation

Overview

Package cache 提供缓存组件,支持基于 Redis 的多种数据结构操作。

Cache 组件是 Genesis 微服务组件库的缓存抽象层,提供了统一的缓存操作语义。 支持 Redis 的核心数据结构:String、Hash、Sorted Set、List,并支持自动序列化。

基本使用:

redisConn, _ := connector.NewRedis(redisConfig)
cacheClient, _ := cache.New(&cache.Config{
    Driver:     cache.DriverRedis,
    Prefix:     "myapp:",
    Serializer: "json",
}, cache.WithRedisConnector(redisConn), cache.WithLogger(logger))

// 缓存对象
err := cacheClient.Set(ctx, "user:1001", user, time.Hour)

// 获取对象
var cachedUser User
err = cacheClient.Get(ctx, "user:1001", &cachedUser)

// Hash 操作
err = cacheClient.HSet(ctx, "user:1001:profile", "name", "Alice")
err = cacheClient.HGet(ctx, "user:1001:profile", "name", &name)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache interface {
	// --- Key-Value ---
	Set(ctx context.Context, key string, value any, ttl time.Duration) error
	Get(ctx context.Context, key string, dest any) error
	Delete(ctx context.Context, key string) error
	Has(ctx context.Context, key string) (bool, error)
	Expire(ctx context.Context, key string, ttl time.Duration) error

	// --- Hash(Distributed Only) ---
	HSet(ctx context.Context, key string, field string, value any) error
	HGet(ctx context.Context, key string, field string, dest any) error
	HGetAll(ctx context.Context, key string, destMap any) error
	HDel(ctx context.Context, key string, fields ...string) error
	HIncrBy(ctx context.Context, key string, field string, increment int64) (int64, error)

	// --- Sorted Set(Distributed Only) ---
	ZAdd(ctx context.Context, key string, score float64, member any) error
	ZRem(ctx context.Context, key string, members ...any) error
	ZScore(ctx context.Context, key string, member any) (float64, error)
	ZRange(ctx context.Context, key string, start, stop int64, destSlice any) error
	ZRevRange(ctx context.Context, key string, start, stop int64, destSlice any) error
	ZRangeByScore(ctx context.Context, key string, min, max float64, destSlice any) error

	// --- List(Distributed Only) ---
	LPush(ctx context.Context, key string, values ...any) error
	RPush(ctx context.Context, key string, values ...any) error
	LPop(ctx context.Context, key string, dest any) error
	RPop(ctx context.Context, key string, dest any) error
	LRange(ctx context.Context, key string, start, stop int64, destSlice any) error
	LPushCapped(ctx context.Context, key string, limit int64, values ...any) error

	// --- Batch Operations ---
	// MGet 批量获取多个 key 的值,destSlice 必须是指向切片的指针
	// 返回的切片顺序与 keys 顺序一致,不存在的 key 对应位置为零值
	MGet(ctx context.Context, keys []string, destSlice any) error
	// MSet 批量设置多个 key-value 对
	MSet(ctx context.Context, items map[string]any, ttl time.Duration) error

	// --- Advanced ---
	// Client 返回底层 Redis 客户端,用于执行 Pipeline、Lua 脚本等高级操作
	// Memory 驱动返回 nil
	Client() any

	// --- Utility ---
	Close() error
}

Cache 定义了缓存组件的核心能力

func New

func New(cfg *Config, opts ...Option) (Cache, error)

New 根据配置创建缓存实例(配置驱动)

通过 cfg.Driver 选择后端,连接器通过 Option 注入:

  • DriverRedis: WithRedisConnector
  • DriverMemory: 无需连接器

type Config

type Config struct {
	// Driver 缓存驱动: "redis" | "memory" (默认 "redis")
	Driver DriverType `json:"driver" yaml:"driver"`

	// Prefix: 全局 Key 前缀 (e.g., "app:v1:")
	Prefix string `json:"prefix" yaml:"prefix"`

	// Serializer: "json" | "msgpack"
	Serializer string `json:"serializer" yaml:"serializer"`

	// Standalone 单机缓存配置
	Standalone *StandaloneConfig `json:"standalone" yaml:"standalone"`
}

Config 缓存组件统一配置

type DriverType

type DriverType string

DriverType 缓存驱动类型

const (
	DriverRedis  DriverType = "redis"
	DriverMemory DriverType = "memory"
)

type Option

type Option func(*options)

Option 缓存组件选项函数

func WithLogger

func WithLogger(l clog.Logger) Option

WithLogger 注入日志记录器 组件内部会自动追加 Namespace: logger.WithNamespace("cache")

func WithMeter

func WithMeter(m metrics.Meter) Option

WithMeter 注入指标 Meter(默认使用 metrics.Discard)

func WithRedisConnector

func WithRedisConnector(conn connector.RedisConnector) Option

WithRedisConnector 注入 Redis 连接器 (仅用于分布式模式)

type StandaloneConfig

type StandaloneConfig struct {
	// Capacity 缓存最大容量(条目数,默认:10000)
	Capacity int `json:"capacity" yaml:"capacity"`
}

StandaloneConfig 单机缓存配置

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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