Save generic struct to redis
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.
Related videos on Youtube
Max
Updated on June 04, 2022Comments
-
Max almost 2 years
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? -
Sudhir Jonathan over 5 yearsConsider MessagePack as well. Gob is great in that it's super optimized and will work even with small changes in the struct, but you still need a destination struct in Go that's same/similar do your source. MessagePack works like JSON with overhead closer to Gob.
-
Amin Shojaei over 3 yearsThanks. It's fine. But i wish there was a way to use
redis hash
and store values side-by-side