From 71366828f494320a7b0db5a2e61d25fcf2d74e05 Mon Sep 17 00:00:00 2001 From: douxu Date: Wed, 17 Sep 2025 16:41:30 +0800 Subject: [PATCH] add real time cache --- real-time-data/real_time_cache.go | 48 +++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 real-time-data/real_time_cache.go diff --git a/real-time-data/real_time_cache.go b/real-time-data/real_time_cache.go new file mode 100644 index 0000000..eaa3a4b --- /dev/null +++ b/real-time-data/real_time_cache.go @@ -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) +}