cache

package
v0.7.0 Latest Latest
Warning

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

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

README

cache 缓存系统

本模块是 goagent 框架的缓存系统,为 LLM 调用和工具执行提供缓存能力。

目录

架构设计

系统架构图
graph TB
    subgraph "应用层"
        LLMCache["LLM Cache Middleware"]
        ToolCache["Tool Cache"]
    end

    subgraph "缓存抽象层"
        CacheInterface["Cache Interface<br/>Get/Set/Delete/Clear/Has/GetStats"]
    end

    subgraph "缓存实现层"
        SimpleCache["SimpleCache<br/>sync.Map + TTL<br/>推荐使用"]
        NoOpCache["NoOpCache<br/>空实现"]
    end

    subgraph "工具层"
        KeyGen["CacheKeyGenerator<br/>SHA256 键生成"]
        Stats["CacheStats<br/>统计信息"]
    end

    LLMCache --> CacheInterface
    ToolCache --> CacheInterface
    CacheInterface --> SimpleCache
    CacheInterface --> NoOpCache
    SimpleCache --> KeyGen
    SimpleCache --> Stats

    style SimpleCache fill:#e8f5e9
    style CacheInterface fill:#e1f5ff
缓存访问流程
sequenceDiagram
    participant App as 应用
    participant Cache as Cache
    participant KeyGen as KeyGenerator
    participant Store as sync.Map

    App->>KeyGen: GenerateKey(prompt, params)
    KeyGen-->>App: SHA256 Key

    App->>Cache: Get(key)
    Cache->>Store: Load(key)
    alt 缓存命中
        Store-->>Cache: cacheEntry
        Cache->>Cache: 检查 TTL
        Cache-->>App: value (hits++)
    else 缓存未命中
        Store-->>Cache: nil
        Cache-->>App: ErrCacheMiss (misses++)
    end

    App->>Cache: Set(key, value, ttl)
    Cache->>Store: Store(key, entry)
    Store-->>Cache: 存储成功
    Cache-->>App: nil

核心组件

1. Cache 接口

统一的缓存接口定义:

type Cache interface {
    Get(ctx context.Context, key string) (interface{}, error)
    Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
    Delete(ctx context.Context, key string) error
    Clear(ctx context.Context) error
    Has(ctx context.Context, key string) (bool, error)
    GetStats() CacheStats
}
2. SimpleCache

推荐使用的缓存实现,基于 sync.Map + TTL

type SimpleCache struct {
    data   sync.Map
    ttl    time.Duration
    hits   atomic.Int64
    misses atomic.Int64
}
3. CacheKeyGenerator

基于 SHA256 的缓存键生成器:

type CacheKeyGenerator struct {
    prefix string
}
4. CacheStats

缓存统计信息:

type CacheStats struct {
    Hits      int64   // 命中次数
    Misses    int64   // 未命中次数
    Sets      int64   // 设置次数
    Deletes   int64   // 删除次数
    Evictions int64   // 驱逐次数
    Size      int64   // 当前大小
    MaxSize   int64   // 最大大小
    HitRate   float64 // 命中率
}

使用方法

基础缓存操作
// 创建缓存(推荐)
cache := cache.NewSimpleCache(5 * time.Minute)

// 设置缓存
err := cache.Set(ctx, "key", "value", 10*time.Minute)

// 获取缓存
value, err := cache.Get(ctx, "key")
if err == cache.ErrCacheMiss {
    // 缓存未命中
}

// 检查是否存在
exists, err := cache.Has(ctx, "key")

// 删除缓存
err := cache.Delete(ctx, "key")

// 清空所有缓存
err := cache.Clear(ctx)

// 获取统计信息
stats := cache.GetStats()
fmt.Printf("命中率: %.2f%%\n", stats.HitRate*100)

// 关闭缓存(停止后台清理)
cache.Close()
LLM 调用缓存
// 创建缓存
llmCache := cache.NewSimpleCache(5 * time.Minute)

// 创建键生成器
keyGen := cache.NewCacheKeyGenerator("llm")

// 生成缓存键
key := keyGen.GenerateKey(prompt, map[string]interface{}{
    "temperature": 0.7,
    "max_tokens":  100,
    "model":       "gpt-4",
})

// 检查缓存
if cached, err := llmCache.Get(ctx, key); err == nil {
    return cached.(*CompletionResponse), nil
}

// 调用 LLM
response, err := llmClient.Complete(ctx, request)
if err != nil {
    return nil, err
}

// 缓存结果
llmCache.Set(ctx, key, response, 5*time.Minute)
return response, nil
工具执行缓存
// 使用缓存中间件
cacheMW := middleware.NewCachingMiddleware(
    middleware.WithCache(cache.NewSimpleCache(10*time.Minute)),
    middleware.WithTTL(10*time.Minute),
)

// 包装工具
cachedTool := cacheMW.Wrap(originalTool)

// 执行(自动缓存)
result, err := cachedTool.Invoke(ctx, input)
键生成
// 创建键生成器
gen := cache.NewCacheKeyGenerator("llm")

// 复杂键生成(基于 prompt + 参数)
key := gen.GenerateKey("hello world", map[string]interface{}{
    "temp":       0.7,
    "max_tokens": 100,
})
// 输出: llm:sha256:abc123...

// 简单键生成
key := gen.GenerateKeySimple("model", "gpt4", "system")
// 输出: llm:model:gpt4:system
禁用缓存
// 使用空缓存实现
cache := cache.NewNoOpCache()

// 所有操作都是空操作
cache.Set(ctx, "key", "value", time.Hour) // 不存储
value, err := cache.Get(ctx, "key")        // 总是返回 ErrCacheMiss
基于配置创建
// 默认配置
config := cache.DefaultCacheConfig()

// 自定义配置
config := &cache.CacheConfig{
    Enabled:         true,
    Type:            "simple",
    MaxSize:         10000,
    DefaultTTL:      5 * time.Minute,
    CleanupInterval: time.Minute,
}

// 从配置创建
c := cache.NewCacheFromConfig(config)

API 参考

工厂函数
// 创建简化缓存(推荐)
NewSimpleCache(ttl time.Duration) *SimpleCache

// 创建空缓存
NewNoOpCache() *NoOpCache

// 从配置创建
NewCacheFromConfig(config *CacheConfig) Cache

// 默认配置
DefaultCacheConfig() *CacheConfig
Cache 接口
Get(ctx context.Context, key string) (interface{}, error)
Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
Delete(ctx context.Context, key string) error
Clear(ctx context.Context) error
Has(ctx context.Context, key string) (bool, error)
GetStats() CacheStats
CacheKeyGenerator
// 创建键生成器
NewCacheKeyGenerator(prefix string) *CacheKeyGenerator

// 生成复杂键
GenerateKey(prompt string, params map[string]interface{}) string

// 生成简单键
GenerateKeySimple(parts ...string) string
错误类型
var (
    ErrCacheMiss     = errors.New("cache miss")
    ErrCacheInvalid  = errors.New("invalid cache entry")
    ErrCacheDisabled = errors.New("cache is disabled")
)

代码结构

cache/
├── base.go             # 核心接口和配置
├── simple_cache.go     # SimpleCache 实现
├── cache_test.go       # 测试
└── simple_cache_test.go

设计特点

SimpleCache 优势
  • 高性能:使用 sync.Map 无锁读取
  • 简洁可维护:核心代码仅 ~180 行
  • 自动清理:后台定时清理过期条目
  • 生命周期管理:支持优雅关闭
自动清理机制
// 后台清理线程
// 每 ttl/2 间隔运行一次清理
// 遍历并删除所有过期条目
func (c *SimpleCache) cleanupExpired() {
    now := time.Now()
    c.data.Range(func(key, value interface{}) bool {
        entry := value.(*cacheEntry)
        if now.After(entry.expiresAt) {
            c.data.Delete(key)
        }
        return true
    })
}

扩展阅读

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCacheMiss     = errors.New("cache miss")
	ErrCacheInvalid  = errors.New("invalid cache entry")
	ErrCacheDisabled = errors.New("cache is disabled")
)

Functions

This section is empty.

Types

type Cache

type Cache interface {
	// Get 获取缓存值
	Get(ctx context.Context, key string) (interface{}, error)

	// Set 设置缓存值
	Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

	// Delete 删除缓存值
	Delete(ctx context.Context, key string) error

	// Clear 清空所有缓存
	Clear(ctx context.Context) error

	// Has 检查键是否存在
	Has(ctx context.Context, key string) (bool, error)

	// GetStats 获取缓存统计信息
	GetStats() CacheStats
}

Cache 定义缓存接口

借鉴 LangChain 的缓存设计,用于缓存 LLM 调用结果 减少 API 调用次数,降低成本和延迟

func NewCacheFromConfig

func NewCacheFromConfig(config CacheConfig) Cache

NewCacheFromConfig 根据配置创建缓存

已简化为使用 SimpleCache,删除过度设计的 LRU/MultiTier 等实现

type CacheConfig

type CacheConfig struct {
	Enabled         bool          // 是否启用缓存
	Type            string        // 缓存类型: "memory", "redis", "multi-tier"
	MaxSize         int           // 最大条目数
	DefaultTTL      time.Duration // 默认 TTL
	CleanupInterval time.Duration // 清理间隔
}

CacheConfig 缓存配置

func DefaultCacheConfig

func DefaultCacheConfig() CacheConfig

DefaultCacheConfig 返回默认配置

type CacheEntry

type CacheEntry struct {
	Key         string      // 键
	Value       interface{} // 值
	CreateTime  time.Time   // 创建时间
	ExpireTime  time.Time   // 过期时间
	AccessTime  time.Time   // 最后访问时间
	AccessCount int64       // 访问次数
}

CacheEntry 缓存条目

func (*CacheEntry) IsExpired

func (e *CacheEntry) IsExpired() bool

IsExpired 检查是否过期

type CacheKeyGenerator

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

CacheKeyGenerator 缓存键生成器

func NewCacheKeyGenerator

func NewCacheKeyGenerator(prefix string) *CacheKeyGenerator

NewCacheKeyGenerator 创建键生成器

func (*CacheKeyGenerator) GenerateKey

func (g *CacheKeyGenerator) GenerateKey(prompt string, params map[string]interface{}) string

GenerateKey 生成缓存键

根据提示和参数生成唯一的缓存键

func (*CacheKeyGenerator) GenerateKeySimple

func (g *CacheKeyGenerator) GenerateKeySimple(parts ...string) string

GenerateKeySimple 生成简单的缓存键

Optimized to use strings.Builder for efficient string concatenation and avoid multiple allocations in the loop.

type CacheStats

type CacheStats struct {
	Hits      int64   // 命中次数
	Misses    int64   // 未命中次数
	Sets      int64   // 设置次数
	Deletes   int64   // 删除次数
	Evictions int64   // 驱逐次数
	Size      int64   // 当前大小
	MaxSize   int64   // 最大大小
	HitRate   float64 // 命中率
}

CacheStats 缓存统计信息

type InMemoryCache

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

InMemoryCache 内存缓存实现

使用 sync.RWMutex + map 提供线程安全的内存缓存

func NewInMemoryCache deprecated

func NewInMemoryCache(maxSize int, defaultTTL, cleanupInterval time.Duration) *InMemoryCache

NewInMemoryCache 创建内存缓存

Deprecated: 使用 NewSimpleCache 代替。此函数将在未来版本中移除。 InMemoryCache 实现过于复杂,包含不必要的特性。建议使用更简化的 SimpleCache。

func (*InMemoryCache) Clear

func (c *InMemoryCache) Clear(ctx context.Context) error

Clear 清空所有缓存

func (*InMemoryCache) Close

func (c *InMemoryCache) Close()

Close 关闭缓存

func (*InMemoryCache) Delete

func (c *InMemoryCache) Delete(ctx context.Context, key string) error

Delete 删除缓存值

func (*InMemoryCache) Get

func (c *InMemoryCache) Get(ctx context.Context, key string) (interface{}, error)

Get 获取缓存值

func (*InMemoryCache) GetStats

func (c *InMemoryCache) GetStats() CacheStats

GetStats 获取统计信息

func (*InMemoryCache) Has

func (c *InMemoryCache) Has(ctx context.Context, key string) (bool, error)

Has 检查键是否存在

func (*InMemoryCache) Set

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

Set 设置缓存值

type LRUCache

type LRUCache struct {
	*InMemoryCache
}

LRUCache LRU (Least Recently Used) 缓存

当缓存满时,驱逐最近最少使用的条目

func NewLRUCache deprecated

func NewLRUCache(maxSize int, defaultTTL, cleanupInterval time.Duration) *LRUCache

NewLRUCache 创建 LRU 缓存

Deprecated: 使用 NewSimpleCache 代替。此函数将在未来版本中移除。 LRU驱逐逻辑在实际场景中很少使用,SimpleCache 基于 TTL 的方式更简单有效。

type MultiTierCache

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

MultiTierCache 多级缓存

支持多个缓存层,如 L1 内存 + L2 Redis

func NewMultiTierCache deprecated

func NewMultiTierCache(tiers ...Cache) *MultiTierCache

NewMultiTierCache 创建多级缓存

Deprecated: 使用 NewSimpleCache 代替。此函数将在未来版本中移除。 多级缓存在单进程应用中过于复杂,实际使用场景有限。

func (*MultiTierCache) Clear

func (c *MultiTierCache) Clear(ctx context.Context) error

Clear 清空所有层级

func (*MultiTierCache) Delete

func (c *MultiTierCache) Delete(ctx context.Context, key string) error

Delete 从所有层级删除

func (*MultiTierCache) Get

func (c *MultiTierCache) Get(ctx context.Context, key string) (interface{}, error)

Get 从各级缓存获取

func (*MultiTierCache) GetStats

func (c *MultiTierCache) GetStats() CacheStats

GetStats 获取第一层的统计信息

func (*MultiTierCache) Has

func (c *MultiTierCache) Has(ctx context.Context, key string) (bool, error)

Has 检查键是否存在于任何层级

func (*MultiTierCache) Set

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

Set 设置到所有层级

type NoOpCache

type NoOpCache struct{}

NoOpCache 无操作缓存

用于禁用缓存的场景

func NewNoOpCache

func NewNoOpCache() *NoOpCache

NewNoOpCache 创建无操作缓存

func (*NoOpCache) Clear

func (c *NoOpCache) Clear(ctx context.Context) error

func (*NoOpCache) Delete

func (c *NoOpCache) Delete(ctx context.Context, key string) error

func (*NoOpCache) Get

func (c *NoOpCache) Get(ctx context.Context, key string) (interface{}, error)

func (*NoOpCache) GetStats

func (c *NoOpCache) GetStats() CacheStats

func (*NoOpCache) Has

func (c *NoOpCache) Has(ctx context.Context, key string) (bool, error)

func (*NoOpCache) Set

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

type SimpleCache added in v0.5.0

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

SimpleCache 简化的缓存实现

使用 sync.Map + TTL 提供线程安全的缓存,删除所有过度设计的特性: - 删除 LRU (实际场景不需要) - 删除多层缓存 (单进程应用不需要) - 删除分片 (sync.Map内部已优化) - 删除自动调优 (过度设计) - 删除依赖管理 (过度复杂)

func NewSimpleCache added in v0.5.0

func NewSimpleCache(ttl time.Duration) *SimpleCache

NewSimpleCache 创建简化缓存

func (*SimpleCache) Clear added in v0.5.0

func (c *SimpleCache) Clear(ctx context.Context) error

Clear 清空所有缓存

func (*SimpleCache) Close added in v0.5.0

func (c *SimpleCache) Close()

Close 关闭缓存

func (*SimpleCache) Delete added in v0.5.0

func (c *SimpleCache) Delete(ctx context.Context, key string) error

Delete 删除缓存值

func (*SimpleCache) Get added in v0.5.0

func (c *SimpleCache) Get(ctx context.Context, key string) (interface{}, error)

Get 获取缓存值

func (*SimpleCache) GetStats added in v0.5.0

func (c *SimpleCache) GetStats() CacheStats

GetStats 获取统计信息

func (*SimpleCache) Has added in v0.5.0

func (c *SimpleCache) Has(ctx context.Context, key string) (bool, error)

Has 检查键是否存在

func (*SimpleCache) Set added in v0.5.0

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

Set 设置缓存值

Jump to

Keyboard shortcuts

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