Go cache 原始碼閱讀

2021-10-05 13:32:49 字數 1231 閱讀 1424

go-cache是一款類似於memached 的key/value 快取。它比較適用於單機執行的應用程式。不需要額外部署服務,直接在記憶體中以map管理快取的資料。

go-cache實質上就是擁有過期時間並且執行緒安全的map,可以被多個goroutine安全訪問。快取過期策略為lru策略。

專案主要**都在cache.go中,並僅需此乙個檔案即可

**邏輯清晰。主要是

type item struct 

expiration int64

}type cache struct 

type cache struct )

janitor *janitor

}type janitor struct 

其中item儲存了每條資料的資訊

cache為快取的總的結構

janitor為啟動器。

先說下這個janitor, 使用者呼叫new完成快取的創立:

func new(defaultexpiration, cleanupinterval time.duration) *cache

newcachewithjanitor創立了cache物件,函式呼叫 runjanitor 創立了乙個 goroutine完成快取過期清理。同時使用了小技巧(檢視原始碼注釋)保證了快取清理的goroutine的**。

而cache提供了快取的增刪改的功能,不再複述,其中用讀寫鎖對map進行多執行緒保護。

其中乙個提高效能小技巧:為了減少defer帶來的效能損耗,直接用unlock解鎖而不用defer 

// todo: calls to mu.unlock are currently not deferred because defer adds ~200 ns (as of go1.)

除了key-value型別的快取,還支援計數類的快取。

而此外專案提供的sharded.go,是提供了上述的標準方式的快取的一種優化。

type unexportedshardedcache struct 

type shardedcache struct 

最主要的優化點是用了cache陣列(buckets),採用了djb33/djb2的雜湊方法(// djb2 with better shuffling. 5x faster than fnv with the hash.hash overhead.)將快取分布於cache陣列中

從而防止了寫的過程中對整個快取的加鎖,提高了寫入效能。當然也帶來了一點記憶體的消耗和系統複雜度的提公升。

《原始碼閱讀》原始碼閱讀技巧,原始碼閱讀工具

檢視某個類的完整繼承關係 選中類的名稱,然後按f4 quick type hierarchy quick type hierarchy可以顯示出類的繼承結構,包括它的父類和子類 supertype hierarchy supertype hierarchy可以顯示出類的繼承和實現結構,包括它的父類和...

原始碼閱讀 Glide原始碼閱讀之with方法(一)

前言 本篇基於4.8.0版本 原始碼閱讀 glide原始碼閱讀之with方法 一 原始碼閱讀 glide原始碼閱讀之load方法 二 原始碼閱讀 glide原始碼閱讀之into方法 三 大多數情況下,我們使用glide 就一句 但是這一句 裡面蘊含著成噸的 with方法有以下幾個過載方法 publi...

原始碼閱讀 Glide原始碼閱讀之load方法(二)

原始碼閱讀 glide原始碼閱讀之load方法 二 原始碼閱讀 glide原始碼閱讀之into方法 三 首先,load方法有以下幾個過載方法 public requestbuilder load nullable bitmap bitmap public requestbuilder load nu...