-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache.go
executable file
·106 lines (93 loc) · 1.88 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package roc
import (
"context"
"time"
"github.com/xiaojiaoyu100/curlew"
)
// Cache is a store.
type Cache struct {
GCInterval time.Duration
BucketNum int
buckets []*Bucket
dispatcher *curlew.Dispatcher
close chan struct{}
}
// New returns a new cache.
func New(setters ...Setter) (*Cache, error) {
c := new(Cache)
c.GCInterval = 120 * time.Second
c.BucketNum = 16
for _, setter := range setters {
if err := setter(c); err != nil {
return nil, err
}
}
c.buckets = make([]*Bucket, 0, c.BucketNum)
for idx := 0; idx < c.BucketNum; idx++ {
bucket, err := NewBucket()
if err != nil {
return nil, err
}
c.buckets = append(c.buckets, bucket)
}
monitor := func(err error) {}
var err error
c.dispatcher, err = curlew.New(
curlew.WithMonitor(monitor),
curlew.WithMaxWorkerNum(16),
)
if err != nil {
return nil, err
}
c.close = make(chan struct{})
c.gc()
return c, nil
}
func (c *Cache) gc() {
go func() {
ticker := time.NewTicker(c.GCInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
for _, bucket := range c.buckets {
j := curlew.NewJob()
j.Fn = func(_ context.Context, arg interface{}) error {
b := arg.(*Bucket)
b.gc()
return nil
}
j.Arg = bucket
c.dispatcher.Submit(j)
}
case <-c.close:
return
}
}
}()
}
// Get returns a value.
func (c *Cache) Get(key string) (interface{}, error) {
idx, err := c.hashIndex(key)
if err != nil {
return nil, err
}
return c.buckets[idx].Get(key)
}
// Set sets a value.
func (c *Cache) Set(key string, value interface{}, duration time.Duration) error {
idx, err := c.hashIndex(key)
if err != nil {
return err
}
return c.buckets[idx].Set(key, value, duration)
}
// Del deletes a key.
func (c *Cache) Del(key string) error {
idx, err := c.hashIndex(key)
if err != nil {
return err
}
c.buckets[idx].Del(key)
return nil
}