当前位置: 首页 > 工具软件 > cachego > 使用案例 >

1.go开源cache2go项目笔记——简单使用-

蒙胤
2023-12-01

1.go开源cache2go项目笔记——简单使用-

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

 

 

 

 

 

 类似资料: