duangang4001
duangang4001
2017-05-02 20:40

带字符串字段的Go-Redis HMSet提供WRONGTYPE操作

已采纳

I'm trying to use HMSET to set a new hash containing two string fields, id and content.

I'm able to make this via redis-cli pretty easily using SET i 0 to initialize a counter for ids, then creating a new hash using HMSET test id hey content herro and getting both of these fields with HMGET test id content resulting in 1) hey 2) herro.

Unfortunately I'm not able to achieve such result with Go-Redis and in particular with HMSet.

So far I tried

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)

Everything works fine but c.HMSet("i", m).Result(). I get:

WRONGTYPE Operation against a key holding the wrong kind of value

And I cannot really get why since I managed to make it work on the very same way in redis-cli.

HMSet is defined as func (c *Client) HMSet(key string, fields map[string]interface{}) *StatusCmd.

I wasn't able to find any example online using Go-Redis illustrating this use case.

What Am I doing Wrong?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongsao8279 dongsao8279 4年前

    You are accessing the same key "i" twice - once as a string when calling SET, and then as a hash when calling HMSET.

    The error you are getting is just redis denying HMSET on a string, which is an invalid operation.

    BTW the other way around will work - calling SET on any type in redis will just write a string instead of that value, so be careful.

    点赞 评论 复制链接分享