Files
EdgeNode/internal/ttlcache/piece.go

109 lines
1.9 KiB
Go
Raw Normal View History

2020-11-21 21:43:03 +08:00
package ttlcache
import (
"github.com/TeaOSLab/EdgeNode/internal/utils"
2020-11-22 12:11:39 +08:00
"github.com/iwind/TeaGo/types"
"sync"
"time"
)
type Piece struct {
2020-11-21 21:43:03 +08:00
m map[uint64]*Item
maxItems int
2022-03-12 18:00:22 +08:00
locker sync.RWMutex
}
2020-11-21 21:43:03 +08:00
func NewPiece(maxItems int) *Piece {
return &Piece{m: map[uint64]*Item{}, maxItems: maxItems}
}
func (this *Piece) Add(key uint64, item *Item) (ok bool) {
this.locker.Lock()
2020-11-21 21:43:03 +08:00
if len(this.m) >= this.maxItems {
2021-12-22 16:43:16 +08:00
// 尝试先删除过期的
this.gcWithoutLocker()
// 仍然是满的就跳过
if len(this.m) >= this.maxItems {
this.locker.Unlock()
return
}
2020-11-21 21:43:03 +08:00
}
this.m[key] = item
this.locker.Unlock()
return true
}
2020-11-22 12:11:39 +08:00
func (this *Piece) IncreaseInt64(key uint64, delta int64, expiredAt int64) (result int64) {
this.locker.Lock()
item, ok := this.m[key]
2021-07-19 10:49:56 +08:00
if ok && item.expiredAt > time.Now().Unix() {
result = types.Int64(item.Value) + delta
2020-11-22 12:11:39 +08:00
item.Value = result
item.expiredAt = expiredAt
} else {
if len(this.m) < this.maxItems {
result = delta
this.m[key] = &Item{
Value: delta,
expiredAt: expiredAt,
}
}
}
this.locker.Unlock()
return
}
func (this *Piece) Delete(key uint64) {
this.locker.Lock()
delete(this.m, key)
this.locker.Unlock()
}
func (this *Piece) Read(key uint64) (item *Item) {
this.locker.RLock()
item = this.m[key]
if item != nil && item.expiredAt < utils.UnixTime() {
item = nil
}
this.locker.RUnlock()
return
}
func (this *Piece) Count() (count int) {
this.locker.RLock()
count = len(this.m)
this.locker.RUnlock()
return
}
func (this *Piece) GC() {
this.locker.Lock()
2021-12-22 16:43:16 +08:00
this.gcWithoutLocker()
this.locker.Unlock()
}
2020-11-22 12:11:39 +08:00
func (this *Piece) Clean() {
this.locker.Lock()
this.m = map[uint64]*Item{}
this.locker.Unlock()
}
2020-11-22 12:11:39 +08:00
func (this *Piece) Destroy() {
this.locker.Lock()
this.m = nil
this.locker.Unlock()
}
2021-12-22 16:43:16 +08:00
// 不加锁的gc
func (this *Piece) gcWithoutLocker() {
timestamp := time.Now().Unix()
for k, item := range this.m {
if item.expiredAt <= timestamp {
delete(this.m, k)
}
}
}