我正在尝试使用HMSET设置包含两个字符串字段hashid的新content

我可以使用redis-cli轻松初始化id的计数器,然后通过SET i 0进行设置,然后使用HMSET test id hey content herro创建新的哈希,并使用HMGET test id content获取这两个字段,从而生成1) hey 2) herro

不幸的是,我不能使用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()。我得到:



我真的不知道为什么,因为我设法使它在redis-cli中以相同的方式工作。
HMSet定义为func (c *Client) HMSet(key string, fields map[string]interface{}) *StatusCmd

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

我在做什么错了?

最佳答案

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

您得到的错误只是在拒绝字符串上的HMSET而已,这是无效的操作。

顺便说一句,另一种方法将起作用-在redis中的任何类型上调用SET只会写一个字符串而不是该值,所以要小心。

07-28 04:02