bigcache

package
v1.0.2 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	// Expired 表示条目因过期而被移除
	Expired = RemoveReason(1)
	// NoSpace 表示由于空间不足而移除条目
	NoSpace = RemoveReason(2)
	// Deleted 表示条目被显式删除
	Deleted = RemoveReason(3)
)

定义移除原因的常量

View Source
const ErrCannotRetrieveEntry = iteratorError("cannot retrieve entry from cache")

ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying

View Source
const ErrInvalidIteratorState = iteratorError("iterator is in invalid state. Use SetNext() to move to next position")

ErrInvalidIteratorState is reported when iterator is in invalid state

Variables

View Source
var (
	// ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key
	ErrEntryNotFound = errors.New("entry not found")
)

Functions

This section is empty.

Types

type BigCache

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

BigCache 是一个快速、并发、可淘汰的缓存,用于存储大量条目而不会影响性能 它将条目保存在堆上但避免了GC对它们的影响。为了实现这一点,操作在字节数组上进行, 因此在大多数使用场景下,缓存前需要对条目进行(反)序列化。

func New

func New(ctx context.Context, config Config) (*BigCache, error)

New 初始化 BigCache 的新实例 参数:

ctx: 上下文,用于控制清理goroutine的生命周期
config: 缓存配置

返回值:

*BigCache: BigCache实例指针
error: 错误信息

func NewBigCache

func NewBigCache(config Config) (*BigCache, error)

NewBigCache 创建 BigCache 实例的旧版本接口(向后兼容) 参数:

config: 缓存配置

返回值:

*BigCache: BigCache实例指针
error: 错误信息

func (*BigCache) Append

func (c *BigCache) Append(key string, entry []byte) error

Append 如果键存在则在键下追加条目,否则行为与 Set() 相同 使用 Append() 可以以锁优化的方式在同一个键下连接多个条目 参数:

key: 键
entry: 要追加的条目数据

返回值:

error: 错误信息

func (*BigCache) Capacity

func (c *BigCache) Capacity() int

Capacity 返回缓存中存储的字节数 返回值:

int: 缓存中存储的字节总数

func (*BigCache) Close

func (c *BigCache) Close() error

Close 用于在使用完缓存后发出关闭信号 这允许清理goroutine退出,并确保不保留对缓存的引用,从而允许GC回收条目缓存 返回值:

error: 错误信息

func (*BigCache) Delete

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

Delete 删除指定键 参数:

key: 要删除的键

返回值:

error: 错误信息

func (*BigCache) Get

func (c *BigCache) Get(key string) ([]byte, error)

Get 根据键读取条目 当给定键不存在条目时返回 ErrEntryNotFound 错误 参数:

key: 要查找的键

返回值:

[]byte: 条目数据
error: 错误信息

func (*BigCache) GetWithInfo

func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error)

GetWithInfo 根据键读取条目并返回响应信息 当给定键不存在条目时返回 ErrEntryNotFound 错误 参数:

key: 要查找的键

返回值:

[]byte: 条目数据
Response: 响应信息
error: 错误信息

func (*BigCache) Iterator

func (c *BigCache) Iterator() *EntryInfoIterator

Iterator 返回迭代器函数,用于遍历整个缓存中的 EntryInfo 返回值:

*EntryInfoIterator: 条目信息迭代器

func (*BigCache) KeyMetadata

func (c *BigCache) KeyMetadata(key string) Metadata

KeyMetadata 返回缓存资源被请求的次数 参数:

key: 要查询的键

返回值:

Metadata: 键的元数据信息

func (*BigCache) Len

func (c *BigCache) Len() int

Len 计算缓存中的条目数量 返回值:

int: 缓存中条目的总数

func (*BigCache) Reset

func (c *BigCache) Reset() error

Reset 清空所有缓存分片 返回值:

error: 错误信息

func (*BigCache) ResetStats

func (c *BigCache) ResetStats() error

ResetStats 重置缓存统计信息 返回值:

error: 错误信息

func (*BigCache) Set

func (c *BigCache) Set(key string, entry []byte) error

Set 在键下保存条目 参数:

key: 键
entry: 要保存的条目数据

返回值:

error: 错误信息

func (*BigCache) Stats

func (c *BigCache) Stats() Stats

Stats 返回缓存的统计信息 返回值:

Stats: 缓存统计信息

type Config

type Config struct {
	// Number of cache shards, value must be a power of two
	Shards int
	// Time after which entry can be evicted
	LifeWindow time.Duration
	// Interval between removing expired entries (clean up).
	// If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution.
	CleanWindow time.Duration
	// Max number of entries in life window. Used only to calculate initial size for cache shards.
	// When proper value is set then additional memory allocation does not occur.
	MaxEntriesInWindow int
	// Max size of entry in bytes. Used only to calculate initial size for cache shards.
	MaxEntrySize int
	// StatsEnabled if true calculate the number of times a cached resource was requested.
	StatsEnabled bool
	// Verbose mode prints information about new memory allocation
	Verbose bool
	// Hasher used to calculate hash values for cache keys.
	Hasher hash2.Hasher `json:"-"`
	// HardMaxCacheSize is a limit for BytesQueue size in MB.
	// It can protect application from consuming all available memory on machine, therefore from running OOM Killer.
	// Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then
	// the oldest entries are overridden for the new ones. The max memory consumption will be bigger than
	// HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys
	// and statistics (map[uint64]uint32) the size of this map is equal to number of entries in
	// cache ~ 2×(64+32)×n bits + overhead or map itself.
	HardMaxCacheSize int
	// OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left
	// for the new entry, or because delete was called.
	// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
	// ignored if OnRemoveWithMetadata is specified.
	OnRemove func(key string, entry []byte)
	// OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left
	// for the new entry, or because delete was called. A structure representing details about that specific entry.
	// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
	OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata)
	// OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left
	// for the new entry, or because delete was called. A constant representing the reason will be passed through.
	// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
	// Ignored if OnRemove is specified.
	OnRemoveWithReason func(key string, entry []byte, reason RemoveReason)

	// Logger is a logging interface and used in combination with `Verbose`
	// Defaults to `DefaultLogger()`
	Logger *zap.Logger
	// contains filtered or unexported fields
}

Config for BigCache

func DefaultConfig

func DefaultConfig(eviction time.Duration) Config

DefaultConfig initializes config with default values. When load for BigCache can be predicted in advance then it is better to use custom config.

func (Config) OnRemoveFilterSet

func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config

OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. Filtering out reasons prevents bigcache from unwrapping them, which saves cpu.

type EntryInfo

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

EntryInfo holds informations about entry in the cache

func (EntryInfo) Hash

func (e EntryInfo) Hash() uint64

Hash returns entry's hash value

func (EntryInfo) Key

func (e EntryInfo) Key() string

Key returns entry's underlying key

func (EntryInfo) Timestamp

func (e EntryInfo) Timestamp() uint64

Timestamp returns entry's timestamp (time of insertion)

func (EntryInfo) Value

func (e EntryInfo) Value() []byte

Value returns entry's underlying value

type EntryInfoIterator

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

EntryInfoIterator allows to iterate over entries in the cache

func (*EntryInfoIterator) SetNext

func (it *EntryInfoIterator) SetNext() bool

SetNext moves to next element and returns true if it exists

func (*EntryInfoIterator) Value

func (it *EntryInfoIterator) Value() (EntryInfo, error)

Value returns current value from the iterator

type Metadata

type Metadata struct {
	// RequestCount 记录该条目被请求的次数
	RequestCount uint32
}

Metadata 包含特定缓存条目的信息

type RemoveReason

type RemoveReason uint32

RemoveReason 是一个值,用于在 OnRemove 回调中向用户指示特定键被移除的原因。

type Response

type Response struct {
	EntryStatus RemoveReason
}

Response will contain metadata about the entry for witch GetWithInfo(key) was called

type Stats

type Stats struct {
	// Hits is a number of successfully found keys
	Hits int64 `json:"hits"`
	// Misses is a number of not found keys
	Misses int64 `json:"misses"`
	// DelHits is a number of successfully deleted keys
	DelHits int64 `json:"delete_hits"`
	// DelMisses is a number of not deleted keys
	DelMisses int64 `json:"delete_misses"`
	// Collisions is a number of happened key-collisions
	Collisions int64 `json:"collisions"`
}

Stats stores cache statistics

Jump to

Keyboard shortcuts

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