-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache.go
175 lines (152 loc) · 4.04 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
// Copyright 2020 Ye Zi Jie. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
//
// Author: FishGoddess
// Email: fishgoddess@qq.com
// Created at 2020/09/05 22:19:56
package caches
import (
"sync"
"sync/atomic"
"time"
)
// Cache is a struct with caching functions.
type Cache struct {
// segmentSize is the size of segments.
// This value will affect the performance of concurrency.
segmentSize int
// segments is a slice stores the real data.
segments []*segment
// options stores all options.
options *Options
// dumping means if cache is in dumping status.
// 1 is dumping.
dumping int32
}
// NewCache returns a new Cache holder with default options.
func NewCache() *Cache {
return NewCacheWith(DefaultOptions())
}
// NewCacheWith returns a new Cache holder with given options.
func NewCacheWith(options Options) *Cache {
if cache, ok := recoverFromDumpFile(options.DumpFile); ok {
return cache
}
return &Cache{
segmentSize: options.SegmentSize,
segments: newSegments(&options),
options: &options,
dumping: 0,
}
}
// recoverFromDumpFile recovers the cache from a dump file.
// Return a false if failed.
func recoverFromDumpFile(dumpFile string) (*Cache, bool) {
cache, err := newEmptyDump().from(dumpFile)
if err != nil {
return nil, false
}
return cache, true
}
// newSegments returns a slice of initialized segments.
func newSegments(options *Options) []*segment {
segments := make([]*segment, options.SegmentSize)
for i := 0; i < options.SegmentSize; i++ {
segments[i] = newSegment(options)
}
return segments
}
// index returns a position in segments of this key.
func index(key string) int {
index := 0
keyBytes := []byte(key)
for _, b := range keyBytes {
index = 31*index + int(b&0xff)
}
return index ^ (index >> 16)
}
// segmentOf returns the segment of this key.
func (c *Cache) segmentOf(key string) *segment {
return c.segments[index(key)&(c.segmentSize-1)]
}
// Get returns the value of specified key.
func (c *Cache) Get(key string) ([]byte, bool) {
c.waitForDumping()
return c.segmentOf(key).get(key)
}
// Set sets an entry of specified key and value.
func (c *Cache) Set(key string, value []byte) error {
return c.SetWithTTL(key, value, NeverDie)
}
// SetWithTTL sets an entry of specified key and value which has ttl.
func (c *Cache) SetWithTTL(key string, value []byte, ttl int64) error {
c.waitForDumping()
return c.segmentOf(key).set(key, value, ttl)
}
// Delete deletes the specified key and value.
func (c *Cache) Delete(key string) error {
c.waitForDumping()
c.segmentOf(key).delete(key)
return nil
}
// Status returns the status of cache.
func (c *Cache) Status() Status {
result := NewStatus()
for _, segment := range c.segments {
status := segment.status()
result.Count += status.Count
result.KeySize += status.KeySize
result.ValueSize += status.ValueSize
}
return *result
}
// gc will clean up the dead entries in cache.
func (c *Cache) gc() {
c.waitForDumping()
wg := &sync.WaitGroup{}
for _, seg := range c.segments {
wg.Add(1)
go func(s *segment) {
defer wg.Done()
s.gc()
}(seg)
}
wg.Wait()
}
// AutoGc starts a goroutine and runs the gc task at fixed duration.
func (c *Cache) AutoGc() {
go func() {
ticker := time.NewTicker(time.Duration(c.options.GcDuration) * time.Minute)
for {
select {
case <-ticker.C:
c.gc()
}
}
}()
}
// dump dumps c to dumpFile and returns an error if failed.
func (c *Cache) dump() error {
atomic.StoreInt32(&c.dumping, 1)
defer atomic.StoreInt32(&c.dumping, 0)
return newDump(c).to(c.options.DumpFile)
}
// AutoDump starts a goroutine and runs the dump task at fixed duration.
func (c *Cache) AutoDump() {
go func() {
ticker := time.NewTicker(time.Duration(c.options.DumpDuration) * time.Minute)
for {
select {
case <-ticker.C:
c.dump()
}
}
}()
}
// waitForDumping will wait for dumping.
func (c *Cache) waitForDumping() {
for atomic.LoadInt32(&c.dumping) != 0 {
time.Sleep(time.Duration(c.options.CasSleepTime) * time.Microsecond)
}
}