1. 程式人生 > >Redis之網站文章投票

Redis之網站文章投票

blog cnblogs cut color nbsp pos redis 用戶 tle

直接上代碼:

# python3
# -*- coding: utf-8 -*-

import redis
import time

ONE_WEEK_IN_SECONDS = 7 * 86400
# 如果一篇文章獲得200個贊,那麽這篇文章就是有趣的
VOTE_SCORE = 86400 / 200

def redis_init(redis):
    # article_time記錄文章發布時間
    redis.zadd(article_time, article_100408=1496662197, article_100635=1496669721, article_100716=1496660089)
    
# article_score記錄文章得分 redis.zadd(article_score, article_100408=1496666517, article_100635=1496670153, article_100716=1496665705) # voted_article_id記錄編號為article_id的文章的點贊用戶集合 redis.sadd(voted_100408, user_234487, user_253378, user_364680, user_132097, user_350917) # 用hash描述每篇文章
article_desc = {title:kunlun, link:www.kunlun.com, poster:fengge, time:1441728000, votes:523} redis.hmset(article_100408, article_desc) article_desc = {title: zhuxian, link: www.zhuxian.com, poster: xiaoding, time: 1081440000, votes: 677} redis.hmset(article_100635
, article_desc) article_desc = {title: soushenji, link: www.soushenji.com, poster: shuxiayehu, time: 1187280000, votes: 421} redis.hmset(article_100635, article_desc) def article_note(conn, user, article): cutoff = time.time() - ONE_WEEK_IN_SECONDS if conn.zscore(article_time, article) < cutoff: return article_id = article.partition(_)[-1] if conn.sadd(voted_ + article_id, user): conn.zincrby(article_score, article, VOTE_SCORE) conn.hincrby(article, votes, 1) r = redis.StrictRedis(host=redis_server_ip, port=6379, password=redis_passwd, db=0) redis_init(r) article_note(r,use_115423, article_100408)

參考資料:

《Redis實戰》

Redis之網站文章投票