add real time cache
This commit is contained in:
parent
a9532debe9
commit
71366828f4
|
|
@ -0,0 +1,48 @@
|
|||
// Package realtimedata define real time data operation functions
|
||||
package realtimedata
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CacheItem define structure for caching real time data with calculation capabilities
|
||||
type CacheItem struct {
|
||||
key string
|
||||
value []any
|
||||
CalculatorFunc any
|
||||
LastAccessed time.Time
|
||||
}
|
||||
|
||||
// Reset defines a method to reset the CacheItem to its zero state
|
||||
func (ci *CacheItem) Reset() {
|
||||
ci.key = ""
|
||||
ci.value = nil
|
||||
ci.CalculatorFunc = nil
|
||||
ci.LastAccessed = time.Time{}
|
||||
}
|
||||
|
||||
// IsExpired defines a method to check if the cache item has expired based on a given TTL
|
||||
func (ci *CacheItem) IsExpired(ttl time.Duration) bool {
|
||||
return time.Since(ci.LastAccessed) > ttl
|
||||
}
|
||||
|
||||
// CachePool define sync.Pool for cache item objects to optimize memory usage and reduce allocations
|
||||
var CachePool = sync.Pool{
|
||||
New: func() any {
|
||||
return &CacheItem{}
|
||||
},
|
||||
}
|
||||
|
||||
// GetCacheItem define a method to get a cache item from the pool
|
||||
func GetCacheItem() *CacheItem {
|
||||
item := CachePool.Get().(*CacheItem)
|
||||
item.Reset()
|
||||
return item
|
||||
}
|
||||
|
||||
// PutCacheItem define a method to put a cache item back to the pool
|
||||
func PutCacheItem(item *CacheItem) {
|
||||
item.Reset()
|
||||
CachePool.Put(item)
|
||||
}
|
||||
Loading…
Reference in New Issue