-
Notifications
You must be signed in to change notification settings - Fork 3
/
cache.go
204 lines (171 loc) · 5.06 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// Copyright 2020 FishGoddess. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cachego
import (
"errors"
"time"
"github.com/FishGoddess/cachego/pkg/singleflight"
)
var (
// errNotFound is the error of key not found.
errNotFound = errors.New("cachego: key not found")
)
// IsNotFound returns if this error is key not found.
func IsNotFound(err error) bool {
return err != nil && err == errNotFound
}
// Cache is a struct of cache.
type Cache struct {
// conf is the config of cache.
conf config
// segments is a slice stores the real data.
segments []*segment
// groups is a slice stores the singleflight keys.
groups []*singleflight.Group
}
// NewCache returns a new Cache holder for use.
func NewCache(opts ...Option) *Cache {
c := &Cache{
conf: *applyOptions(newDefaultConfig(), opts),
}
c.segments = newSegments(c.conf.mapSize, c.conf.segmentSize)
if c.conf.singleflight {
c.groups = newGroups(c.conf.mapSize, c.conf.segmentSize)
}
if c.conf.gcDuration > 0 {
c.AutoGC(c.conf.gcDuration)
}
return c
}
// newSegments returns a slice of initialized segments.
func newSegments(mapSize int, segmentSize int) []*segment {
segments := make([]*segment, segmentSize)
for i := 0; i < segmentSize; i++ {
segments[i] = newSegment(mapSize)
}
return segments
}
// newGroups returns a slice of initialized singleflight groups.
func newGroups(mapSize int, groupSize int) []*singleflight.Group {
groups := make([]*singleflight.Group, groupSize)
for i := 0; i < groupSize; i++ {
groups[i] = singleflight.NewGroup(mapSize)
}
return groups
}
// indexOf returns a position of this key.
func (c *Cache) indexOf(key string) int {
index := 1469598103934665603
keyBytes := []byte(key)
for _, b := range keyBytes {
index = (index << 5) - index + int(b&0xff)
index *= 1099511628211
}
return index
}
// segmentOf returns the segment of this key.
func (c *Cache) segmentOf(key string) *segment {
return c.segments[c.indexOf(key)&(len(c.segments)-1)]
}
// groupOf returns the singleflight group of this key.
func (c *Cache) groupOf(key string) *singleflight.Group {
return c.groups[c.indexOf(key)&(len(c.groups)-1)]
}
// Get fetches value of key from cache first, and returns it if ok.
// Returns an NotFoundErr if this key is not found, and you can use IsNotFound to judge if this error is not found.
// Also, you can specify a function which will be called if missed, so you can load this entry to cache again.
// See OpOption.
func (c *Cache) Get(key string, opts ...OpOption) (interface{}, error) {
v, ok := c.segmentOf(key).get(key)
if ok {
return v, nil
}
if len(opts) <= 0 {
return nil, errNotFound
}
conf := applyOpOptions(newDefaultGetConfig(), opts)
if conf.onMissed == nil {
return nil, errNotFound
}
var data interface{}
var err error
if c.conf.singleflight && conf.singleflight {
data, err = c.groupOf(key).Call(conf.ctx, key, conf.onMissed)
} else {
data, err = conf.onMissed(conf.ctx)
}
if err != nil {
return nil, err
}
if conf.reload {
c.Set(key, data, WithOpTTL(conf.ttl))
}
return data, nil
}
// Set sets key and value to cache.
// In default, this entry will not expire, so if you want it to expire, see SetOption.
func (c *Cache) Set(key string, value interface{}, opts ...OpOption) {
conf := applyOpOptions(newDefaultSetConfig(), opts)
c.segmentOf(key).set(key, value, conf.ttl)
}
// Delete removes the value of key.
// If this key is not existed, nothing will happen.
func (c *Cache) Delete(key string) {
c.segmentOf(key).delete(key)
c.groupOf(key).Delete(key)
}
// DeleteAll removes all keys in cache.
// Notice that this method is weak-consistency.
func (c *Cache) DeleteAll() {
for _, segment := range c.segments {
segment.deleteAll()
}
for _, group := range c.groups {
group.DeleteAll()
}
}
// Size returns the size of cache.
// Notice that this method is weak-consistency.
func (c *Cache) Size() int {
size := 0
for _, segment := range c.segments {
size += segment.size()
}
return size
}
// GC removes dead entries in cache.
// Notice that this method is weak-consistency, and it doesn't guarantee 100% removed.
func (c *Cache) GC() {
for _, segment := range c.segments {
segment.gc()
}
}
// AutoGC starts a goroutine to execute GC() at fixed duration.
// It returns a channel which can be used to stop this goroutine.
func (c *Cache) AutoGC(duration time.Duration) chan<- struct{} {
quitChan := make(chan struct{})
go func() {
ticker := time.NewTicker(duration)
defer ticker.Stop()
for {
select {
case <-ticker.C:
c.GC()
case <-quitChan:
return
}
}
}()
return quitChan
}