您的位置 首页 golang

Golang cache2go了解

cache2go是一个用Go实现的并发安全的缓存库.

特性:

并发安全;

可设置每条 缓存 的超时时间;

内置缓存访问计数;

自调节的缓存过期检查;

可设置缓存增加/删除 回调函数

cache2go中主要涉及两个类型CacheItem、CacheTable:

一个CacheItem代表一条缓存;

一个CacheTable代表一个缓存表,由一条条缓存组成。

//CacheItem

type CacheItem struct {

sync.RWMutex // 互斥锁

key interface{} // data-key

data interface{} // data-value

lifeSpan time.Duration // 生命周期

createdOn time.Time // 创建时间

accessedOn time.Time // 最后访问时间

accessCount int64 // 访问次数

aboutToExpire func(key interface{}) // TODO

}

//CacheTable

type CacheTable struct {

sync.RWMutex // 互斥锁

name string // 表名

items map[interface{}]*CacheItem // item的集合

cleanupTimer *time.Timer // 设置清理时间(处于等待状态)

cleanupInterval time.Duration // 设置清理时间段

logger *log.Logger // 设置日志

loadData func(key interface{}, args …interface{}) *CacheItem

addedItem func(item *CacheItem)

aboutToDeleteItem func(item *CacheItem)

}

官方示例:

go get github.com/muesli/cache2go

package main

import (

“github.com/muesli/cache2go”

“fmt”

“time”

)

// Keys & values in cache2go can be of arbitrary types, e.g. a struct.

type myStruct struct {

text string

moreData [] byte

}

func main() {

// Accessing a new cache table for the first time will create it.

cache := cache2go.Cache(“myCache”)

// We will put a new item in the cache. It will expire after

// not being accessed via Value(key) for more than 5 seconds.

val := myStruct{“This is a test!”, []byte{}}

cache.Add(“someKey”, 5*time.Second, &val)

// Let’s retrieve the item from the cache.

res, err := cache.Value(“someKey”)

if err == nil {

fmt.Println(“Found value in cache:”, res.Data().(*myStruct).text)

} else {

fmt.Println(“Error retrieving value from cache:”, err)

}

// Wait for the item to expire in cache.

time.Sleep(6 * time.Second)

res, err = cache.Value(“someKey”)

if err != nil {

fmt.Println(“Item is not cached (anymore).”)

}

// Add another item that never expires.

cache.Add(“someKey”, 0, &val)

// cache2go supports a few handy callbacks and loading mechanisms.

cache.SetAboutToDeleteItemCallback(func(e *cache2go.CacheItem) {

fmt.Println(“Deleting:”, e.Key(), e.Data().(*myStruct).text, e.CreatedOn())

})

// Remove the item from the cache.

cache.Delete(“someKey”)

// And wipe the entire cache table.

cache.Flush()

}

小结 :cache2go的源代码很少但是很经典,可以作为go入门代码学习。整体上cache2go也比较好理解,示例比较详细,不需要过多解释。如果在日常开发中有用到cache的不妨一试。

更多内容请关注头条号每日编程,每天进步一点。

文章来源:智云一二三科技

文章标题:Golang cache2go了解

文章地址:https://www.zhihuclub.com/88667.shtml

关于作者: 智云科技

热门文章

网站地图