-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
72 lines (64 loc) · 1.4 KB
/
cache.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
67
68
69
70
71
72
package rsstore
import (
"fmt"
"sync"
"time"
)
var vCache sync.Map
func Cache() *sync.Map {
return &vCache
}
func SetCache(key string, val interface{}, bForce bool) error {
if !bForce {
if _, ok := vCache.Load(key); ok {
return fmt.Errorf("cache data already exists, key: %v", key)
}
}
vCache.Store(key, val)
return nil
}
// delete: beforeDelleteFunc return true
func GetCache(key string, bDelete bool, beforeDelleteFunc func(v interface{}) bool) interface{} {
val, _ := vCache.Load(key)
if bDelete {
if beforeDelleteFunc != nil && !beforeDelleteFunc(val) {
return val
}
vCache.Delete(key)
}
return val
}
func SetCacheByTime(key string, val interface{}, bForce bool, timeout time.Duration, callback func(key, val any) bool) error {
if !bForce {
if _, ok := vCache.Load(key); ok {
return fmt.Errorf("cache data already exists, key: %v", key)
}
}
vCache.Store(key, val)
if timeout > 0 {
go autoClearByTimer(key, val, timeout, callback)
}
return nil
}
// timeUnit: second
func autoClearByTimer(key, val any, timeout time.Duration, callback func(key, val any) bool) {
timer := time.NewTimer(timeout * time.Second)
for {
select {
case <-timer.C:
if callback != nil {
if callback(key, val) {
timer.Stop()
vCache.Delete(key)
} else {
timer.Reset(timeout * time.Second)
break
}
} else {
timer.Stop()
vCache.Delete(key)
}
return
}
}
}