2021-05-13 11:49:38 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
2021-05-14 18:21:13 +00:00
|
|
|
"time"
|
|
|
|
|
2021-05-27 19:30:11 +00:00
|
|
|
"github.com/patrickmn/go-cache"
|
2021-05-13 11:49:38 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2021-05-27 19:30:11 +00:00
|
|
|
DefaultCacheExpiration = 5 * time.Minute
|
|
|
|
DefaultGCInterval = 10 * time.Minute
|
2021-05-13 11:49:38 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type InMemoryCache struct {
|
2021-05-27 19:30:11 +00:00
|
|
|
cache *cache.Cache
|
2021-05-13 11:49:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewInMemoryCache() *InMemoryCache {
|
|
|
|
return &InMemoryCache{
|
2021-05-27 19:30:11 +00:00
|
|
|
cache: cache.New(DefaultCacheExpiration, DefaultGCInterval),
|
2021-05-13 11:49:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (imc *InMemoryCache) Store(key string, value interface{}) error {
|
2021-05-27 19:30:11 +00:00
|
|
|
imc.cache.Set(key, value, cache.NoExpiration)
|
2021-05-13 11:49:38 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-05-14 18:21:13 +00:00
|
|
|
func (imc *InMemoryCache) StoreWithTTL(key string, value interface{}, ttl time.Duration) error {
|
2021-05-27 19:30:11 +00:00
|
|
|
imc.cache.Set(key, value, ttl)
|
|
|
|
return nil
|
2021-05-14 18:21:13 +00:00
|
|
|
}
|
|
|
|
|
2021-05-27 19:30:11 +00:00
|
|
|
func (imc *InMemoryCache) Get(key string, value interface{}) error {
|
|
|
|
v, exists := imc.cache.Get(key)
|
|
|
|
if !exists {
|
2021-05-13 11:49:38 +00:00
|
|
|
return ErrNilValue
|
|
|
|
}
|
2021-05-27 19:30:11 +00:00
|
|
|
value = v
|
2021-05-13 11:49:38 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (imc *InMemoryCache) Delete(key string) {
|
2021-05-27 19:30:11 +00:00
|
|
|
imc.cache.Delete(key)
|
2021-05-13 11:49:38 +00:00
|
|
|
}
|