-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcache.go
executable file
·81 lines (64 loc) · 1.22 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
73
74
75
76
77
78
79
80
81
package rcc
import (
"encoding/gob"
"os"
"sync"
)
// 配置kv内存结构
type Cache struct {
kv sync.Map
}
func newCache() *Cache {
return &Cache{
kv: sync.Map{},
}
}
func (c *Cache) set(key, val string) {
c.kv.Store(key, val)
}
func (c *Cache) get(key string) (string, bool) {
if val, ok := c.kv.Load(key); ok {
if ret, ok := val.(string); ok {
return ret, true
}
}
return "", false
}
func (c *Cache) delete(key string) {
c.kv.Delete(key)
}
func (c *Cache) dump() map[string]string {
var ret = map[string]string{}
c.kv.Range(func(key, val interface{}) bool {
k, _ := key.(string)
v, _ := val.(string)
ret[k] = v
return true
})
return ret
}
func (c *Cache) store(name string) error {
f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
return err
}
defer f.Close()
var dumps = map[string]string{}
dumps = c.dump()
return gob.NewEncoder(f).Encode(&dumps)
}
func (c *Cache) load(name string) error {
f, err := os.OpenFile(name, os.O_RDONLY, 0755)
if err != nil {
return err
}
defer f.Close()
var dumps = map[string]string{}
if err := gob.NewDecoder(f).Decode(&dumps); err != nil {
return err
}
for k, v := range dumps {
c.set(k, v)
}
return nil
}