Use gob encoding for struct marshalling in redis cache

This commit is contained in:
ChronosX88 2021-05-27 22:30:52 +03:00
parent 3366a71ac1
commit 00b041fbb0
Signed by: ChronosXYZ
GPG Key ID: 085A69A82C8C511A
3 changed files with 28 additions and 15 deletions

2
cache/cache.go vendored
View File

@ -5,7 +5,7 @@ import (
"time"
)
var ErrNilValue = errors.New("value is empty")
var ErrNotFound = errors.New("key doesn't exist in cache")
type Cache interface {
Store(key string, value interface{}) error

View File

@ -35,7 +35,7 @@ func (imc *InMemoryCache) StoreWithTTL(key string, value interface{}, ttl time.D
func (imc *InMemoryCache) Get(key string, value interface{}) error {
v, exists := imc.cache.Get(key)
if !exists {
return ErrNilValue
return ErrNotFound
}
value = v

39
cache/redis_cache.go vendored
View File

@ -1,11 +1,13 @@
package cache
import (
"bytes"
"context"
"encoding/gob"
"errors"
"time"
"github.com/Secured-Finance/dione/config"
"github.com/fxamacker/cbor/v2"
"github.com/go-redis/redis/v8"
)
@ -28,41 +30,52 @@ func NewRedisCache(config *config.Config) *RedisCache {
}
func (rc *RedisCache) Store(key string, value interface{}) error {
mRes, err := cbor.Marshal(value)
data, err := gobMarshal(value)
if err != nil {
return err
}
rc.Client.Set(rc.ctx, key, mRes, 0)
rc.Client.Set(rc.ctx, key, data, 0)
return nil
}
func (rc *RedisCache) StoreWithTTL(key string, value interface{}, ttl time.Duration) error {
mRes, err := cbor.Marshal(value)
data, err := gobMarshal(value)
if err != nil {
return err
}
rc.Client.Set(rc.ctx, key, mRes, ttl)
rc.Client.Set(rc.ctx, key, data, ttl)
return nil
}
func gobMarshal(val interface{}) ([]byte, error) {
buf := bytes.NewBuffer(nil)
enc := gob.NewEncoder(buf)
err := enc.Encode(val)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func gobUnmarshal(data []byte, val interface{}) error {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
return dec.Decode(&val)
}
func (rc *RedisCache) Get(key string, value interface{}) error {
data, err := rc.Client.Get(rc.ctx, key).Bytes()
if err != nil {
if err == redis.Nil {
return ErrNilValue
if errors.Is(err, redis.Nil) {
return ErrNotFound
}
return err
}
err = cbor.Unmarshal(data, &value)
if err != nil {
return err
}
return nil
return gobUnmarshal(data, &value)
}
func (rc *RedisCache) Delete(key string) {