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.

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

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等