正文
public
String
postArticle
(Jedis conn, String user, String title, String link)
{
String articleId = String.valueOf(conn.incr(
"article:"
));
String voted =
"voted:"
+ articleId;
conn.sadd(voted, user);
conn.expire(voted, ONE_WEEK_IN_SECONDS);
long
now = System.currentTimeMillis() /
1000
;
String article =
"article:"
+ articleId;
HashMap<String,String> articleData =
new
HashMap<String,String>();
articleData.put(
"title"
, title);
articleData.put(
"link"
, link);
articleData.put(
"user"
, user);
articleData.put(
"now"
, String.valueOf(now));
articleData.put(
"oppose"
,
"0"
);
articleData.put(
"votes"
,
"1"
);
conn.hmset(article, articleData);
conn.zadd(
"score:"
, now + VOTE_SCORE, article);
conn.zadd(
"time:"
, now, article);
return
articleId;
}
}
2.当用户尝试对一篇文章进行投票时,
(1)用ZSCORE命令检查记录文章发布时间的有序集合(redis设计2),判断文章的发布时间是否未超过一周。
(2)如果文章仍然处于可以投票的时间范畴,那么用SADD将用户添加到记录文章已投票用户名单的集合(redis设计4)中。
(3)如果上一步操作成功,那么说明用户是第一次对这篇文章进行投票,那么使用ZINCRBY命令为文章的评分增加432(ZINCRBY命令用于对有序集合成员的分值执行自增操作);
并使用HINCRBY命令对散列记录的文章投票数量进行更新
public void articleVote(Jedis conn, String user, String article) {
long cutoff = (System.currentTimeMillis() / 1000) - ONE_WEEK_IN_SECONDS;
if (conn.zscore("time:", article) < cutoff){
return;
}