微博评论功能:

import redis

class Comment(object):
    """创建评论"""
    def __init__(self, client):
        self.client = client
        
    def create(self, author_id, content):
        """创建一条评论,并返回评论ID"""
        comment_id = IdGenerator("weibo::comment::id", self.client).gen()
        comment_key = "weibo::comment::" + str(comment_id)
        self.client.hmset(comment_key, {"id": comment_id, "author_id": author_id, "time": int(time.time()), "content": content})
        return comment_id
        
    def get_by_id(self, comment_id):
        """获取指定ID的评论内容"""
        comment_key = "weibo::comment::" + str(comment_id)
        return self.client.hgetall(comment_key)


class CommentList(object):
    """将评论推入到该微博的评论列表中"""
    def __init__(self, msg_id, client):
        self.msg_id = msg_id
        self.client = client
        self.key = "weibo::message::" + str(msg_id) + "::comments"
        
    def push(self, comment_id):
        """将评论ID推入到该微博的列表中"""
        self.client.lpush(self.key, comment_id)
        
    def count(self):
        """获取该微博的总评论数"""
        return self.client.llen(self.key)

    def paging(self, n):
        """查看第几页的评论,返回的是评论的ID"""
        count = 5  # 5条评论为一页
        start_index = (n-1) * count
        end_index = n*count - 1
        return self.client.lrange(self.key, start_index, end_index)


if __name__ == "__main__":
    redis_client = redis.StrictRedis()
    # 10010用户新写了一条微博
    msg = Message(redis_client)
    message_id, weibo_timestamp = msg.create(10010, "very nice day")
    # 10086用户给这条微博做了评论
    comment = Comment(redis_client)
    comment_id = comment.create(10086, "very good")
    # 将10086的这条评论推入到10010用户发布的微博的评论列表中
    comment_list = CommentList(message_id, redis_client)
    comment_list.push(comment_id)
    # 获取这条微博的总评论数
    print(comment_list.count())
    # 查看该微博的第一页评论内容(ID)
    print(comment_list.paging(1))

    当我们发布一条微博后,所有人都可以对该微博进行评论。对于每条评论,redis都会分配唯一的一个评论ID,用格式为"weibo::comment::<id>"的散列键来存储评论的发布者,发布时间和内容等信息。对于每条微博,redis都会使用一个列表键"weibo::message::<id>::comments"来存储该微博的所有评论的ID;每当有新的评论产生时,redis都会把评论ID从左侧推入到列表中,所有的新评论都在列表左侧,旧的评论都在列表右侧。

        至此我们已经实现了微博的所有基本功能,当然这仅仅只是一个简单的IT框架,没有考虑高并发高负载高可用的用户访问,Redis微博系列也到此结束,谢谢!