dsy19811981 2018-12-09 22:54
浏览 41
已采纳

将通用结构保存到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?

  • 写回答

1条回答 默认 最新

  • duanlushen8940 2018-12-09 23:12
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?