英文:
GO: How to save and retrieve a struct to redis using redigo
问题
我正在使用GO语言,尝试在Redis中保存和检索结构体数组。我该如何实现呢?
我有以下结构体:
type Resource struct {
title string
}
我正在使用以下代码保存资源:
_, err := redigo.Do("lpush", <unique id>, <resource object>);
那么我该如何从Redis中检索结构体对象的数组呢?
英文:
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.
答案1
得分: 14
由于您要来回传输代码,我建议您使用@Not_a_Golfer的解决方案。
以下是一个示例:
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}
// 使用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}
//进行Redis事务...
}
//检索Redis实例中存储的任何值...
var deserialized Emotions
err = json.Unmarshal(serialized, &deserialized)
if err == nil {
fmt.Println("deserialized data: ", deserialized.Sad)
//deserialized data: true
}
}
至于如何在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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论