9.go开源cache2go项目笔记——dataloader调用
测试dataloader相关功能。
1 代码packagemain
import(
"fmt"
"strconv"
"github.com/muesli/cache2go"
)
funcmain(){
cache:=cache2go.Cache("myCache")
cache.SetDataLoader(func(keyinterface{},args...interface{})*cache2go.CacheItem{
val:="Thisisatestwithkey"+key.(string)
item:=cache2go.CreateCacheItem(key,0,val)
return&item
})
fori:=0;i<10;i++{
res,err:=cache.Value("someKey_"+strconv.Itoa(i))
iferr==nil{
fmt.Println("Foundvalueincache:",res.Data())
}else{
fmt.Println("Errorretrievingvaluefromcache:",err)
}
}
}2 执行如下
Found value in cache: Thisis a test with key someKey_0
Found value in cache: Thisis a test with key someKey_1
Found value in cache: Thisis a test with key someKey_2
Found value in cache: Thisis a test with key someKey_3
Found value in cache: Thisis a test with key someKey_4
Found value in cache: Thisis a test with key someKey_5
Found value in cache: Thisis a test with key someKey_6
Found value in cache: Thisis a test with key someKey_7
Found value in cache: Thisis a test with key someKey_8
Found value in cache: This is a test with key someKey_9
3 代码说明cache:=cache2go.Cache("myCache")创建一个CACHE TABLE。
cache.SetDataLoader(func(keyinterface{},args...interface{}) 设置函数loadData函数,入参是CACHE ITEM的指针。当从CACHE TABLE中获取不存在的键时候会调用该函数,其中调用CreateCacheItem函数来创建CACHE ITEM。
然后一个循环10次,查找CACHE值,因为查找之前没有加载所以每次查找都不存在,然后就调用SetDataLoader(这个通过value函数来调用loadData)来创建CACHE。