去redis HMSet失败

huangapple go评论85阅读模式
英文:

go redis HMSet fail

问题

当我在Go中使用redis hmset时,我遇到了以下问题,为什么会这样呢?
ERR wrong number of arguments for 'hset' command
导致值没有存储在redis中?
我参考了redis书籍,为什么会出现这个问题?

func (r *ArticleRepo) PostArticle(user, title, link string) string {
	articleId := strconv.Itoa(int(r.Conn.Incr("article:").Val()))

	voted := "voted:" + articleId
	r.Conn.SAdd(voted, user)
	r.Conn.Expire(voted, common.OneWeekInSeconds*time.Second)

	now := time.Now().Unix()
	article := "article:" + articleId
	_, err := r.Conn.HMSet(article, map[string]interface{}{
		"title":  title,
		"link":   link,
		"poster": user,
		"time":   now,
		"votes":  1,
	}).Result()
	if err != nil {
		fmt.Println(err)
	}

	r.Conn.ZAdd("score:", &redis.Z{Score: float64(now + common.VoteScore), Member: article})
	r.Conn.ZAdd("time:", &redis.Z{Score: float64(now), Member: article})
	return articleId
}
英文:

When I use redis hmset in Go I get the following problem, why is it?
ERR wrong number of arguments for 'hset' command
Resulting in values not being stored in redis ?
I'm referring to the redis book, why is this a problem ?

func (r *ArticleRepo) PostArticle(user, title, link string) string {
	articleId := strconv.Itoa(int(r.Conn.Incr("article:").Val()))

	voted := "voted:" + articleId
	r.Conn.SAdd(voted, user)
	r.Conn.Expire(voted, common.OneWeekInSeconds*time.Second)

	now := time.Now().Unix()
	article := "article:" + articleId
	_, err := r.Conn.HMSet(article, map[string]interface{}{
		"title":  title,
		"link":   link,
		"poster": user,
		"time":   now,
		"votes":  1,
	}).Result()
	if err != nil {
		fmt.Println(err)
	}

	r.Conn.ZAdd("score:", &redis.Z{Score: float64(now + common.VoteScore), Member: article})
	r.Conn.ZAdd("time:", &redis.Z{Score: float64(now), Member: article})
	return articleId
}

答案1

得分: 1

你可以在Go中使用hset代替hmset,类似这样的方式:

_, err := r.Conn.Do("hset", article, map[string]interface{}{
    "title":  title,
    "link":   link,
    "poster": user,
    "time":   now,
    "votes":  1,
}).Result()
英文:

You can use hset instead of hmset with something like this in Go:

 _, err := r.Conn.Do("hset", article, map[string]interface{}{
    "title":  title,
    "link":   link,
    "poster": user,
    "time":   now,
    "votes":  1,
}).Result()

huangapple
  • 本文由 发表于 2021年11月2日 16:02:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/69807034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定