CloudGeek读源码系列-cache2go源码解析

一、cache2go是什么

二、项目结构

项目目录结构如上图所示,可以看到功能实现相关源码文件只有3个:

  1. cache.go
  2. cacheitem.go
  3. cachetable.go

 三、关键数据结构

 项目中只涉及到2个复杂的数据类型,分别是:

  1. CacheItem
  2. CacheTable

 含义和字面意义一致,一个是缓存表,一个是缓存表中的条目。下面分别看一下这2个结构是怎么定义的。

1、CacheItem

CacheItem类型是用来表示一个单独的缓存条目,源码如下所示,每个字段都很清晰易懂,注释稍长的属性已经中文标注。

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

2、CacheTable

 CacheTable描述了缓存中的一个表项,里面的items属性就是上面讲到的CacheItem类型实例。这里除了常规属性外还有若干函数类型的属性,源码如下所示:

type CacheTable struct {
	sync.RWMutex

	// The table's name.
	name string
	// All cached items.【一个表中的所有条目都存在这个map里,map的key是任意类型,值是CacheItem指针类型】
	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.【需要提取一个不存在的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)
}

 如上所示,cache2go的核心数据结构很简洁,应该比较容易理解。当然没有完全理解每个字段这样定义的原因也别急,看完下面的代码逻辑后反过来再看数据结构,肯定就明白每个字段的作用了。

四、代码逻辑

猜你喜欢

转载自www.cnblogs.com/cloudgeek/p/9146736.html