515439429 发表于 2018-11-3 11:19:22

Redis实现微博后台业务逻辑系列(六)

imprort redis  

  
class TimeLine(object):
  
    """用户定制时间线和个人时间线"""
  
    def __init__(self, client):
  
      self.client = client
  

  
    def custom_push(self, user_id, msg_id, time):
  
      """将微博推入到用户定制的时间线中"""
  
      custom_timeline_key = "weibo::user::" + str(user_id) + "::custom_timeline"
  
      self.client.zadd(custom_timeline_key, time, msg_id)
  

  
    def personal_push(self, user_id, msg_id, time):
  
      """将微博推入到用户的个人时间线中"""
  
      personal_timeline_key = "weibo::user::" + str(user_id) + "::personal_timeline"
  
      self.client.zadd(personal_timeline_key, time, msg_id)
  

  
    def broadcast(msg_id, time, *fans_ids):
  
      """将微博推入所有粉丝的定制时间线中"""
  
      for fans in fans_ids:
  
            self.custom_push(fans, msg_id, time)
  

  
    def custom_paging(self, user_id, n):
  
      """获取用户定制时间线第n页的微博"""
  
      count = 5# 5条数据为一页
  
      custom_timeline_key = "weibo::user::" + str(user_id) + "::custom_timeline"
  
      start_index = (n-1) * count# 起始索引
  
      end_index = n*count - 1# 结束索引
  
      return self.client.zrevrange(custom_timeline_key, start_index, end_index)
  

  
    def personal_paging(self, user_id, n):
  
      """获取用户个人时间线第n页的微博"""
  
      count = 5# 5条数据为一页
  
      personal_timeline_key = "weibo::user::" + str(user_id) + "::personal_timeline"
  
      start_index = (n-1) * count# 起始索引
  
      end_index = n*count - 1# 结束索引
  
      return self.client.zrevrange(personal_timeline_key, start_index, end_index)
  

  

  
if __name__ == "__main__":
  
redis_client = redis.StrictRedis()
  
msg = Message(redis_client)
  
message_id, weibo_timestamp = msg.create(10086, "hello world")
  
# print("message_id:", message_id)
  
# print("weibo_timestamp:", weibo_timestamp)
  

  
tl = TimeLine(redis_client)
  
tl.custom_push(10086, message_id, weibo_timestamp)
  
tl.personal_push(10086, message_id, weibo_timestamp)
  

  
relation = RelatoinShip(redis_client)
  
fans_dict = relation.get_all_fans(10086)
  
if fans_dict == False:
  
      print("没有粉丝")
  
else:
  
      fans_list = list()
  
      for fans in fans_dict:
  
          fans_list.append(fans.decode())
  
      tl.broadcast(message_id, weibo_timestamp, *fans_list)
  

  
print(tl.custom_paging(10086, 1))
  
print(tl.personal_paging(10086, 1))


页: [1]
查看完整版本: Redis实现微博后台业务逻辑系列(六)