如何使用 redigo 将地图保存并检索到 redis 中?

我有一张这样的地图,我想使用 redigo 从 redis 中保存/检索它:


animals := map[string]bool{

    "cat": true,

    "dog":   false,

    "fox": true,

}

地图的长度可能会有所不同。


我尝试了这些功能:


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

}

但无法GetHash正确制作。我检查了文档示例,但没有帮助。因此,感谢您对提供工作示例的帮助。


慕莱坞森
浏览 169回答 2
2回答

30秒到达战场

HMSET已弃用,请HSET改用,但在这里没有效果。map[string]bool可以用forAddFlat()展平SetHash()。c.Do("HSET", redis.Args{}.Add("key").AddFlat(value)...)对于GetHash(),使用Values()。您可以使用ScanStruct()映射到结构或遍历值以动态创建映射。v, err := redis.Values(c.Do("HGETALL", key)) redis.ScanStruct(v, &myStruct);请参阅 scan_test.go 中redigo测试的示例。

慕工程0101907

应用程序负责将结构化类型与 Redis 理解的类型相互转换。将地图展平为参数列表:func SetHash(key string, value map[string]bool) error {&nbsp; &nbsp; conn := Pool.Get()&nbsp; &nbsp; defer conn.Close()&nbsp; &nbsp; // Create arguments: key field value [field value]...&nbsp; &nbsp; var args = []interface{}{key}&nbsp; &nbsp; for k, v := range value {&nbsp; &nbsp; &nbsp; &nbsp; args = append(args, k, v)&nbsp; &nbsp; }&nbsp; &nbsp; _, err := conn.Do("HMSET", args...)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return fmt.Errorf("error setting key %s to %v: %v", key, value, err)&nbsp; &nbsp; }&nbsp; &nbsp; return err}将返回的字段值对转换为映射:func GetHash(key string) (map[string]bool, error) {&nbsp; &nbsp; conn := Pool.Get()&nbsp; &nbsp; defer conn.Close()&nbsp; &nbsp; values, err := redis.Strings(conn.Do("HGETALL", key))&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // Loop through [field value]... and parse value as bool.&nbsp; &nbsp; m := map[string]bool{}&nbsp; &nbsp; for i := 0; i < len(values); i += 2 {&nbsp; &nbsp; &nbsp; &nbsp; b, err := strconv.ParseBool(value)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return nil, errors.New("value not a bool")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; m[key] = b&nbsp; &nbsp; }&nbsp; &nbsp; return m, nil}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go