Hello Redis - Voting on articles
Posted rsapaper
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hello Redis - Voting on articles相关的知识,希望对你有一定的参考价值。
Redis in Action JOSIAH L. CARLSON MANNING Shelter Island
1 ONE_WEEK_IN_SECONDS = 7 * 86400 2 VOTE_SCORE = 432 3 4 def article_vote(conn, user, article): 5 cutoff = time.time() - ONE_WEEK_IN_SECONDS 6 if conn.zscore(‘time:‘, article) < cutoff: 7 return 8 9 article_id = article.partition(‘:‘)[-1] 10 if conn.sadd(‘voted:‘ + article_id, user): 11 conn.zincrby(‘score:‘, article, VOTE_SCORE) 12 conn.hincrby(article, ‘votes‘, 1) 13 14 def post_article(conn, user, title, link): 15 article_id = str(conn.incr(‘article:‘)) 16 17 voted = ‘voted:‘ + article_id 18 conn.sadd(voted, user) 19 conn.expire(voted, ONE_WEEK_IN_SECONDS) 20 21 now = time.time() 22 article = ‘article:‘ + article_id 23 conn.hmset(article, { 24 ‘title‘: title, 25 ‘link‘: link, 26 ‘poster‘: user, 27 ‘timer‘: now, 28 ‘votes‘:1, 29 }) 30 31 conn.zadd(‘score:‘, article, now + VOTE_SCORE) 32 conn.zadd(‘time:‘, article, now) 33 34 return article_id 35 36 37 ARTICLES_PER_PAGE = 25 38 39 def get_articles(conn, page, order=‘score:‘): 40 start = (page-1) * ARTICLES_PER_PAGE 41 end = start + ARTICLES_PER_PAGE - 1 42 43 ids = conn.zrevrange(order, start, end) 44 articles = [] 45 for id in ids: 46 article_data = conn.hgetall(id) 47 article_data[‘id‘] = id 48 articles.append(article_data) 49 50 return articles
1 def add_remove_groups(conn, article_id, to_add=[], to_remove=[]): 2 article = ‘article:‘ + article_id 3 for group in to_add: 4 conn.sadd(‘group:‘ + group, article) 5 for group in to_remove: 6 conn.srem(‘group:‘ + group, article) 7 8 def get_group_articles(conn, group, page, order=‘score:‘): 9 key = order + group 10 if not conn.exists(key): 11 conn.zinterstore(key, 12 [‘group:‘ + group, order], 13 aggregate = ‘max‘, 14 ) 15 conn.expire(key, 60) 16 return get_articles(conn, page, key)
以上是关于Hello Redis - Voting on articles的主要内容,如果未能解决你的问题,请参考以下文章
算法-多数投票算法(Boyer-Moore Voting Algorithm)及推广
[Chapt1] Redis Install on linux
11g RAC OCR,VOTING DISK存储全部损坏,利用自动备份,恢复OCR,VOTING DISK到新存储。
[Chapt2] Python visit Redis based on HiRedis
Redis "MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on di