[英]How can I save and retrieve a map into redis using redigo?
I have a map like this, which I want to save/retrive from redis using redigo:我有一个这样的地图,我想使用 redigo 从 redis 保存/检索它:
animals := map[string]bool{
"cat": true,
"dog": false,
"fox": true,
}
The length of the map may vary.地图的长度可能会有所不同。
I tried these function:我试过这些功能:
func SetHash(key string, value map[string]bool) error {
conn := Pool.Get()
defer conn.Close()
_, err := conn.Do("HMSET", key, value)
if err != nil {
return fmt.Errorf("error setting key %s to %s: %v", key, value, err)
}
return err
}
func GetHash(key string) (map[string]bool, error) {
conn := Pool.Get()
defer conn.Close()
val, err := conn.Do("HGETALL", key)
if err != nil {
fmt.Errorf("error setting key %s to %s: %v", key, nil, err)
return nil, err
}
return val, err
}
But can not make GetHash
correctly.但是不能正确制作
GetHash
。 I've checked thedocs examples and it was not helpful.我检查了文档示例,但没有帮助。 So appreciate your help to have a working example.
因此,感谢您提供一个有效示例的帮助。
HMSET
is deprecated, use HSET
instead, no effect here though. HMSET
已过时,使用HSET
相反,这里没有任何影响,但。
The map[string]bool
may be flattened with AddFlat()
for SetHash()
. map[string]bool
可以用AddFlat()
for SetHash()
。
c.Do("HSET", redis.Args{}.Add("key").AddFlat(value)...)
For GetHash()
, use Values()
.对于
GetHash()
,使用Values()
。 You may use ScanStruct()
to map to a struct or loop through the values to create a map dynamically.您可以使用
ScanStruct()
映射到结构或循环访问值以动态创建映射。
v, err := redis.Values(c.Do("HGETALL", key))
redis.ScanStruct(v, &myStruct);
See example from redigo tests in scan_test.go .请参阅 scan_test.go 中 redigo 测试的示例。
The application is responsible for converting structured types to and from the types understood by Redis.应用程序负责将结构化类型与 Redis 理解的类型相互转换。
Flatten the map into a list of arguments:将地图展平为参数列表:
func SetHash(key string, value map[string]bool) error {
conn := Pool.Get()
defer conn.Close()
// Create arguments: key field value [field value]...
var args = []interface{}{key}
for k, v := range value {
args = append(args, k, v)
}
_, err := conn.Do("HMSET", args...)
if err != nil {
return fmt.Errorf("error setting key %s to %v: %v", key, value, err)
}
return err
}
Convert the returned field value pairs to a map:将返回的字段值对转换为映射:
func GetHash(key string) (map[string]bool, error) {
conn := Pool.Get()
defer conn.Close()
values, err := redis.Strings(conn.Do("HGETALL", key))
if err != nil {
return nil, err
}
// Loop through [field value]... and parse value as bool.
m := map[string]bool{}
for i := 0; i < len(values); i += 2 {
b, err := strconv.ParseBool(value)
if err != nil {
return nil, errors.New("value not a bool")
}
m[key] = b
}
return m, nil
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.