Skip to content

Commit b91898b

Browse files
committed
feat: correct the way of handling expired cache
Signed-off-by: Rueian <[email protected]>
1 parent b9b2beb commit b91898b

File tree

1 file changed

+13
-18
lines changed

1 file changed

+13
-18
lines changed

cache.go

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -206,17 +206,18 @@ type flatentry struct {
206206

207207
func (f *flatentry) insert(e *flatentry) {
208208
f.size += e.size
209+
f.ttl = e.ttl
209210
f.mu.Lock()
210211
e.ovfl = f.ovfl
211212
f.ovfl = e
212213
f.mu.Unlock()
213214
}
214215

215216
func (f *flatentry) find(cmd string, ts int64) ([]byte, bool) {
217+
if f != nil && ts >= f.ttl {
218+
return nil, true
219+
}
216220
for next := f; next != nil; {
217-
if ts >= next.ttl {
218-
return nil, true
219-
}
220221
if cmd == next.cmd {
221222
return next.val, false
222223
}
@@ -232,7 +233,7 @@ const lrBatchSize = 64
232233
const flattEntrySize = unsafe.Sizeof(flatentry{})
233234

234235
type lrBatch struct {
235-
m map[*flatentry]bool
236+
m map[*flatentry]struct{}
236237
}
237238

238239
func NewFlattenCache(limit int) CacheStore {
@@ -247,7 +248,7 @@ func NewFlattenCache(limit int) CacheStore {
247248
f.head.next = unsafe.Pointer(f.tail)
248249
f.tail.prev = unsafe.Pointer(f.head)
249250
f.lrup = sync.Pool{New: func() any {
250-
b := &lrBatch{m: make(map[*flatentry]bool, lrBatchSize)}
251+
b := &lrBatch{m: make(map[*flatentry]struct{}, lrBatchSize)}
251252
runtime.SetFinalizer(b, func(b *lrBatch) {
252253
if len(b.m) >= 0 {
253254
f.mu.Lock()
@@ -292,13 +293,9 @@ func (f *flatten) llTail(e *flatentry) {
292293
}
293294

294295
func (f *flatten) llTailBatch(b *lrBatch) {
295-
for e, expired := range b.m {
296+
for e := range b.m {
296297
if e.mark == f.mark {
297-
if expired {
298-
f.remove(e)
299-
} else {
300-
f.llTail(e)
301-
}
298+
f.llTail(e)
302299
}
303300
}
304301
clear(b.m)
@@ -315,20 +312,18 @@ func (f *flatten) Flight(key, cmd string, ttl time.Duration, now time.Time) (Red
315312
e := f.cache[key]
316313
f.mu.RUnlock()
317314
ts := now.UnixMilli()
318-
if v, expired := e.find(cmd, ts); v != nil || expired {
315+
if v, _ := e.find(cmd, ts); v != nil {
319316
batch := f.lrup.Get().(*lrBatch)
320-
batch.m[e] = expired
317+
batch.m[e] = struct{}{}
321318
if len(batch.m) >= lrBatchSize {
322319
f.mu.Lock()
323320
f.llTailBatch(batch)
324321
f.mu.Unlock()
325322
}
326323
f.lrup.Put(batch)
327-
if v != nil {
328-
var ret RedisMessage
329-
_ = ret.CacheUnmarshalView(v)
330-
return ret, nil
331-
}
324+
var ret RedisMessage
325+
_ = ret.CacheUnmarshalView(v)
326+
return ret, nil
332327
}
333328
fk := key + cmd
334329
f.mu.RLock()

0 commit comments

Comments
 (0)