8.go开源cache2go项目笔记——callbacks调用

来源:互联网 发布:阿里云 腾讯云 香港 编辑:程序博客网 时间:2024/05/18 00:54

8.go开源cache2go项目笔记——callbacks调用

调用CALLBACK测试,包含main函数

1      代码如下:

package main

import (

       "fmt"

       "time"

       "cache2go-master"

)

func main() {

       cache:= cache2go.Cache("myCache")

       cache.SetAddedItemCallback(func(entry*cache2go.CacheItem) {

              fmt.Println("Added:",entry.Key(), entry.Data(), entry.CreatedOn())

       })

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

              fmt.Println("Deleting:",entry.Key(), entry.Data(), entry.CreatedOn())

       })

       cache.Add("someKey",0, "This is a test!")

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

       iferr == nil {

              fmt.Println("Foundvalue in cache:", res.Data())

       }else {

              fmt.Println("Errorretrieving value from cache:", err)

       }

       cache.Delete("someKey")

       res= cache.Add("anotherKey", 3*time.Second, "This is anothertest")

       res.SetAboutToExpireCallback(func(keyinterface{}) {

              fmt.Println("Aboutto expire:", key.(string))

       })

 

       time.Sleep(5* time.Second)

}

2      执行如下:

Added: someKey This is a test! 2016-07-16 23:46:08.1364223+0800 CST

Found value in cache: This is a test!

Deleting: someKey This is a test! 2016-07-16 23:46:08.1364223+0800 CST

Added: anotherKey This is another test 2016-07-1623:46:08.1634223 +0800 CST

Deleting: anotherKey This is another test 2016-07-1623:46:08.1634223 +0800 CST

About toexpire: anotherKey

3      代码说明:

其中cache.SetAddedItemCallback 函数是在cachetable.go中定义中实现的接口函数,将具体的函数指针赋值给cache table结构中的addedItem。本次实现的函数入参为CacheItem的指针,然后输出键、值和创建时间。

cache. SetAboutToDeleteItemCallback函数是在cachetable.go中定义中实现的接口函数。实现的函数入参为CacheItem的指针,然后输出删除的键、值和创建时间。

cache.Add("someKey", 0,"This is a test!") 函数向CACHE TABLE中加入一个缓存,不过期。键为someKey,值为This is a test.返回cache item指针。

res, err :=cache.Value("someKey") 从cache table中获取键为someKey的值。

cache.Delete("someKey")从cache table中删除键为someKey的值。

res=cache.Add("anotherKey",3*time.Second,"Thisisanothertest")增加一个键为anotherKey,键值This is another test,持续时间为3秒。返回cache item指针。

res.SetAboutToExpireCallback设置该CACHE ITEM的过期回调函数,定义在cacheitem.go文件中。当过期后调用,调用则会输出键过期。

 

 

阅读全文
0 0
原创粉丝点击