cache2go開源項目的回調方法使用

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
}
相關文章
相關標籤/搜索