优化ttlcache

This commit is contained in:
刘祥超
2022-04-09 18:28:22 +08:00
parent 02469f2886
commit ded2f98cce
10 changed files with 259 additions and 90 deletions

View File

@@ -5,21 +5,24 @@ import (
"sync"
)
type ItemMap = map[int64]zero.Zero
type ItemMap = map[uint64]zero.Zero
type List struct {
expireMap map[int64]ItemMap // expires timestamp => map[id]ItemMap
itemsMap map[int64]int64 // itemId => timestamp
itemsMap map[uint64]int64 // itemId => timestamp
locker sync.Mutex
gcCallback func(itemId int64)
gcCallback func(itemId uint64)
gcBatchCallback func(itemIds ItemMap)
lastTimestamp int64
}
func NewList() *List {
var list = &List{
expireMap: map[int64]ItemMap{},
itemsMap: map[int64]int64{},
itemsMap: map[uint64]int64{},
}
SharedManager.Add(list)
@@ -27,12 +30,25 @@ func NewList() *List {
return list
}
func NewSingletonList() *List {
var list = &List{
expireMap: map[int64]ItemMap{},
itemsMap: map[uint64]int64{},
}
return list
}
// Add 添加条目
// 如果条目已经存在,则覆盖
func (this *List) Add(itemId int64, expiresAt int64) {
func (this *List) Add(itemId uint64, expiresAt int64) {
this.locker.Lock()
defer this.locker.Unlock()
if this.lastTimestamp == 0 || this.lastTimestamp > expiresAt {
this.lastTimestamp = expiresAt
}
// 是否已经存在
oldExpiresAt, ok := this.itemsMap[itemId]
if ok {
@@ -55,34 +71,61 @@ func (this *List) Add(itemId int64, expiresAt int64) {
this.itemsMap[itemId] = expiresAt
}
func (this *List) Remove(itemId int64) {
func (this *List) Remove(itemId uint64) {
this.locker.Lock()
defer this.locker.Unlock()
this.removeItem(itemId)
}
func (this *List) GC(timestamp int64, callback func(itemId int64)) {
func (this *List) GC(timestamp int64) ItemMap {
if this.lastTimestamp > timestamp+1 {
return nil
}
this.locker.Lock()
var itemMap = this.gcItems(timestamp)
if len(itemMap) == 0 {
this.locker.Unlock()
return
return itemMap
}
this.locker.Unlock()
if callback != nil {
if this.gcCallback != nil {
for itemId := range itemMap {
callback(itemId)
this.gcCallback(itemId)
}
}
if this.gcBatchCallback != nil {
this.gcBatchCallback(itemMap)
}
return itemMap
}
func (this *List) OnGC(callback func(itemId int64)) *List {
func (this *List) Clean() {
this.locker.Lock()
this.itemsMap = map[uint64]int64{}
this.expireMap = map[int64]ItemMap{}
this.locker.Unlock()
}
func (this *List) Count() int {
this.locker.Lock()
var count = len(this.itemsMap)
this.locker.Unlock()
return count
}
func (this *List) OnGC(callback func(itemId uint64)) *List {
this.gcCallback = callback
return this
}
func (this *List) removeItem(itemId int64) {
func (this *List) OnGCBatch(callback func(itemMap ItemMap)) *List {
this.gcBatchCallback = callback
return this
}
func (this *List) removeItem(itemId uint64) {
expiresAt, ok := this.itemsMap[itemId]
if !ok {
return