MSP-437 implement simple cache
This commit is contained in:
1 parent
ed77144fdf
commit
bd4b52e5cc
2 files changed
+100
No files matched your search
Vendored
+53
@@ -0,0 +1,53 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Item struct {
|
||||
data []byte
|
||||
expiredAt time.Time
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
store map[string]Item
|
||||
lock *sync.RWMutex
|
||||
}
|
||||
|
||||
func New() *Cache {
|
||||
return &Cache{
|
||||
store: map[string]Item{},
|
||||
lock: &sync.RWMutex{},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) Get(key string) ([]byte, bool) {
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
|
||||
item, ok := c.store[key]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if c.now().After(item.expiredAt) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return item.data, true
|
||||
}
|
||||
|
||||
func (c *Cache) Set(key string, data []byte, lifeTime time.Duration) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
c.store[key] = Item{
|
||||
data: data,
|
||||
expiredAt: c.now().Add(lifeTime),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) now() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
Vendored
+47
@@ -0,0 +1,47 @@
|
||||
package cache_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"isp-gate-service/cache"
|
||||
)
|
||||
|
||||
func TestGetBasic(t *testing.T) {
|
||||
require := require.New(t)
|
||||
|
||||
cache := cache.New()
|
||||
cache.Set("key", []byte("data"), 24*time.Hour)
|
||||
|
||||
data, ok := cache.Get("key")
|
||||
require.True(ok)
|
||||
require.EqualValues("data", data)
|
||||
|
||||
_, ok = cache.Get("key2")
|
||||
require.False(ok)
|
||||
}
|
||||
|
||||
func TestGetExpired(t *testing.T) {
|
||||
require := require.New(t)
|
||||
|
||||
cache := cache.New()
|
||||
cache.Set("key", []byte("data"), 500*time.Millisecond)
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
data, ok := cache.Get("key")
|
||||
require.False(ok)
|
||||
require.Nil(data)
|
||||
}
|
||||
|
||||
func TestNilValue(t *testing.T) {
|
||||
require := require.New(t)
|
||||
|
||||
cache := cache.New()
|
||||
cache.Set("key", nil, 24*time.Hour)
|
||||
|
||||
data, ok := cache.Get("key")
|
||||
require.True(ok)
|
||||
require.Nil(data)
|
||||
}
|
||||
Reference in new issue
Block a user