cache

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package cache 提供高性能的多级缓存系统,支持本地缓存、远程缓存和二级缓存架构,内置多种缓存保护机制。

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrKeyNotFound           = errors.New("cache: key not found")
	ErrCacheClosed           = errors.New("cache: cache is closed")
	ErrSerializationFailed   = errors.New("cache: serialization failed")
	ErrDeserializationFailed = errors.New("cache: deserialization failed")
)

Functions

func GetCached

func GetCached[R any](
	cacheOption *CacheOption,
	loader func(context.Context) (R, error),
	fallback ...func() (R, error),
) (R, error)

GetCached 通用缓存获取函数

func OptionPoolPut

func OptionPoolPut(co *CacheOption)

OptionPoolPut 将使用完的CacheOption放回选项池

Types

type Cache

type Cache interface {
	Get(ctx context.Context, key string, co *CacheOption) (string, error)
	Set(ctx context.Context, key string, value interface{}, co *CacheOption) error
	Delete(ctx context.Context, keys ...string) error
	Close() error
	Wait() error
	GetLevel() Level
}

Cache 缓存接口,定义了通用接口的方法 定义Get、Set、Del、Wait、Close等

type CacheBloomFilter

type CacheBloomFilter interface {
	// Add 添加Key到布隆过滤器
	Add(key []byte)
	// Test 测试Key是否存在于布隆过滤器中,可能存在误判
	Test(key []byte) bool
	// TestAndAdd 测试Key是否存在于布隆过滤器中,若不存在则添加Key,返回true表示Key可能存在,false表示Key一定不存在
	TestAndAdd(key []byte) bool
	// Reset 如有需要,重置布隆过滤器
	Reset()
}

CacheBloomFilter 布隆过滤器接口

func NewShardedBloomFilter

func NewShardedBloomFilter(shardCount int, estPerShard uint, fpRate float64) CacheBloomFilter

type CacheCircuitBreaker

type CacheCircuitBreaker interface {
	// Call 受保护的方法调用
	Call(fn func() (string, error)) (interface{}, error)
	// ConvertCircuitBreakerOpenError 将熔断错误识别和转换为"熔断器打开时错误",见 cache.ErrCircuitBreakerOpen
	ConvertCircuitBreakerOpenError(err error) error
	// Allow 如有需要,作为允许条件打开熔断器,返回true,否则返回false
	Allow() bool
	// Reset 如有需要,重置熔断器的状态
	Reset()
}

CacheCircuitBreaker 熔断器接口

type CacheError

type CacheError struct {
	Op  string
	Key string
	Err error
}

CacheError 包含缓存操作失败的详细信息

func NewCacheError

func NewCacheError(op, key string, err error) *CacheError

func (*CacheError) Error

func (e *CacheError) Error() string

func (*CacheError) Unwrap

func (e *CacheError) Unwrap() error

type CacheLocator

type CacheLocator interface {
	fiberhouse.Locator
	GetRemote() Cache
	GetLocal() Cache
	GetLevel2() Cache
	SetOrigin(locator fiberhouse.Locator) fiberhouse.Locator
	GetOrigin() fiberhouse.Locator
}

CacheLocator 缓存定位器接口,继承自Locator接口

type CacheOption

type CacheOption struct {
	// 全局上下文
	AppCtx fiberhouse.IContext
	// contains filtered or unexported fields
}

CacheOption 缓存配置选项

func NewCacheOption

func NewCacheOption(appCtx fiberhouse.IContext) *CacheOption

NewCacheOption 创建默认的CacheOption实例

func OptionPoolGet

func OptionPoolGet(ctx fiberhouse.IContext) *CacheOption

OptionPoolGet 从选项池获取缓存选项

func (*CacheOption) Clone

func (c *CacheOption) Clone(ctx ...context.Context) *CacheOption

Clone 克隆CacheOption实例,可以传入新的context.Context

func (*CacheOption) DisableCache

func (c *CacheOption) DisableCache() *CacheOption

DisableCache 关闭缓存

func (*CacheOption) EnableBloomFilter

func (c *CacheOption) EnableBloomFilter() *CacheOption

EnableBloomFilter 启动布隆过滤器保护

func (*CacheOption) EnableCache

func (c *CacheOption) EnableCache() *CacheOption

EnableCache 开启缓存

func (*CacheOption) EnableCircuitBreaker

func (c *CacheOption) EnableCircuitBreaker() *CacheOption

EnableCircuitBreaker 启动断路器保护

func (*CacheOption) EnableProtectionAll

func (c *CacheOption) EnableProtectionAll() *CacheOption

EnableProtectionAll 启动所有保护措施

func (*CacheOption) EnableSingleFlight

func (c *CacheOption) EnableSingleFlight() *CacheOption

EnableSingleFlight 启动单飞保护

func (*CacheOption) GetBloomFilterState

func (c *CacheOption) GetBloomFilterState() bool

GetBloomFilterState 获取布隆过滤器保护启动状态

func (*CacheOption) GetCacheKey

func (c *CacheOption) GetCacheKey() string

GetCacheKey 获取缓存key值

func (*CacheOption) GetCacheLevel

func (c *CacheOption) GetCacheLevel() Level

GetCacheLevel 获取缓存级别

func (*CacheOption) GetCircuitBreakerState

func (c *CacheOption) GetCircuitBreakerState() bool

GetCircuitBreakerState 获取断路器保护启动状态

func (*CacheOption) GetContext

func (c *CacheOption) GetContext() fiberhouse.IContext

GetContext 获取全局上下文对象

func (*CacheOption) GetContextCtx

func (c *CacheOption) GetContextCtx() context.Context

GetContextCtx 获取上下文对象

func (*CacheOption) GetDefaultInstanceKey

func (c *CacheOption) GetDefaultInstanceKey() globalmanager.KeyName

GetDefaultInstanceKey 获取默认的缓存实例key值

func (*CacheOption) GetJsonWrapper

func (c *CacheOption) GetJsonWrapper() fiberhouse.JsonWrapper

GetJsonWrapper 获取json编解码器,默认获取GetDefaultTrafficCodecKey编解码器

func (*CacheOption) GetLocalBaseTTL

func (c *CacheOption) GetLocalBaseTTL() time.Duration

GetLocalBaseTTL 获取本地缓存基础TTL(不含随机)

func (*CacheOption) GetLocalTTL

func (c *CacheOption) GetLocalTTL() time.Duration

GetLocalTTL 获取计算后的本地缓存有效期

func (*CacheOption) GetRemoteBaseTTL

func (c *CacheOption) GetRemoteBaseTTL() time.Duration

GetRemoteBaseTTL 获取远程缓存存基础TTL(不含随机)

func (*CacheOption) GetRemoteTTL

func (c *CacheOption) GetRemoteTTL() time.Duration

GetRemoteTTL 获取远程缓存TTL(如果启用随机,返回随机值)

func (*CacheOption) GetSingleFlightState

func (c *CacheOption) GetSingleFlightState() bool

GetSingleFlightState 获取单飞保护启动状态

func (*CacheOption) GetSyncStrategy

func (c *CacheOption) GetSyncStrategy() Strategy

GetSyncStrategy 获取同步策略

func (*CacheOption) GetTTLInfo

func (c *CacheOption) GetTTLInfo() map[string]interface{}

GetTTLInfo 获取TTL配置信息(用于调试)

func (*CacheOption) IsCache

func (c *CacheOption) IsCache() bool

IsCache 判断是否开启缓存

func (*CacheOption) IsLocalTTLRandom

func (c *CacheOption) IsLocalTTLRandom() bool

IsLocalTTLRandom 检查本地缓存是否启用随机TTL

func (*CacheOption) IsRemoteTTLRandom

func (c *CacheOption) IsRemoteTTLRandom() bool

IsRemoteTTLRandom 检查远程缓存是否启用随机TTL

func (*CacheOption) Level2

func (c *CacheOption) Level2() *CacheOption

Level2 设置为二级缓存级别

func (*CacheOption) Local

func (c *CacheOption) Local() *CacheOption

Local 设置为本地缓存级别

func (*CacheOption) Release

func (c *CacheOption) Release()

Release 释放CacheOption实例到选项池

func (*CacheOption) Remote

func (c *CacheOption) Remote() *CacheOption

Remote 设置为远程缓存级别

func (*CacheOption) Reset

func (c *CacheOption) Reset() *CacheOption

Reset 重置CacheOption实例属性,保留AppCtx

func (*CacheOption) SetCacheKey

func (c *CacheOption) SetCacheKey(key string) *CacheOption

SetCacheKey 设置缓存key的值

func (*CacheOption) SetCacheLevel

func (c *CacheOption) SetCacheLevel(st Level) *CacheOption

SetCacheLevel 设置缓存级别

func (*CacheOption) SetContextCtx

func (c *CacheOption) SetContextCtx(ctx context.Context) *CacheOption

SetContextCtx 设置上下文对象

func (*CacheOption) SetDefaultInstanceKey

func (c *CacheOption) SetDefaultInstanceKey(key string) *CacheOption

SetDefaultInstanceKey 设置默认的缓存实例的key,用于从全局管理器获取默认缓存实例

func (*CacheOption) SetJsonWrapper

func (c *CacheOption) SetJsonWrapper(jpr fiberhouse.JsonWrapper) *CacheOption

SetJsonWrapper 设置json编解码器

func (*CacheOption) SetLocalTTL

func (c *CacheOption) SetLocalTTL(ttl time.Duration) *CacheOption

SetLocalTTL 设置本地缓存有效期

func (*CacheOption) SetLocalTTLRandomPercent

func (c *CacheOption) SetLocalTTLRandomPercent(baseTTL time.Duration, percent float64) *CacheOption

SetLocalTTLRandomPercent 设置按百分比随机的本地缓存TTL baseTTL: 基础过期时间 percent: 随机百分比(0.0-1.0)

func (*CacheOption) SetLocalTTLWithRandom

func (c *CacheOption) SetLocalTTLWithRandom(baseTTL, randomRange time.Duration) *CacheOption

SetLocalTTLWithRandom 设置带随机范围的本地缓存TTL baseTTL: 基础过期时间 randomRange: 随机范围(±randomRange)

func (*CacheOption) SetRemoteTTL

func (c *CacheOption) SetRemoteTTL(ttl time.Duration) *CacheOption

SetRemoteTTL 设置固定的远程缓存TTL

func (*CacheOption) SetRemoteTTLRandomPercent

func (c *CacheOption) SetRemoteTTLRandomPercent(baseTTL time.Duration, percent float64) *CacheOption

SetRemoteTTLRandomPercent 设置按百分比随机的远程缓存TTL

func (*CacheOption) SetRemoteTTLWithRandom

func (c *CacheOption) SetRemoteTTLWithRandom(baseTTL, randomRange time.Duration) *CacheOption

SetRemoteTTLWithRandom 设置带随机范围的远程缓存TTL

func (*CacheOption) SetSyncStrategy

func (c *CacheOption) SetSyncStrategy(sst Strategy) *CacheOption

SetSyncStrategy 设置同步策略

func (*CacheOption) SetSyncStrategyAsyncWriteBoth

func (c *CacheOption) SetSyncStrategyAsyncWriteBoth() *CacheOption

SetSyncStrategyAsyncWriteBoth 同步策略: 异步双写2级缓存

func (*CacheOption) SetSyncStrategyAsyncWriteRemoteOnly

func (c *CacheOption) SetSyncStrategyAsyncWriteRemoteOnly() *CacheOption

SetSyncStrategyAsyncWriteRemoteOnly 同步策略: 异步写远程缓存

func (*CacheOption) SetSyncStrategyWriteBoth

func (c *CacheOption) SetSyncStrategyWriteBoth() *CacheOption

SetSyncStrategyWriteBoth 同步策略: 同步双写2级缓存

func (*CacheOption) SetSyncStrategyWriteRemoteOnly

func (c *CacheOption) SetSyncStrategyWriteRemoteOnly() *CacheOption

SetSyncStrategyWriteRemoteOnly 同步策略: 同步写远程缓存

func (*CacheOption) Valid

func (c *CacheOption) Valid() error

Valid 验证缓存选项是否有效

type CircuitBreakerWrap

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

CircuitBreakerWrap gobreaker熔断器封装

func NewCircuitBreakerWrap

func NewCircuitBreakerWrap(name string, st ...*gobreaker.Settings) *CircuitBreakerWrap

func (*CircuitBreakerWrap) Allow

func (cbw *CircuitBreakerWrap) Allow() bool

func (*CircuitBreakerWrap) Call

func (cbw *CircuitBreakerWrap) Call(fn func() (string, error)) (interface{}, error)

func (*CircuitBreakerWrap) ConvertCircuitBreakerOpenError

func (cbw *CircuitBreakerWrap) ConvertCircuitBreakerOpenError(err error) error

ConvertCircuitBreakerOpenError 转换熔断器打开错误为自定义错误类型

func (*CircuitBreakerWrap) Reset

func (cbw *CircuitBreakerWrap) Reset()

type ErrCircuitBreakerOpen

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

ErrCircuitBreakerOpen 预定义熔断器打开时的特殊的错误

func NewErrCircuitBreakerOpen

func NewErrCircuitBreakerOpen(text string) ErrCircuitBreakerOpen

func (ErrCircuitBreakerOpen) Error

func (e ErrCircuitBreakerOpen) Error() string

type ErrRedisNil

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

ErrRedisNil 预定义明确Redis key 不存在的错误

func NewErrRedisNil

func NewErrRedisNil(key string) ErrRedisNil

func (ErrRedisNil) Error

func (e ErrRedisNil) Error() string

type ErrRejectedByBloomFilter

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

ErrRejectedByBloomFilter 预定义缓存穿透、雪崩时特殊的错误

func NewErrRejectedByBloomFilter

func NewErrRejectedByBloomFilter(key string) ErrRejectedByBloomFilter

func (ErrRejectedByBloomFilter) Error

func (e ErrRejectedByBloomFilter) Error() string

type Factory

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

Factory 缓存工厂,根据缓存级别返回相应的缓存实例

func NewFactory

func NewFactory(ctx fiberhouse.IContext) *Factory

NewFactory 创建缓存工厂

func (*Factory) GetCache

func (cf *Factory) GetCache(l Level) Cache

GetCache 根据缓存级别获取相应的缓存实例

type IRedisClient

type IRedisClient interface {
	GetRedisClient() *redis.Client
}

IRedisClient Redis客户端接口,定义获取Redis客户端的方法

type Level

type Level int8

Level 缓存级别

const (
	Local Level = iota + 1 // 从1开始,避免零值问题
	Remote
	Level2
)

缓存级别

type ShardedBloomFilter

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

ShardedBloomFilter 分片锁布隆过滤器

func (*ShardedBloomFilter) Add

func (sb *ShardedBloomFilter) Add(key []byte)

func (*ShardedBloomFilter) Reset

func (sb *ShardedBloomFilter) Reset()

func (*ShardedBloomFilter) Test

func (sb *ShardedBloomFilter) Test(key []byte) bool

func (*ShardedBloomFilter) TestAndAdd

func (sb *ShardedBloomFilter) TestAndAdd(key []byte) bool

type StableBloomFilter

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

StableBloomFilter 支持陈旧信息驱逐的稳定布隆过滤器 稳定的布隆过滤器 适合缓存场景,能够自动清理陈旧的key信息,同时保持较低的误报率和稳定的内存消耗 热点数据会被频繁添加,不易被驱逐 冷数据计数器逐渐减少,最终被清理 内存占用保持稳定,适合长期运行

func NewStableBloomFilter

func NewStableBloomFilter(capacity uint32, errorRate float64, evictRate float64) *StableBloomFilter

NewStableBloomFilter 创建稳定布隆过滤器 capacity: 预期容量 errorRate: 期望误报率 evictRate: 驱逐率,控制旧元素被移除的速度

func (*StableBloomFilter) Add

func (sbf *StableBloomFilter) Add(key string)

Add 添加元素到过滤器

func (*StableBloomFilter) GetStats

func (sbf *StableBloomFilter) GetStats() StableBloomStats

GetStats 获取统计信息

func (*StableBloomFilter) Reset

func (sbf *StableBloomFilter) Reset()

Reset 重置过滤器

func (*StableBloomFilter) Test

func (sbf *StableBloomFilter) Test(key string) bool

Test 测试元素是否可能存在

type StableBloomStats

type StableBloomStats struct {
	Buckets         uint32  `json:"buckets"`
	CellsPerBucket  uint32  `json:"cells_per_bucket"`
	TotalCells      uint32  `json:"total_cells"`
	NonZeroCells    uint64  `json:"non_zero_cells"`
	UtilizationRate float64 `json:"utilization_rate"`
	AverageCount    float64 `json:"average_count"`
	MemoryBytes     uint64  `json:"memory_bytes"`
}

StableBloomStats 稳定布隆过滤器统计信息

type Strategy

type Strategy int8

Strategy 缓存在2级缓存的同步策略

const (
	WriteBoth Strategy = iota + 1
	WriteRemoteOnly
	AsyncWriteBoth
	AsyncWriteRemoteOnly
)

同步策略

type TTLConfig

type TTLConfig struct {
	BaseTTL     time.Duration // 基础TTL
	RandomRange time.Duration // 随机范围
	UseRandom   bool          // 是否使用随机TTL
}

TTLConfig TTL配置结构

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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