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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格