2021-05-13 11:49:38 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
2021-07-11 23:23:00 +00:00
|
|
|
"fmt"
|
|
|
|
"reflect"
|
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
|
|
|
}
|
|
|
|
|
2021-05-31 19:24:07 +00:00
|
|
|
func NewInMemoryCache() Cache {
|
2021-05-13 11:49:38 +00:00
|
|
|
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-27 19:30:52 +00:00
|
|
|
return ErrNotFound
|
2021-05-13 11:49:38 +00:00
|
|
|
}
|
2021-07-11 23:23:00 +00:00
|
|
|
reflectedValue := reflect.ValueOf(value)
|
|
|
|
if reflectedValue.Kind() != reflect.Ptr {
|
|
|
|
return fmt.Errorf("value isn't a pointer")
|
|
|
|
}
|
|
|
|
if reflectedValue.IsNil() {
|
|
|
|
reflectedValue.Set(reflect.New(reflectedValue.Type().Elem()))
|
|
|
|
}
|
|
|
|
reflectedValue.Elem().Set(reflect.ValueOf(v).Elem())
|
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
|
|
|
}
|
2021-05-31 19:24:07 +00:00
|
|
|
|
|
|
|
func (imc *InMemoryCache) Items() map[string]interface{} {
|
|
|
|
m := make(map[string]interface{})
|
|
|
|
for k, v := range imc.cache.Items() {
|
|
|
|
m[k] = v.Object
|
|
|
|
}
|
|
|
|
return m
|
|
|
|
}
|
2021-07-26 21:18:16 +00:00
|
|
|
|
|
|
|
func (imc *InMemoryCache) Exists(key string) bool {
|
|
|
|
_, exists := imc.cache.Get(key)
|
|
|
|
return exists
|
|
|
|
}
|