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

 




查看原文: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值