Cache2go源码分析

cacheitem.go

所有有关 cacheitem 的操作都存放在 cacheitem.go 源文件里面,我们看到,在程序的一开始首先定义了 cacheitem 的结构,具体代码如下:

// 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{}) }

下面,首先,我们先看 NewCacheItem 接口,具体代码如下:

// NewCacheItem returns a newly created CacheItem. // Parameter key is the item's cache-key. // Parameter lifeSpan determines after which time period without an access the item // will get removed from the cache. // Parameter data is the item's value. func NewCacheItem(key interface{}, lifeSpan time.Duration, data interface{}) *CacheItem { t := time.Now() return &CacheItem{ key: key, lifeSpan: lifeSpan, createdOn: t, accessedOn: t, accessCount: 0, aboutToExpire: nil, data: data, } }

在 Go 语言中,没有构造函数,所以一般都是通过 NewXXX 来实现构造函数的功能,这个我们创建一个 CacheItem 需要传入一个键 key、一个生命时长和需要缓存的数据,返回一个创建好的 CacheItem 指针对象。

接着,我们看下 KeepAlive 接口,具体代码如下:

// KeepAlive marks an item to be kept for another expireDuration period. func (item *CacheItem) KeepAlive() { item.Lock() defer item.Unlock() item.accessedOn = time.Now() item.accessCount++ }

KeepAlive 接口其实非常的简单,就是首先加锁,然后使用 defer 解锁,接着,将访问时间设置为当前时间,并将访问次数加一即可。接着,我们再次再次看下 AccessedOn 接口,该接口代码如下:

// AccessedOn returns when this item was last accessed. func (item *CacheItem) AccessedOn() time.Time { item.RLock() defer item.RUnlock() return item.accessedOn }

我们看到,这个同样的就是先加锁,然后直接返回对应的属性即可。

Cache2go源码分析总结

在 Go 语言中,没有构造函数,所以一般都是通过 NewXXX 来实现构造函数的功能。