如何使用redigo将结构体保存到redis并检索出来?

huangapple go评论89阅读模式
英文:

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(&quot;lpush&quot;, &lt;unique id&gt;, &lt;resource object&gt;);

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 (
	&quot;encoding/json&quot;
	&quot;fmt&quot;
)

type Emotions struct {
	Sad      bool
	Happy    Happy
	Confused int
}

type Happy struct {
	Money  int
	Moral  bool
	Health bool
}

func main() {

	emo := &amp;Emotions{Sad: true}

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

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

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

	var deserialized Emotions

	err = json.Unmarshal(serialized, &amp;deserialized)

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

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

huangapple
  • 本文由 发表于 2014年12月14日 18:37:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/27468458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定