我正在尝试使用 HMSET设置包含两个字符串字段 id
和 content
的新 hash
。
我可以通过 redis-cli
轻松地使用 SET i 0
初始化 ids 计数器,然后使用 创建一个新的哈希值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()
。我得到:
WRONGTYPE Operation against a key holding the wrong kind of value
我真的不明白为什么,因为我设法让它在 redis-cli
中以同样的方式工作。
HMSet
定义为 func (c *Client) HMSet(key string, fields map[string]interface{}) *StatusCmd
。
我无法在网上找到任何使用 Go-Redis 来说明此用例的示例。
我做错了什么?
最佳答案
您正在两次访问同一个 key “i”
- 一次在调用 SET 时作为字符串,然后在调用 HMSET 时作为散列。
您收到的错误只是 redis 拒绝字符串上的 HMSET,这是一个无效的操作。
顺便说一句,相反的方法也可以 - 对 redis 中的任何类型调用 SET 只会写入一个字符串而不是该值,所以要小心。
关于带有字符串字段的 Go-Redis HMSet 给出了 WRONGTYPE 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43746853/