猿问

GO:如何使用 redigo 将结构保存和检索到 redis

我正在使用 GO 并尝试在 redis 中保存和检索结构数组。我该如何去实施它。


我有以下结构


type Resource struct {

   title string

}

并使用以下代码保存资源


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

现在如何从 redis 中检索结构对象数组。


海绵宝宝撒
浏览 139回答 1
1回答

明月笑刀无情

由于您要来回整理代码,我建议使用 @ Not_a_Golfer的解决方案。以下是您可以执行的操作的示例:package mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt")type Emotions struct {&nbsp; &nbsp; Sad&nbsp; &nbsp; &nbsp; bool&nbsp; &nbsp; Happy&nbsp; &nbsp; Happy&nbsp; &nbsp; Confused int}type Happy struct {&nbsp; &nbsp; Money&nbsp; int&nbsp; &nbsp; Moral&nbsp; bool&nbsp; &nbsp; Health bool}func main() {&nbsp; &nbsp; emo := &Emotions{Sad: true}&nbsp; &nbsp; // retain readability with json&nbsp; &nbsp; serialized, err := json.Marshal(emo)&nbsp; &nbsp; if err == nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("serialized data: ", string(serialized))//serialized data:&nbsp; {"Sad":true,"Happy":{"Money":0,"Moral":false,"Health":false},"Confused":0}&nbsp; &nbsp; &nbsp; &nbsp; //do redis transactions...&nbsp; &nbsp; }&nbsp; &nbsp; //retriving whatever value stored in your redis instance...&nbsp; &nbsp; var deserialized Emotions&nbsp; &nbsp; err = json.Unmarshal(serialized, &deserialized)&nbsp; &nbsp; if err == nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("deserialized data: ", deserialized.Sad)//deserialized data:&nbsp; true&nbsp; &nbsp; }}现在关于如何在 redis 上存储内容,这在很大程度上取决于您的数据。
随时随地看视频慕课网APP

相关分类

Go
我要回答