-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
56 lines (48 loc) · 944 Bytes
/
example_test.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
package warmcache
import (
"fmt"
"sync/atomic"
"time"
)
func Example() {
var counter int32
// prepare cache setting
cacheFunc := func() (interface{}, error) {
atomic.AddInt32(&counter, 1)
return atomic.LoadInt32(&counter), nil
}
interval := 1 * time.Second
// create CacheMgr
c, err := NewCacheMgr(cacheFunc, interval, nil)
if err != nil {
fmt.Println("cacheFunc is failed", err)
return
}
// fetch cache. no origin access. always warm.
data, isStale, err := c.CacheData()
if isStale {
fmt.Println("cache is stale")
return
}
if err != nil {
fmt.Println("cacheFunc is failed", err)
return
}
fmt.Println(data)
// wait updating
time.Sleep(interval + 100*time.Millisecond)
// fetch new cache.
data, isStale, err = c.CacheData()
if isStale {
fmt.Println("cache is stale")
return
}
if err != nil {
fmt.Println("cacheFunc is failed", err)
return
}
fmt.Println(data)
// Output:
// 1
// 2
}