美文网首页Go
内存缓存 - cache2go分析

内存缓存 - cache2go分析

作者: cx7 | 来源:发表于2019-02-27 21:52 被阅读0次

最近接触到一个内存缓存的例子 cache2go
描述了最简单的缓存机制 :

  1. 维护一个缓存对象map,设置到期时间.
  2. 访问缓存对象 刷新缓存对象的生存周期
  3. 生存周期到期后删除缓存对象

cache2go结构

.
├── LICENSE.txt
├── README.md
├── benchmark_test.go
├── cache.go
├── cache_test.go
├── cacheitem.go
├── cachetable.go
├── errors.go
└── examples
    ├── callbacks
    │   └── callbacks.go
    ├── dataloader
    │   └── dataloader.go
    └── mycachedapp
        └── mycachedapp.go

主要构成 cacheitem.go 描述缓存对象
cachetable.go 描述缓存对象表
errors.go 定义缓存状态错误
cache.go 定义多个缓存对象表

go编程风格

go和c有些相似之处 以结构体为单元 描述一个对象

CacheItem是cache2go描述缓存对象的结构

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

KeepAlive是CacheItem这个结构的一个方法 刷新缓存对象的声明周期

func (item *CacheItem) KeepAlive() {
    item.Lock()
    defer item.Unlock()
    item.accessedOn = time.Now()
    item.accessCount++
}

整体的编程逻辑类似C语言
cache2go的逻辑设计的简单易懂 比较有意思的一个地方是缓存对象的到期处理

判断有下一个到期的缓存对象 增加一个对应的延时执行的协程来执行

func (table *CacheTable) expirationCheck() {
......
table.cleanupInterval = smallestDuration
    if smallestDuration > 0 {
        table.cleanupTimer = time.AfterFunc(smallestDuration, func() {
            go table.expirationCheck()
        })
    }
    table.Unlock()
}

相关文章

网友评论

    本文标题:内存缓存 - cache2go分析

    本文链接:https://www.haomeiwen.com/subject/upbfuqtx.html