样例代码分析

mycachedapp.go源码

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main

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

// Keys & values in cache2go can be of arbitrary types, e.g. a struct.
// 定义cache2go存储数据的结构
type myStruct struct {
text string
moreData []byte
}

func main() {
// Accessing a new cache table for the first time will create it.
// 创建一个新的名为myCache的缓存表,缓存库包含多张缓存表
cache := cache2go.Cache("myCache")

// We will put a new item in the cache. It will expire after
// not being accessed via Value(key) for more than 5 seconds.
// 实例化一个存储数据值
val := myStruct{"This is a test!", []byte{}}
// 将这个实例的地址(指针)添加到数据表中,设置key值为“someKey”,设置过期时间为5秒
cache.Add("someKey", 5*time.Second, &val)

// Let's retrieve the item from the cache.
// 从缓存中检索key值为“someKey”的数据项
res, err := cache.Value("someKey")
if err == nil {
// 如果没有错误,输出值中的text属性
fmt.Println("Found value in cache:", res.Data().(*myStruct).text)
} else {
// 如果有错误,输出错误信息
fmt.Println("Error retrieving value from cache:", err)
}

// Wait for the item to expire in cache.
// 延时6秒,等待刚刚缓存中的项目过期
time.Sleep(6 * time.Second)
// 再次从缓存中检索key值为“someKey”的数据项
res, err = cache.Value("someKey")
if err != nil {
// 如果有错误,输出“Item is not cached (anymore)”
fmt.Println("Item is not cached (anymore).")
}

// Add another item that never expires.
// 将val的指针添加到数据表中,设置key值为“someKey”,设置永不过期(过期时间参数为0)
cache.Add("someKey", 0, &val)

// cache2go supports a few handy callbacks and loading mechanisms.
// 为cache设置即将删除回调,即将删除项目时,输出数据的值以及创建时间
cache.SetAboutToDeleteItemCallback(func(e *cache2go.CacheItem) {
fmt.Println("Deleting:", e.Key(), e.Data().(*myStruct).text, e.CreatedOn())
})

// Remove the item from the cache.
// 删除key值为“someKey”的数据项
cache.Delete("someKey")

// And wipe the entire cache table.
// 清理整个缓存表
cache.Flush()
}

运行mycachedapp.go文件

1
2
3
4
mini@Vantablack:~/readsrc/cache2go/examples/mycachedapp$ go run mycachedapp.go 
Found value in cache: This is a test!
Item is not cached (anymore).
Deleting: someKey This is a test! 2021-04-23 17:14:39.985715126 +0800 CST m=+6.000372519

dataloader.go源码

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
package main

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

func main() {
// 创建一个新的名为myCache的缓存表
cache := cache2go.Cache("myCache")

// The data loader gets called automatically whenever something
// tries to retrieve a non-existing key from the cache.
// 设置数据加载函数,SetDataLoader的参数时一个函数。SetDataLoader函数会在调用cache.Value时触发
cache.SetDataLoader(func(key interface{}, args ...interface{}) *cache2go.CacheItem {
// Apply some clever loading logic here, e.g. read values for
// this key from database, network or file.
// 断言key为string,并与"This is a test with key "拼接
val := "This is a test with key " + key.(string)

// This helper method creates the cached item for us. Yay!
// 创建新的缓存项
item := cache2go.NewCacheItem(key, 0, val)
return item
})

// Let's retrieve a few auto-generated items from the cache.
for i := 0; i < 10; i++ {
// cache.Value会触发SetDataLoader设置的回调函数,自动生成数据添加到缓存库中
// strconv.Itoa()函数的参数是一个整型数字,它可以将数字转换成对应的字符串类型的数字。
res, err := cache.Value("someKey_" + strconv.Itoa(i))
if err == nil {
fmt.Println("Found value in cache:", res.Data())
} else {
fmt.Println("Error retrieving value from cache:", err)
}
}
}

运行dataloader.go文件

1
2
3
4
5
6
7
8
9
10
11
mini@Vantablack:~/readsrc/cache2go/examples/dataloader$ go run dataloader.go 
Found value in cache: This is a test with key someKey_0
Found value in cache: This is a test with key someKey_1
Found value in cache: This is a test with key someKey_2
Found value in cache: This is a test with key someKey_3
Found value in cache: This is a test with key someKey_4
Found value in cache: This is a test with key someKey_5
Found value in cache: This is a test with key someKey_6
Found value in cache: This is a test with key someKey_7
Found value in cache: This is a test with key someKey_8
Found value in cache: This is a test with key someKey_9

callbacks.go源码

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main

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

func main() {
// 创建一个新的名为myCache的缓存表
cache := cache2go.Cache("myCache")

// This callback will be triggered every time a new item
// gets added to the cache.
// 设置添加数据项回调函数,SetAddedItemCallback的参数时一个函数。SetDataLoader函数会在
cache.SetAddedItemCallback(func(entry *cache2go.CacheItem) {
// 输出"Added Callback 1:"+数据项的键、值以及创建时间
fmt.Println("Added Callback 1:", entry.Key(), entry.Data(), entry.CreatedOn())
})
// 添加已添加数据项回调函数
cache.AddAddedItemCallback(func(entry *cache2go.CacheItem) {
// 输出"Added Callback 2:"+数据项的键、值以及创建时间
fmt.Println("Added Callback 2:", entry.Key(), entry.Data(), entry.CreatedOn())
})
// This callback will be triggered every time an item
// is about to be removed from the cache.
// 为cache设置即将删除回调,删除项目时,输出数据的值以及创建时间
cache.SetAboutToDeleteItemCallback(func(entry *cache2go.CacheItem) {
// 输出"Deleting:"+数据项的键、值以及创建时间
fmt.Println("Deleting:", entry.Key(), entry.Data(), entry.CreatedOn())
})

// Caching a new item will execute the AddedItem callback.
// 往缓存表中添加数据
cache.Add("someKey", 0, "This is a test!")

// Let's retrieve the item from the cache
// 从缓存中检索key值为“someKey”的数据项
res, err := cache.Value("someKey")
if err == nil {
fmt.Println("Found value in cache:", res.Data())
} else {
fmt.Println("Error retrieving value from cache:", err)
}

// Deleting the item will execute the AboutToDeleteItem callback.
// 删除key值为“someKey”的数据项
cache.Delete("someKey")

// 删除添加数据回调函数
cache.RemoveAddedItemCallbacks()
// Caching a new item that expires in 3 seconds
// 在缓存表中添加一个key值为“anotherKey”,值为“This is another test”的数据向,设置过期时间为3秒
res = cache.Add("anotherKey", 3*time.Second, "This is another test")

// This callback will be triggered when the item is about to expire
// 设置过期回调
res.SetAboutToExpireCallback(func(key interface{}) {
fmt.Println("About to expire:", key.(string))
})

// 延时5秒
time.Sleep(5 * time.Second)
}

运行callbacks.go文件

1
2
3
4
5
6
7
mini@Vantablack:~/readsrc/cache2go/examples/callbacks$ go run callbacks.go 
Added Callback 1: someKey This is a test! 2021-04-23 19:03:45.069657446 +0800 CST m=+0.000035121
Added Callback 2: someKey This is a test! 2021-04-23 19:03:45.069657446 +0800 CST m=+0.000035121
Found value in cache: This is a test!
Deleting: someKey This is a test! 2021-04-23 19:03:45.069657446 +0800 CST m=+0.000035121
Deleting: anotherKey This is another test 2021-04-23 19:03:45.069732211 +0800 CST m=+0.000109882
About to expire: anotherKey