简体   繁体   中英

GO: How to save and retrieve a struct to redis using redigo

i am using GO and trying to save and retrieve array of struct's in redis. How can i go about implementing it.

i have the following struct

type Resource struct {
   title string
}

and am saving the resources using the following code

_, err := redigo.Do("lpush", <unique id>, <resource object>);

now how can i retrieve the array of structure objects from redis.

Since you're going to marsal code back and forth, I'd suggest going with @ Not_a_Golfer 's solution.

Here is a sample of what you can do:

package main

import (
    "encoding/json"
    "fmt"
)

type Emotions struct {
    Sad      bool
    Happy    Happy
    Confused int
}

type Happy struct {
    Money  int
    Moral  bool
    Health bool
}

func main() {

    emo := &Emotions{Sad: true}

    // retain readability with json
    serialized, err := json.Marshal(emo)

    if err == nil {
        fmt.Println("serialized data: ", string(serialized))
//serialized data:  {"Sad":true,"Happy":{"Money":0,"Moral":false,"Health":false},"Confused":0}
        //do redis transactions...
    }

    //retriving whatever value stored in your redis instance...

    var deserialized Emotions

    err = json.Unmarshal(serialized, &deserialized)

    if err == nil {
        fmt.Println("deserialized data: ", deserialized.Sad)
//deserialized data:  true
    }
}

Now regarding how you should store things on redis, it depends pretty much on your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM