From 11d4487abec7289fc176710246e1e73f0d758392 Mon Sep 17 00:00:00 2001 From: id Date: Fri, 22 May 2020 16:53:57 +0300 Subject: [PATCH] feat(cache): add cache stats --- .gitignore | 3 ++- cache.go | 16 +++++++++++++++- group.go | 18 +++++++++++++++++- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 723ef36..6e6b069 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -.idea \ No newline at end of file +.idea +go.sum \ No newline at end of file diff --git a/cache.go b/cache.go index 3238ab2..76c74ab 100644 --- a/cache.go +++ b/cache.go @@ -50,10 +50,24 @@ func NewSyncCacheClient(opts SyncCacheOpts) *SyncCacheClient { func (c *SyncCacheClient) AddCacheGroup(cacheGroupName string, getterFunc GetterFunc) { c.cacheGroupManager.Lock() - c.cacheGroupManager.cacheGroups[cacheGroupName] = NewCacheGroup(getterFunc) + c.cacheGroupManager.cacheGroups[cacheGroupName] = NewCacheGroup(cacheGroupName, getterFunc) c.cacheGroupManager.Unlock() } +func (c *SyncCacheClient) GetCacheGroup(cacheGroupName string) *CacheGroup { + c.cacheGroupManager.RUnlock() + g := c.cacheGroupManager.cacheGroups[cacheGroupName] + c.cacheGroupManager.RUnlock() + return g +} + +func (c *SyncCacheClient) GetCacheGroups() map[string]*CacheGroup { + c.cacheGroupManager.RUnlock() + g := c.cacheGroupManager.cacheGroups + c.cacheGroupManager.RUnlock() + return g +} + func (c *SyncCacheClient) RemoveCacheGroup(cacheGroupName string) { c.cacheGroupManager.Lock() delete(c.cacheGroupManager.cacheGroups, cacheGroupName) diff --git a/group.go b/group.go index e79e688..70090dc 100644 --- a/group.go +++ b/group.go @@ -8,6 +8,7 @@ type GetterFunc func(key string, setCacheFunc SetCacheFunc) error type SetCacheFunc func(i interface{}) type CacheGroup struct { + name string sync.RWMutex cache map[string]CacheEntity getterFunc GetterFunc @@ -18,13 +19,28 @@ type CacheEntity struct { object interface{} } -func NewCacheGroup(getterFunc GetterFunc) *CacheGroup { +type CacheStats struct { + Items int +} + +func NewCacheGroup(name string, getterFunc GetterFunc) *CacheGroup { return &CacheGroup{ + name: name, cache: make(map[string]CacheEntity, GroupCacheCapacity), getterFunc: getterFunc, } } +func (g *CacheGroup) Name() string { + return g.name +} + +func (g *CacheGroup) CacheStats() *CacheStats { + return &CacheStats{ + Items: len(g.cache), + } +} + func (g *CacheGroup) set(key string, i interface{}, uuid string) { g.Lock() g.cache[key] = CacheEntity{