Discover Packages
github.com/zc310/ofd
internal
cache
package
Version:
v0.1.6
Opens a new window with list of versions in this module.
Published: Oct 27, 2026
License: Apache-2.0
Opens a new window with license information.
Imports: 4
Opens a new window with list of imports.
Imported by: 0 modules, 0 packages
The first number is the count of modules that contain a package that imports this one.
The module count is a better indicator of popularity than the package count.
A module with 100 importing packages is counted only once instead of 100 times,
reflecting the fact that the choice to use the package was likely made only once,
not 100 times.
A '?' means that the value hasn't been computed yet.
Opens a new window with list of known importers.
Documentation
Documentation
¶
Package cache 提供支持容量、权重和淘汰保护的并发安全缓存。
type LRU
func NewLRU[K comparable, V any](capacity int, onEvict func(K, V)) *LRU[K, V]
func NewWeightedLRU[K comparable, V any](capacity int, maxWeight int64, onEvict func(K, V), canEvict ...func(K, V) bool) *LRU[K, V]
func (c *LRU[K, V]) Add(key K, value V)
func (c *LRU[K, V]) AddWeighted(key K, value V, weight int64)
func (c *LRU[K, V]) Get(key K) (V, bool)
func (c *LRU[K, V]) Len() int
func (c *LRU[K, V]) Trim()
func (c *LRU[K, V]) Values() []V
func (c *LRU[K, V]) Weight() int64
LRU 是一个并发安全的最近最少使用缓存。
缓存同时受条目数量和可选总权重限制;条目淘汰后会在缓存锁释放后调用 onEvict。
NewLRU 创建只按条目数量限制的 LRU 缓存。
NewWeightedLRU 创建按条目数量和总权重限制的 LRU 缓存。
maxWeight 小于等于 0 表示不启用权重限制。可选的 canEvict 只用于暂时保护条目。
func (c *LRU [K, V]) Add(key K, value V)
Add 添加一个权重为 1 的条目。
func (c *LRU [K, V]) AddWeighted(key K, value V, weight int64 )
AddWeighted 添加一个带权重的条目;负权重按 0 处理。
func (c *LRU [K, V]) Get(key K) (V, bool )
Get 获取 key 对应的值,并将该条目提升为最近使用条目。
func (c *LRU [K, V]) Trim()
Trim 主动按当前容量和权重限制清理可淘汰条目。
被淘汰策略保护的条目会暂时保留,待之后再次调用 Trim 时处理。
func (c *LRU [K, V]) Values() []V
Values 返回当前缓存的全部值,按最近使用顺序。
调用方据此做收尾(如释放条目持有的重资源)时要注意:拿到的只是快照,之后
缓存仍可能被并发修改;因此适合在已经停用该缓存之后调用。
Weight 返回当前缓存条目的总权重,超过 int64 范围时返回 math.MaxInt64。
内部仍精确记账,淘汰或替换条目后会恢复实际可表示的权重。
Source Files
¶
Click to show internal directories.
Click to hide internal directories.