【问题标题】:Go-Redis HMSet with string fields gives WRONGTYPE Operation带有字符串字段的 Go-Redis HMSet 给出了 WRONGTYPE 操作
【发布时间】:2017-05-02 20:40:09
【问题描述】:

我正在尝试使用HMSET 设置一个新的hash,其中包含两个字符串字段idcontent

我可以很容易地通过redis-cli 完成此操作,使用SET i 0 为id 初始化一个计数器,然后使用HMSET test id hey content herro 创建一个新的哈希,并使用HMGET test id content 获取这两个字段,从而得到@987654331 @。

很遗憾,我无法使用 Go-Redis 获得这样的结果,尤其是使用 HMSet

到目前为止我尝试过

var uid = "0"
err = c.Get("i").Err()
if(err != nil) {
    //If the counter is not set, set it to 0
    err := c.Set("i", "0", 0).Err()
    if(err != nil){
        panic(err)
    }
} else {
    //Else, increment it
    counter, err := c.Incr("i").Result()
    //Cast it to string
    uid = strconv.FormatInt(index, 10)
    if(err != nil){
        panic(err)
    }
    //Set new counter
    err = c.Set("i", counter, 0).Err()
    if( err!= nil ){
        panic(err)
    }
}

//Init a map[string]interface{}
var m = make(map[string]interface{})
m["id"] = uid
m["content"] = "herro"

hash, err := c.HMSet("i", m).Result()
if(err != nil){
    panic(err)
}

fmt.Println(hash)

一切正常,但c.HMSet("i", m).Result()。我明白了:

WRONGTYPE 对持有错误值的键的操作

我真的不明白为什么,因为我设法让它在 redis-cli 中以同样的方式工作。

HMSet 定义为func (c *Client) HMSet(key string, fields map[string]interface{}) *StatusCmd

我无法在网上找到任何使用 Go-Redis 来说明此用例的示例。

我做错了什么?

【问题讨论】:

    标签: go hash redis


    【解决方案1】:

    您正在访问同一个键 "i" 两次 - 一次在调用 SET 时作为字符串,然后在调用 HMSET 时作为哈希。

    你得到的错误只是 redis 在字符串上拒绝 HMSET,这是一个无效的操作。

    顺便说一句,反过来也可以——在 redis 中对任何类型调用 SET 只会写入一个字符串而不是那个值,所以要小心。

    【讨论】:

    • 哦,是的,我真的没有真正注意到这一点。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    相关资源
    最近更新 更多