go开源cache2go项目蛤蟆笔记——简单使用-

来源:互联网 发布:床约软件靠谱吗 编辑:程序博客网 时间:2024/05/21 16:11
                                                                                                     

1     下载开源

下载路径:https://github.com/muesli/cache2go

 

2     代码如下:

packagemain

 

import(

    "fmt"

    "time"

 

    "cache2go-master"

)

 

//Keys&valuesincache2gocanbeoffarbitrarytypes,e.g.astruct.

typemyStructstruct{

    text     string

    moreData[]byte

}

 

funcmain(){

    //Accessinganewcachetableforthefirsttimewillcreateit.

    cache:=cache2go.Cache("myCache")

 

    //Wewillputanewiteminthecache.Itwillexpireafter

    //notbeingaccessedviaValue(key)formorethan5seconds.

    val:=myStruct{"Thisisatest!",[]byte{}}

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

 

    //Let'sretrievetheitemfromthecache.

    res,err:=cache.Value("someKey")

    iferr==nil{

        fmt.Println("Foundvalueincache:",res.Data().(*myStruct).text)

    }else{

        fmt.Println("Errorretrievingvaluefromcache:",err)

    }

 

    //Waitfortheitemtoexpireincache.

    time.Sleep(6*time.Second)

    res,err=cache.Value("someKey")

    iferr!=nil{

        fmt.Println("Itemisnotcached(anymore).")

    }

 

    //Addanotheritemthatneverexpires.

    cache.Add("someKey",0,&val)

 

    //cache2gosupportsafewhandycallbacksandloadingmechanisms.

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

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

    })

 

    //Removetheitemfromthecache.

    cache.Delete("someKey")

 

    //Andwipetheentirecachetable.

    cache.Flush()

}

3     执行如下

Found value in cache: Thisis a test!

Item is not cached(anymore).

Deleting: someKey This is a test! 2016-07-12 16:31:57.0289334 +0800 CST

 




查看原文:http://www.zoues.com/2016/10/20/go%e5%bc%80%e6%ba%90cache2go%e9%a1%b9%e7%9b%ae%e8%9b%a4%e8%9f%86%e7%ac%94%e8%ae%b0-%e7%ae%80%e5%8d%95%e4%bd%bf%e7%94%a8/
0 0
原创粉丝点击