gpt4 book ai didi

带有字符串字段的 Go-Redis HMSet 给出了 WRONGTYPE 操作

转载 作者:IT王子 更新时间:2023-10-29 01:58:02 26 4
gpt4 key购买 nike

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

我可以通过 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 说明此用例的示例。

我做错了什么?

最佳答案

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

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

顺便说一句,另一种方法也行得通——在 Redis 中对任何类型调用 SET 只会写入一个字符串而不是该值,所以要小心。

关于带有字符串字段的 Go-Redis HMSet 给出了 WRONGTYPE 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43746853/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com