golang筆記-cache組件應用: freecache/groupcache/golang-lru


1. freecache:

https://github.com/coocood/freecache
內存中的長壽命對象會引入昂貴的 GC 開銷,使用 FreeCache,您可以在內存中緩存無限數量的對象,而不會增加延遲和降低吞吐量。
Features

存儲數以億計的條目
零 GC 開銷
高並發線程安全訪問
純 Go 實現
支持淘汰
近似 LRU 算法
嚴格限制內存使用
附帶一個toy server,支持一些帶有pipeline的基本 Redis 命令
支持Iterator

注意

內存是預先分配的。
如果分配大量內存,則可能需要將 debug.SetGCPercent() 設置為低得多的百分比以獲得正常的 GC 頻率。

example

// In bytes, where 1024 * 1024 represents a single Megabyte, and 100 * 1024*1024 represents 100 Megabytes.
cacheSize := 100 * 1024 * 1024
cache := freecache.NewCache(cacheSize)
debug.SetGCPercent(20)
key := []byte("abc")
val := []byte("def")
expire := 60 // expire in 60 seconds
cache.Set(key, val, expire)
got, err := cache.Get(key)
if err != nil {
    fmt.Println(err)
} else {
    fmt.Printf("%s\n", got)
}
affected := cache.Del(key)
fmt.Println("deleted key ", affected)
fmt.Println("entry count ", cache.EntryCount())

2. groupcache:

https://github.com/golang/groupcache
groupcache is a distributed caching and cache-filling library, intended as a replacement for a pool of memcached nodes in many cases.
內部支持lrucache:
https://github.com/golang/groupcache/tree/master/lru
注意lru cache的實現並非線程安全:Cache is an LRU cache. It is not safe for concurrent access.
主要方法:

// New creates a new Cache.
// If maxEntries is zero, the cache has no limit and it's assumed
// that eviction is done by the caller.
func New(maxEntries int) *Cache 

// Add adds a value to the cache.
func (c *Cache) Add(key Key, value interface{}) 

// Get looks up a key's value from the cache.
func (c *Cache) Get(key Key) (value interface{}, ok bool)

// Remove removes the provided key from the cache.
func (c *Cache) Remove(key Key)

// RemoveOldest removes the oldest item from the cache.
func (c *Cache) RemoveOldest()

func (c *Cache) removeElement(e *list.Element) 

// Len returns the number of items in the cache.
func (c *Cache) Len() int 

// Clear purges all stored items from the cache.
func (c *Cache) Clear() 

3. golang-lru:

https://github.com/hashicorp/golang-lru
This provides the lru package which implements a fixed-size thread safe LRU cache. It is based on the cache in Groupcache.
特點:線程安全的LRU CACHE


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM