本文共 1360 字,大约阅读时间需要 4 分钟。
微博点赞功能的实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import redis class LikeMessage( object ): """实现微博点赞功能""" def __init__( self , msg_id, client): self .msg_id = msg_id self .client = client self .key = "weibo::message::" + str (msg_id) + "::like" def like( self , user_id): """对该微博点赞""" self .client.sadd( self .key, user_id) def is_liking( self , user_id): """检查用户是否赞了该微博""" return self .client.sismember( self .key, user_id) def undo( self , user_id): """取消点赞""" self .client.srem( self .key, user_id) def count( self ): """获取该微博点赞人数""" return self .client.scard( self .key) def get_all_liking_user( self ): """返回赞了该微博的所有用户""" if not self .client.exists( self .key): return False else : return self .client.smembers( self .key) if __name__ = = "__main__" : redis_client = redis.StrictRedis() vote = LikeMessage( 65535 , redis_client) vote.like( 10010 ) vote.like( 10086 ) vote.like( 10000 ) print (vote.count()) print (vote.is_liking( 10086 )) vote.undo( 10086 ) print (vote.get_all_liking_user()) |
在这里我们使用无序集合键来保存对微博的点赞信息,我们在之前的文章已经用无序集合键实现了保存微博用户之间的关系,无序集合键还可以实现例如书籍的标签信息,个人标签等。只要是不在乎数据存储的顺序,并且数据必须是唯一的,都可以用无序集合键来实现功能。对于每条微博,redis都会创建一个"weibo::message::<id>::like"的无序集合键来存储对该微博点赞的用户。
本文转自戴柏阳的博客博客51CTO博客,原文链接http://blog.51cto.com/daibaiyang119/1963055如需转载请自行联系原作者
daibaiyang119