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

报告相同问题?

悬赏问题

  • ¥20 matlab如何绘制三维瀑布图
  • ¥15 关于用abap来解决动态规划的问题,但是要求输出索引值,这个是难点
  • ¥15 在ISIS中什么是IP从地址
  • ¥15 压测时,并发量过高时,响应时间出现尖刺
  • ¥15 关于vmprotect3.8.4虚拟文件一项
  • ¥15 在不用IT调试的情况下怎样能连外网
  • ¥20 C#调用虚拟键盘TabTip.exe
  • ¥15 Qt4代码实现下面的界面
  • ¥15 CCS离散化传递函数与仿真不一致
  • ¥15 prism提示我reinstall prism 如何解决