go redis存储结构体
时间: 2023-07-23 16:55:47 浏览: 263
在 Go 中使用 Redis 存储结构体可以使用以下两种方法:
1. 使用 JSON 序列化
将结构体序列化为 JSON 字符串,再存储到 Redis 中。这种方法比较简单,但是会增加存储空间和序列化/反序列化的时间。
```go
import (
"encoding/json"
"github.com/go-redis/redis"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
user := &User{Name: "Alice", Age: 20}
jsonString, err := json.Marshal(user)
if err != nil {
panic(err)
}
err = client.Set("user:1", jsonString, 0).Err()
if err != nil {
panic(err)
}
jsonString, err = client.Get("user:1").Bytes()
if err != nil {
panic(err)
}
var newUser User
err = json.Unmarshal(jsonString, &newUser)
if err != nil {
panic(err)
}
fmt.Println(newUser.Name, newUser.Age) // Output: Alice 20
}
```
2. 使用 Redis Hash
将结构体的每个字段存储到 Redis Hash 中。这种方法比较灵活,可以对每个字段进行单独的操作,但是需要手动处理序列化和反序列化。
```go
import (
"encoding/json"
"github.com/go-redis/redis"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
user := &User{Name: "Alice", Age: 20}
userMap := map[string]interface{}{
"name": user.Name,
"age": user.Age,
}
err := client.HMSet("user:1", userMap).Err()
if err != nil {
panic(err)
}
resultMap, err := client.HGetAll("user:1").Result()
if err != nil {
panic(err)
}
var newUser User
jsonString, err := json.Marshal(resultMap)
if err != nil {
panic(err)
}
err = json.Unmarshal(jsonString, &newUser)
if err != nil {
panic(err)
}
fmt.Println(newUser.Name, newUser.Age) // Output: Alice 20
}
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)