简体   繁体   中英

Save generic struct to redis

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM