dongli4711 2019-09-03 18:41
浏览 145
已采纳

从Redis获取结构体数组时解组错误

I am using redigo to save some structs in redis. The thing is that for the same key I need to append new structs, but when I am trying to recover them I cannot unmarshal to an array.

Ie: (ignoring the errors intentionally)

type ADTO struct {
    Value string
}

func main() {
    pool := redis.Pool{
        Dial: func() (conn redis.Conn, e error) {
            return redis.Dial("tcp", "localhost:6379")
        },
        MaxIdle:   80,
        MaxActive: 12000,
    }

    conn := pool.Get()
    defer conn.Close()
    key := "some-key"
    defer conn.Do("DEL", key)

    a := ADTO{Value: "a"}
    bytes, _ := json.Marshal(a)
    conn.Do("APPEND", key, bytes)

    b := ADTO{Value: "b"}
    bytes, _ = json.Marshal(b)
    conn.Do("APPEND", key, bytes)

    c := ADTO{Value: "c"}
    bytes, _ = json.Marshal(c)
    conn.Do("APPEND", key, bytes)

    bytes, _ = redis.Bytes(conn.Do("GET", key))

    adtos := make([]ADTO, 0)

    // the following does not work
    if err := json.Unmarshal(bytes, &adtos); err != nil {
        return
    }
}

If I only append a single struct and retrieving it, then it is working fine

I have tried with redis.ByteSlices with no luck

  • 写回答

1条回答 默认 最新

  • doude2635 2019-09-03 18:50
    关注

    APPEND will only append to a string, it will not make a JSON array. After first insert, you'll have

    {"Value":"a"}
    

    Then after the second one, you'll have

    {"Value":"a"}{"Value":"b"}
    

    That's not a JSON array.

    You can try using json.Decoder, and do something like:

    b, _ = redis.Bytes(conn.Do("GET", key))
    dec := json.NewDecoder(bytes.NewReader(b))
    items := []ADTO{}
    var x ADTO
    for dec.Decode(&x) == nil {
      items = append(items, x)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿