josiahcarlson / redis-in-action

Example code from the book

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Go HMSet method fail

zqm971210 opened this issue · comments

commented

redis_version:3.0.504
When I run Goland Chapter01 redisConn_test.go
I checked redis and found that the results were not stored in redis
I change the code get the following error

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
}

ERR wrong number of arguments for 'hset' command

I have made the following changes to store the results in 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
	ret := map[string]interface{}{
		"title":  title,
		"link":   link,
		"poster": user,
		"time":   now,
		"votes":  1,
	}
	for key, value := range ret {
		r.Conn.HSet(article, key, value)
	}

	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
}