Skip to content

Commit a7301ca

Browse files
committed
feat: batch delete expired cache with llTailBatch
Signed-off-by: Rueian <[email protected]>
1 parent 4aebfc9 commit a7301ca

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

cache.go

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ const lrBatchSize = 64
232232
const flattEntrySize = unsafe.Sizeof(flatentry{})
233233

234234
type lrBatch struct {
235-
m map[*flatentry]struct{}
235+
m map[*flatentry]bool
236236
}
237237

238238
func NewFlattenCache(limit int) CacheStore {
@@ -247,7 +247,7 @@ func NewFlattenCache(limit int) CacheStore {
247247
f.head.next = unsafe.Pointer(f.tail)
248248
f.tail.prev = unsafe.Pointer(f.head)
249249
f.lrup = sync.Pool{New: func() any {
250-
b := &lrBatch{m: make(map[*flatentry]struct{}, lrBatchSize)}
250+
b := &lrBatch{m: make(map[*flatentry]bool, lrBatchSize)}
251251
runtime.SetFinalizer(b, func(b *lrBatch) {
252252
if len(b.m) >= 0 {
253253
f.mu.Lock()
@@ -287,15 +287,19 @@ func (f *flatten) llDel(e *flatentry) {
287287
}
288288

289289
func (f *flatten) llTail(e *flatentry) {
290-
if e.mark == f.mark {
291-
f.llDel(e)
292-
f.llAdd(e)
293-
}
290+
f.llDel(e)
291+
f.llAdd(e)
294292
}
295293

296294
func (f *flatten) llTailBatch(b *lrBatch) {
297-
for e := range b.m {
298-
f.llTail(e)
295+
for e, expired := range b.m {
296+
if e.mark == f.mark {
297+
if expired {
298+
f.remove(e)
299+
} else {
300+
f.llTail(e)
301+
}
302+
}
299303
}
300304
clear(b.m)
301305
}
@@ -311,18 +315,20 @@ func (f *flatten) Flight(key, cmd string, ttl time.Duration, now time.Time) (Red
311315
e := f.cache[key]
312316
f.mu.RUnlock()
313317
ts := now.UnixMilli()
314-
if v, _ := e.find(cmd, ts); v != nil {
318+
if v, expired := e.find(cmd, ts); v != nil || expired {
315319
batch := f.lrup.Get().(*lrBatch)
316-
batch.m[e] = struct{}{}
320+
batch.m[e] = expired
317321
if len(batch.m) >= lrBatchSize {
318322
f.mu.Lock()
319323
f.llTailBatch(batch)
320324
f.mu.Unlock()
321325
}
322326
f.lrup.Put(batch)
323-
var ret RedisMessage
324-
_ = ret.CacheUnmarshalView(v)
325-
return ret, nil
327+
if v != nil {
328+
var ret RedisMessage
329+
_ = ret.CacheUnmarshalView(v)
330+
return ret, nil
331+
}
326332
}
327333
fk := key + cmd
328334
f.mu.RLock()

0 commit comments

Comments
 (0)