mirror of
https://github.com/cgrates/cgrates.git
synced 2026-02-11 18:16:24 +05:00
cache improvements
This commit is contained in:
@@ -13,10 +13,6 @@ type Cache struct {
|
||||
// an item is evicted. Zero means no limit.
|
||||
maxEntries int
|
||||
|
||||
// OnEvicted optionally specificies a callback function to be
|
||||
// executed when an entry is purged from the cache.
|
||||
OnEvicted func(key string, value interface{})
|
||||
|
||||
lruIndex *list.List
|
||||
ttlIndex []*list.Element
|
||||
cache map[string]*list.Element
|
||||
@@ -37,10 +33,10 @@ func NewLRUTTL(maxEntries int, expire time.Duration) *Cache {
|
||||
maxEntries: maxEntries,
|
||||
expiration: expire,
|
||||
lruIndex: list.New(),
|
||||
ttlIndex: make([]*list.Element, 0),
|
||||
cache: make(map[string]*list.Element),
|
||||
}
|
||||
if c.expiration > 0 {
|
||||
c.ttlIndex = make([]*list.Element, 0)
|
||||
go c.cleanExpired()
|
||||
}
|
||||
return c
|
||||
@@ -75,7 +71,9 @@ func (c *Cache) Set(key string, value interface{}) {
|
||||
if c.cache == nil {
|
||||
c.cache = make(map[string]*list.Element)
|
||||
c.lruIndex = list.New()
|
||||
c.ttlIndex = make([]*list.Element, 0)
|
||||
if c.expiration > 0 {
|
||||
c.ttlIndex = make([]*list.Element, 0)
|
||||
}
|
||||
}
|
||||
|
||||
if e, ok := c.cache[key]; ok {
|
||||
@@ -89,7 +87,9 @@ func (c *Cache) Set(key string, value interface{}) {
|
||||
return
|
||||
}
|
||||
e := c.lruIndex.PushFront(&entry{key: key, value: value, timestamp: time.Now()})
|
||||
c.ttlIndex = append(c.ttlIndex, e)
|
||||
if c.expiration > 0 {
|
||||
c.ttlIndex = append(c.ttlIndex, e)
|
||||
}
|
||||
c.cache[key] = e
|
||||
c.mu.Unlock()
|
||||
|
||||
@@ -107,7 +107,7 @@ func (c *Cache) Get(key string) (value interface{}, ok bool) {
|
||||
}
|
||||
if e, hit := c.cache[key]; hit {
|
||||
c.lruIndex.MoveToFront(e)
|
||||
e.Value.(*entry).timestamp = time.Now()
|
||||
//e.Value.(*entry).timestamp = time.Now() don't update the timestamp on get'
|
||||
return e.Value.(*entry).value, true
|
||||
}
|
||||
return
|
||||
@@ -153,9 +153,6 @@ func (c *Cache) removeElement(e *list.Element) {
|
||||
}
|
||||
kv := e.Value.(*entry)
|
||||
delete(c.cache, kv.key)
|
||||
if c.OnEvicted != nil {
|
||||
c.OnEvicted(kv.key, kv.value)
|
||||
}
|
||||
}
|
||||
|
||||
// Len returns the number of items in the cache.
|
||||
@@ -173,6 +170,8 @@ func (c *Cache) Flush() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.lruIndex = list.New()
|
||||
c.ttlIndex = make([]*list.Element, 0)
|
||||
if c.expiration > 0 {
|
||||
c.ttlIndex = make([]*list.Element, 0)
|
||||
}
|
||||
c.cache = make(map[string]*list.Element)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user