https://github.com/muesli/cache2gogit
type CacheTable struct { sync.RWMutex . name string items map[interface{}]*CacheItem cleanupTimer *time.Timer cleanupInterval time.Duration logger *log.Logger // 回調方法定義 loadData func(key interface{}, args ...interface{}) *CacheItem addedItem func(item *CacheItem) aboutToDeleteItem func(item *CacheItem) }
func (table *CacheTable) SetAddedItemCallback(f func(*CacheItem)) { table.Lock() defer table.Unlock() // 回調方法賦值f函數對象 table.addedItem = f }
func (table *CacheTable) addInternal(item *CacheItem) { table.log("Adding item with key", item.key, "and lifespan of", item.lifeSpan, "to table", table.name) table.items[item.key] = item expDur := table.cleanupInterval // 獲取回調方法內容 addedItem := table.addedItem table.Unlock() // 若是不爲空,即已配置回調,執行回調 if addedItem != nil { addedItem(item) } if item.lifeSpan > 0 && (expDur == 0 || item.lifeSpan < expDur) { table.expirationCheck() } }
func main() { cache := cache2go.Cache("myCache") // 配置回調方法 cache.SetAddedItemCallback(func(entry *cache2go.CacheItem) { fmt.Println("Added:", entry.Key(), entry.Data(), entry.CreatedOn()) }) // 添加將執行回調 cache.Add("someKey", 0, "This is a test!") // Added: someKey This is a test! 2018-11-15 15:32:58.226001519 +0800 CST m=+0.000146463 }