Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save generic struct to redis

Tags:

redis

go

while writing a golang webserver I had to use some sort of cache so i chose redis. I had the need for some sort of function that takes any structure and saves it as is to redis as a value. Is there any way to do this without using the interface{} as a receiving parameter or repeating myself too much and still staying type safe?

like image 767
Max Avatar asked Dec 09 '18 22:12

Max


People also ask

Can we store object in Redis?

Object Storing Procedure. In the Redis, Everything can be stored as only key-value pair format. Key must be unique and storing an object in a string format is not a good practice anyway. Objects are usually stored in a binary array format in the databases.

Does Redis allow duplicate keys?

You can use the DUMP and RESTORE commands to duplicate the key: use the DUMP command to serialize the value of a key. use the RESTORE command to restore the serialized value to another key.

What is the recommended size for Redis keys?

The maximum allowed key size is 512 MB.


1 Answers

Encode the struct value to a []byte using the gob, json or similar encoding package. Store the []byte in Redis. Reverse the process when fetching the data.

Assuming a Redis client with methods for Set and Get, the code using the JSON package will look something like this:

func set(c *RedisClient, key string, value interface{}) error {
    p, err := json.Marshal(value)
    if err != nil {
       return err
    }
    return c.Set(key, p)
}

func get(c *RedisClient, key string, dest interface{}) error {
    p, err := c.Get(key)
    if err != nil {
       return err
    }
    return json.Unmarshal(p, dest)
}

Use it like this to save a value:

var v someType
if err := set(c, key, v); err != nil {
     // handle error
}

and like this to retrieve a value. Note that a pointer to the value is passed to get.

var v someType
if err := get(c, key, &v); err != nil {
     // handle error
}

The details will need to adjusted depending on the Redis client that you are using.

This approach avoids repetition and is type safe as long as the application sets and gets values for a given key using the same type.

like image 71
Bayta Darell Avatar answered Oct 19 '22 00:10

Bayta Darell