hashicorp/golang-lru

GitHub: hashicorp/golang-lru

Hashiorp 出品的 Go 语言线程安全 LRU 缓存库,提供固定容量淘汰与 TTL 过期两种缓存策略。

Stars: 5105 | Forks: 540

# golang-lru 这提供了 `lru` 包,它实现了一个固定大小的 线程安全的 LRU cache。它基于 Groupcache 中的 cache 实现。 # 文档 完整文档可在 [Go Packages](https://pkg.go.dev/github.com/hashicorp/golang-lru/v2) 上查阅 # LRU cache 示例 ``` package main import ( "fmt" "github.com/hashicorp/golang-lru/v2" ) func main() { l, _ := lru.New[int, any](128) for i := 0; i < 256; i++ { l.Add(i, nil) } if l.Len() != 128 { panic(fmt.Sprintf("bad len: %v", l.Len())) } } ``` # 可过期的 LRU cache 示例 ``` package main import ( "fmt" "time" "github.com/hashicorp/golang-lru/v2/expirable" ) func main() { // make cache with 10ms TTL and 5 max keys cache := expirable.NewLRU[string, string](5, nil, time.Millisecond*10) // set value under key1. cache.Add("key1", "val1") // get value under key1 r, ok := cache.Get("key1") // check for OK value if ok { fmt.Printf("value before expiration is found: %v, value: %q\n", ok, r) } // wait for cache to expire time.Sleep(time.Millisecond * 12) // get value under key1 after key expiration r, ok = cache.Get("key1") fmt.Printf("value after expiration is found: %v, value: %q\n", ok, r) // set value under key2, would evict old entry because it is already expired. cache.Add("key2", "val2") fmt.Printf("Cache len: %d\n", cache.Len()) // Output: // value before expiration is found: true, value: "val1" // value after expiration is found: false, value: "" // Cache len: 1 } ```
标签:EVTX分析, Golang, LRU, 基础库, 安全编程, 日志审计, 线程安全, 缓存