cache2go 里面主要就涉及到两个数据结构,即一个是 CacheTable,一个是 CacheItem,它们的关系为:一个 Cache 里面可以通过 name 关联多个 CacheTable,同时一个 CacheTable 可以通过 key 关联多个 CacheItem。
CacheTable 结构定义在 cachetable.go 文件里面,具体定义如下:
// CacheTable is a table within the cache
type CacheTable struct {
sync.RWMutex
// The table's name.
name string
// All cached items.
items map[interface{}]*CacheItem
// Timer responsible for triggering cleanup.
cleanupTimer *time.Timer
// Current timer duration.
cleanupInterval time.Duration
// The logger used for this table.
logger *log.Logger
// Callback method triggered when trying to load a non-existing key.
loadData func(key interface{}, args ...interface{}) *CacheItem
// Callback method triggered when adding a new item to the cache.
addedItem func(item *CacheItem)
// Callback method triggered before deleting an item from the cache.
aboutToDeleteItem func(item *CacheItem)
}
字段 | 说明 |
---|---|
sync.RWMutex | 读写锁,在对 Table 进行读写时,加锁,保证并发安全。 |
name | 表的名字。 |
items | 所有被缓存的数据。 |
cleanupTimer | 用于清除过期数据的定时器。 |
cleanupInterval | 下一次清除数据的时长。 |
logger | 日志。 |
loadData | 加载一个不存在的键时候触发的回调。 |
addedItem | 添加一个新数据时触发的回调。 |
aboutToDeleteItem | 删除一个数据之前触发的回调。 |
CacheItem 结构定义在 cacheitem.go 文件里面,具体定义如下:
// CacheItem is an individual cache item
// Parameter data contains the user-set value in the cache.
type CacheItem struct {
sync.RWMutex
// The item's key.
key interface{}
// The item's data.
data interface{}
// How long will the item live in the cache when not being accessed/kept alive.
lifeSpan time.Duration
// Creation timestamp.
createdOn time.Time
// Last access timestamp.
accessedOn time.Time
// How often the item was accessed.
accessCount int64
// Callback method triggered right before removing the item from the cache
aboutToExpire func(key interface{})
}
字段 | 说明 |
---|---|
sync.RWMutex | 读写锁,在对 item 进行读写时,加锁,保证并发安全。 |
key | 数据项的键。 |
data | 数据项的数据。 |
lifeSpan | 如果这个数据一直不被读写,还剩多久要被清除。 |
createdOn | 创建时间。 |
accessedOn | 最后访问时间。 |
accessCount | 访问次数。 |
aboutToExpire | 从缓存删除这个数据之前,触发的回调。 |
cache2go 里面主要就涉及到两个数据结构,即一个是 CacheTable,一个是 CacheItem,它们的关系为:一个 Cache 里面可以通过 name 关联多个 CacheTable,同时一个 CacheTable 可以通过 key 关联多个 CacheItem。