前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go开源cache2go项目蛤蟆笔记——简单使用-

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

作者头像
李海彬
发布2018-03-23 11:37:35
6870
发布2018-03-23 11:37:35
举报
文章被收录于专栏:Golang语言社区Golang语言社区

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2016-10-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档