Add support of deadline (TTL) for values in Cache

This commit is contained in:
ChronosX88 2021-05-14 21:21:13 +03:00
parent 7e3fca5de5
commit 59aa9f5889
Signed by: ChronosXYZ
GPG Key ID: 085A69A82C8C511A
3 changed files with 23 additions and 1 deletions

6
cache/cache.go vendored
View File

@ -1,11 +1,15 @@
package cache
import "errors"
import (
"errors"
"time"
)
var ErrNilValue = errors.New("value is empty")
type Cache interface {
Store(key string, value interface{}) error
StoreWithTTL(key string, value interface{}, ttl time.Duration) error
Get(key string, value interface{}) error
Delete(key string)
}

View File

@ -1,6 +1,8 @@
package cache
import (
"time"
"github.com/VictoriaMetrics/fastcache"
"github.com/fxamacker/cbor/v2"
)
@ -31,6 +33,10 @@ func (imc *InMemoryCache) Store(key string, value interface{}) error {
return nil
}
func (imc *InMemoryCache) StoreWithTTL(key string, value interface{}, ttl time.Duration) error {
return imc.Store(key, value) // fastcache doesn't support ttl for values
}
func (imc *InMemoryCache) Get(key string, v interface{}) error {
data := make([]byte, 0)
imc.cache.GetBig(data, []byte(key))

12
cache/redis_cache.go vendored
View File

@ -2,6 +2,7 @@ package cache
import (
"context"
"time"
"github.com/Secured-Finance/dione/config"
"github.com/fxamacker/cbor/v2"
@ -37,6 +38,17 @@ func (rc *RedisCache) Store(key string, value interface{}) error {
return nil
}
func (rc *RedisCache) StoreWithTTL(key string, value interface{}, ttl time.Duration) error {
mRes, err := cbor.Marshal(value)
if err != nil {
return err
}
rc.Client.Set(rc.ctx, key, mRes, ttl)
return nil
}
func (rc *RedisCache) Get(key string, value interface{}) error {
data, err := rc.Client.Get(rc.ctx, key).Bytes()
if err != nil {