cache

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 5 Imported by: 0

README

cache — 多级缓存

提供统一的缓存接口(Cache),内置内存缓存与 Redis 缓存适配器,支持多种缓存策略(Write-Through、Write-Back、LRU/LFU 等)。

核心接口

type Cache interface {
    Get(ctx context.Context, key string) ([]byte, error)
    Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
    Delete(ctx context.Context, key string) error
    Exists(ctx context.Context, key string) (bool, error)
    Flush(ctx context.Context) error
}

快速开始

内存缓存
import "github.com/leeforge/framework/cache"

// 创建 LRU 内存缓存(容量 1000 条)
c := cache.NewMemoryCache(cache.MemoryConfig{
    MaxSize: 1000,
    Policy:  cache.LRU,
})

// 读写
c.Set(ctx, "user:123", data, 5*time.Minute)
val, err := c.Get(ctx, "user:123")
Redis 缓存
// 基于 redis_client 初始化
rc := cache.NewRedisCache(redisClient, cache.RedisConfig{
    KeyPrefix: "myapp:",
})
二级缓存(L1 内存 + L2 Redis)
twoLevel := cache.NewTwoLevelCache(
    cache.NewMemoryCache(...), // L1:本地内存,速度最快
    cache.NewRedisCache(...),  // L2:Redis,跨实例共享
    cache.TwoLevelConfig{
        L1TTL: 1 * time.Minute,
        L2TTL: 30 * time.Minute,
    },
)

缓存策略

策略 说明
WriteThrough 写时同时更新缓存和存储,强一致性
WriteBack 先写缓存,异步刷盘,高吞吐
WriteAround 绕过缓存直接写存储,适合一次写多次读
LRU 最近最少使用淘汰策略
LFU 最低使用频率淘汰策略
strategy := cache.NewWriteThroughStrategy(store, cacheInstance)
strategy.Write(ctx, "key", value)

适配器接口

BackendAdapter 用于统一不同缓存后端,可自定义实现:

type BackendAdapter interface {
    Get(ctx context.Context, key string) ([]byte, error)
    Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
    Delete(ctx context.Context, key string) error
}

注意事项

  • 在插件中通过 AppContext.Cache() 获取框架内置的缓存实例
  • 二级缓存的 L1 TTL 应小于 L2 TTL,防止数据不一致
  • Key 命名建议使用 {模块}:{类型}:{ID} 格式,如 user:profile:123

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewSimpleAdapter

func NewSimpleAdapter() rbac.CacheAdapter

NewSimpleAdapter 创建简单缓存适配器

Types

type CacheAdapter

type CacheAdapter interface {
	Get(key string) (interface{}, error)
	Set(key string, value interface{}, ttl time.Duration) error
	Delete(key string) error
	Exists(key string) bool
}

CacheAdapter 缓存适配器接口

type CacheAside

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

CacheAside 缓存旁路模式

func NewCacheAside

func NewCacheAside(cache *MultiLevelCache) *CacheAside

NewCacheAside 创建缓存旁路

func (*CacheAside) Read

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

Read 读取数据 (Cache-Aside)

func (*CacheAside) Write

func (c *CacheAside) Write(ctx context.Context, key string, value interface{}) error

Write 写入数据 (Cache-Aside)

type CacheConfig

type CacheConfig struct {
	TTL         map[string]time.Duration
	MaxSize     int
	Compression bool
	Prefix      string
}

CacheConfig 缓存配置

type CacheEvictionPolicy

type CacheEvictionPolicy interface {
	Evict(cache *MultiLevelCache) error
}

CacheEvictionPolicy 缓存淘汰策略接口

type CacheMetrics

type CacheMetrics struct {
	Hits   int64
	Misses int64
	Evicts int64
	Sets   int64
	Gets   int64
}

CacheMetrics 缓存指标

type CacheMonitor

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

CacheMonitor 缓存监控

func NewCacheMonitor

func NewCacheMonitor() *CacheMonitor

NewCacheMonitor 创建监控

func (*CacheMonitor) GetStats

func (m *CacheMonitor) GetStats() CacheStats

GetStats 获取统计

func (*CacheMonitor) RecordDelete

func (m *CacheMonitor) RecordDelete()

RecordDelete 记录删除

func (*CacheMonitor) RecordHit

func (m *CacheMonitor) RecordHit()

RecordHit 记录命中

func (*CacheMonitor) RecordMiss

func (m *CacheMonitor) RecordMiss()

RecordMiss 记录未命中

func (*CacheMonitor) RecordSet

func (m *CacheMonitor) RecordSet()

RecordSet 记录设置

func (*CacheMonitor) Reset

func (m *CacheMonitor) Reset()

Reset 重置统计

type CacheProtection

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

CacheProtection 缓存保护机制

func NewCacheProtection

func NewCacheProtection(cache *MultiLevelCache) *CacheProtection

NewCacheProtection 创建缓存保护

func (*CacheProtection) PreventCacheAvalanche

func (p *CacheProtection) PreventCacheAvalanche(keys []string, ttl time.Duration) error

PreventCacheAvalanche 防止缓存雪崩

func (*CacheProtection) PreventCacheBreakdown

func (p *CacheProtection) PreventCacheBreakdown(ctx context.Context, key string) (interface{}, error)

PreventCacheBreakdown 防止缓存击穿

func (*CacheProtection) PreventCachePenetration

func (p *CacheProtection) PreventCachePenetration(ctx context.Context, key string) (interface{}, error)

PreventCachePenetration 防止缓存穿透

type CacheStats

type CacheStats struct {
	TotalHits    int64
	TotalMisses  int64
	TotalSets    int64
	TotalDeletes int64
	CurrentSize  int
	HitRate      float64
}

CacheStats 缓存统计

type CacheStrategy

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

CacheStrategy 缓存策略

func NewCacheStrategy

func NewCacheStrategy(config CacheConfig) *CacheStrategy

NewCacheStrategy 创建缓存策略

func (*CacheStrategy) GetTTL

func (s *CacheStrategy) GetTTL(cacheType string) time.Duration

GetTTL 获取指定类型的 TTL

func (*CacheStrategy) Key

func (s *CacheStrategy) Key(prefix string, keys ...string) string

Key 生成缓存键

type CacheStrategyBuilder

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

CacheStrategyBuilder 缓存策略构建器

func NewCacheStrategyBuilder

func NewCacheStrategyBuilder() *CacheStrategyBuilder

NewCacheStrategyBuilder 创建构建器

func (*CacheStrategyBuilder) Build

func (b *CacheStrategyBuilder) Build() *CacheStrategy

Build 构建策略

func (*CacheStrategyBuilder) WithCompression

func (b *CacheStrategyBuilder) WithCompression(enabled bool) *CacheStrategyBuilder

WithCompression 启用压缩

func (*CacheStrategyBuilder) WithMaxSize

func (b *CacheStrategyBuilder) WithMaxSize(size int) *CacheStrategyBuilder

WithMaxSize 设置最大大小

func (*CacheStrategyBuilder) WithPrefix

func (b *CacheStrategyBuilder) WithPrefix(prefix string) *CacheStrategyBuilder

WithPrefix 设置前缀

func (*CacheStrategyBuilder) WithTTL

func (b *CacheStrategyBuilder) WithTTL(cacheType string, ttl time.Duration) *CacheStrategyBuilder

WithTTL 设置 TTL

type CacheWarmup

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

CacheWarmup 缓存预热

func NewCacheWarmup

func NewCacheWarmup(cache *MultiLevelCache, loader LoaderFunc) *CacheWarmup

NewCacheWarmup 创建缓存预热

func (*CacheWarmup) Warmup

func (w *CacheWarmup) Warmup(ctx context.Context, keys []string) error

Warmup 预热缓存

type Error

type Error struct {
	Message string
}

Error 缓存错误

func (*Error) Error

func (e *Error) Error() string

type LFUPolicy

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

LFUPolicy LFU 淘汰策略

func NewLFUPolicy

func NewLFUPolicy() *LFUPolicy

NewLFUPolicy 创建 LFU 策略

func (*LFUPolicy) Evict

func (p *LFUPolicy) Evict(cache *MultiLevelCache) error

Evict 淘汰

func (*LFUPolicy) RecordAccess

func (p *LFUPolicy) RecordAccess(key string)

RecordAccess 记录访问

type LRUPolicy

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

LRUPolicy LRU 淘汰策略

func NewLRUPolicy

func NewLRUPolicy() *LRUPolicy

NewLRUPolicy 创建 LRU 策略

func (*LRUPolicy) Evict

func (p *LRUPolicy) Evict(cache *MultiLevelCache) error

Evict 淘汰

func (*LRUPolicy) RecordAccess

func (p *LRUPolicy) RecordAccess(key string)

RecordAccess 记录访问

type LoaderFunc

type LoaderFunc func(ctx context.Context) (interface{}, error)

LoaderFunc 数据加载函数

type MetricsCollector

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

MetricsCollector 指标收集器

func NewMetricsCollector

func NewMetricsCollector() *MetricsCollector

NewMetricsCollector 创建指标收集器

func (*MetricsCollector) GetHitRate

func (c *MetricsCollector) GetHitRate(cacheType string) float64

GetHitRate 获取命中率

func (*MetricsCollector) GetMetrics

func (c *MetricsCollector) GetMetrics(cacheType string) *CacheMetrics

GetMetrics 获取指标

func (*MetricsCollector) RecordEvict

func (c *MetricsCollector) RecordEvict(cacheType string)

RecordEvict 记录驱逐

func (*MetricsCollector) RecordHit

func (c *MetricsCollector) RecordHit(cacheType string)

RecordHit 记录命中

func (*MetricsCollector) RecordMiss

func (c *MetricsCollector) RecordMiss(cacheType string)

RecordMiss 记录未命中

func (*MetricsCollector) RecordSet

func (c *MetricsCollector) RecordSet(cacheType string)

RecordSet 记录设置

type MultiLevelCache

type MultiLevelCache struct {
	L1 *sync.Map    // 本地内存
	L2 CacheAdapter // 二级缓存 (Redis 或其他)
	L3 LoaderFunc   // 三级缓存 (数据库加载器)
}

MultiLevelCache 多级缓存

func NewMultiLevelCache

func NewMultiLevelCache(l2 CacheAdapter, l3 LoaderFunc) *MultiLevelCache

NewMultiLevelCache 创建多级缓存

func (*MultiLevelCache) Clear

func (m *MultiLevelCache) Clear(ctx context.Context) error

Clear 清空缓存

func (*MultiLevelCache) Delete

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

Delete 删除缓存

func (*MultiLevelCache) Get

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

Get 获取缓存,支持自动加载

func (*MultiLevelCache) Set

func (m *MultiLevelCache) Set(ctx context.Context, key string, value interface{}) error

Set 设置缓存 (L1 + L2)

type SimpleAdapter

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

SimpleAdapter 简单的内存缓存适配器 实现 frame-core/auth/rbac.CacheAdapter 接口

func (*SimpleAdapter) Delete

func (c *SimpleAdapter) Delete(key string) error

Delete 删除缓存

func (*SimpleAdapter) Get

func (c *SimpleAdapter) Get(key string) (interface{}, error)

Get 获取缓存

func (*SimpleAdapter) Set

func (c *SimpleAdapter) Set(key string, value interface{}, ttl int64) error

Set 设置缓存 ttl: 过期时间(秒)

type StoreAdapter

type StoreAdapter interface {
	Save(ctx context.Context, key string, value interface{}) error
}

StoreAdapter 存储适配器

type TTLCache

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

TTLCache TTL 缓存

func NewTTLCache

func NewTTLCache(ttl time.Duration) *TTLCache

NewTTLCache 创建 TTL 缓存

func (*TTLCache) Cleanup

func (c *TTLCache) Cleanup()

Cleanup 清理过期项

func (*TTLCache) Get

func (c *TTLCache) Get(key string) (interface{}, error)

Get 获取带 TTL 检查

func (*TTLCache) Set

func (c *TTLCache) Set(key string, value interface{})

Set 设置带 TTL

type TTLItem

type TTLItem struct {
	Value      interface{}
	Expiration int64
}

TTLItem 带 TTL 的缓存项

type WriteBack

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

WriteBack 写回

func NewWriteBack

func NewWriteBack(cache *MultiLevelCache, store StoreAdapter, flushInterval time.Duration) *WriteBack

NewWriteBack 创建写回

func (*WriteBack) Write

func (w *WriteBack) Write(ctx context.Context, key string, value interface{}) error

Write 写入数据 (Write-Back)

type WriteThrough

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

WriteThrough 写穿透

func NewWriteThrough

func NewWriteThrough(cache *MultiLevelCache, store StoreAdapter) *WriteThrough

NewWriteThrough 创建写穿透

func (*WriteThrough) Write

func (w *WriteThrough) Write(ctx context.Context, key string, value interface{}) error

Write 写入数据 (Write-Through)

Jump to

Keyboard shortcuts

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