cache

package
v0.0.0-...-c697eae Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 3 Imported by: 0

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 表示不限制)

func (*LRUCache[K, V]) Delete

func (own *LRUCache[K, V]) Delete(key K)

Delete 删除键

func (*LRUCache[K, V]) Get

func (own *LRUCache[K, V]) Get(key K) (V, bool)

Get 取值并将元素移至最近使用位置

func (*LRUCache[K, V]) GetLength

func (own *LRUCache[K, V]) GetLength() int

GetLength 返回当前元素个数

func (*LRUCache[K, V]) Put

func (own *LRUCache[K, V]) Put(key K, value V)

Put 写入键值,超出容量时淘汰最久未使用元素

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 指定)

func (*TTLCache[K, V]) Delete

func (own *TTLCache[K, V]) Delete(key K)

Delete 删除键

func (*TTLCache[K, V]) Get

func (own *TTLCache[K, V]) Get(key K) (V, bool)

Get 取值,若已过期则返回 (zero, false) 并删除

func (*TTLCache[K, V]) GetLength

func (own *TTLCache[K, V]) GetLength() int

GetLength 返回当前元素个数(含可能已过期的)

func (*TTLCache[K, V]) Purge

func (own *TTLCache[K, V]) Purge() int

Purge 清理所有已过期的元素

func (*TTLCache[K, V]) Put

func (own *TTLCache[K, V]) Put(key K, value V, ttl time.Duration)

Put 写入键值,ttl<=0 时使用默认 TTL,默认也为 0 则永不过期

Jump to

Keyboard shortcuts

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