Documentation
¶
Overview ¶
Package cache 提供线程安全的缓存实现
- LRUCache:基于双向链表 + map 的 LRU 淘汰缓存
- TTLCache:带过期时间的缓存(懒淘汰)
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type LRUCache ¶
type LRUCache[K comparable, V any] struct { // contains filtered or unexported fields }
LRUCache 线程安全的 LRU 缓存
Example ¶
c := NewLRUCache[string, string](2)
c.Put("name", "gokit")
c.Put("lang", "go")
// 命中返回 (value, true)
v, ok := c.Get("name")
fmt.Printf("%s %v\n", v, ok)
// 访问 name 使其成为最近使用,插入第三个时淘汰最久未使用的 "lang"
c.Put("ver", "1.0")
_, ok = c.Get("lang")
fmt.Println("lang present:", ok)
Output: gokit true lang present: false
func NewLRUCache ¶
func NewLRUCache[K comparable, V any](capacity int) *LRUCache[K, V]
NewLRUCache 创建容量为 capacity 的 LRU 缓存(capacity <= 0 表示不限制)
type TTLCache ¶
type TTLCache[K comparable, V any] struct { // contains filtered or unexported fields }
TTLCache 带过期时间的缓存
Example ¶
c := NewTTLCache[string, int](time.Minute)
c.Put("counter", 7, 0)
v, _ := c.Get("counter")
fmt.Println(v)
Output: 7
func NewTTLCache ¶
func NewTTLCache[K comparable, V any](defaultTTL time.Duration) *TTLCache[K, V]
NewTTLCache 创建 TTL 缓存,defaultTTL=0 表示默认永不过期(需每次 Put 指定)
Click to show internal directories.
Click to hide internal directories.