go-redis 读和存储json数组

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21057881/article/details/80892941

用go来驱动redis 存一个 key-value 键值对到redis里,其中value是一个json数组


package main

import (
    "encoding/json"
    "fmt"
    "github.com/garyburd/redigo/redis"
)

type RewardInfo struct {
    Type      uint32 `json:Type`
    Uin       uint64 `json:Uin`
    OrderId   string `json:OrderId`
    Username  string `json:Username`
    Desc      string `json:Desc`
    Cmoney    uint64 `json:Cmoney`
    ScriptId  uint32 `json:ScriptId`
    AuthorUin uint64 `json:AuthorUin`
}

func main() {
    c, err := redis.Dial("tcp", "127.0.0.1:6379")
    if err != nil {
        fmt.Println("Connect to redis error", err)
        return
    }
    defer c.Close()

    var tmp_data []*RewardInfo
    for i := 0; i < 10; i++ {
        tmp_data = append(tmp_data, &RewardInfo{
            Type:      1,
            Uin:       uint64(i),
            OrderId:   "1234567",
            Username:  "sbweijun",
            Desc:      "sb",
            Cmoney:    0,
            ScriptId:  uint32(1),
            AuthorUin: 123,
        })
    }
    data, _ := json.Marshal(tmp_data)
    _, err = c.Do("SET", "script_reward_01", data, "EX", 86400)
    if err != nil {
        fmt.Println(err)
    }
    t_data, err := redis.Bytes(c.Do("GET", "script_reward_01"))
    if t_data == nil || len(t_data) <= 0 {
        fmt.Println("check erroor")
        return
    }
    fmt.Println(t_data)

    var show_data []*RewardInfo
    err = json.Unmarshal(t_data, &show_data)
    if err != nil {
        fmt.Println(err)
    }
    //fmt.Println(fmt.Sprintf("%+v", show_data))

    for _, v := range show_data {
        fmt.Println(fmt.Sprintf("%+v", *v))
    }
}

展开阅读全文

没有更多推荐了,返回首页