cache2go源码分析(一):cache2go应用场景


cache2go介绍

cache2go是golang的一个对象缓存库,可设置对象的缓存周期

cache2go官方案例

下载cache2go

1
2
go get github.com/muesli/cache2go
cd cache2go && go build && go test -v
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main

import (
"github.com/muesli/cache2go"
"fmt"
"time"
)

type myStruct struct {
text string
moreData []byte
}

func main() {
// 创建cache缓存对象
cache := cache2go.Cache("myCache")

// 实例化val,将val存至cache缓存中,缓存对象的key为someKey,缓存周期为5秒(5秒过后缓存对象失效)
val := myStruct{"This is a test!", []byte{}}
cache.Add("someKey", 5*time.Second, &val)

// 从缓存中检索出key为someKey的缓存对象
res, err := cache.Value("someKey")
if err == nil {
fmt.Println("Found value in cache:", res.Data().(*myStruct).text)
} else {
fmt.Println("Error retrieving value from cache:", err)
}

// 等待6秒使someKey对象自动失效
time.Sleep(6 * time.Second)
res, err = cache.Value("someKey")
if err != nil {
fmt.Println("Item is not cached (anymore).")
}

// 添加key为someKey的对象缓存周期为0,表示永不过期
cache.Add("someKey", 0, &val)

// cache2go支持一些回调和加载机制
cache.SetAboutToDeleteItemCallback(func(e *cache2go.CacheItem) {
fmt.Println("Deleting:", e.Key(), e.Data().(*myStruct).text, e.CreatedOn())
})

// 从cache缓存中移除someKey
cache.Delete("someKey")

// 清空整个cache缓存
cache.Flush()
}

执行结果

1
2
3
4
$ go run mycachedapp.go
Found value in cache: This is a test!
Item is not cached (anymore).
Deleting: someKey This is a test! 2016-04-29 14:20:04.758864028 +0800 CST