实战:Redis实现排行榜、点赞和关注功能的基本操作
import redis
# 连接Redis
r = redis.Redis(host='localhost', port=6379, db=0)
# 添加用户
def add_user(username):
r.set(username, 0)
# 获取用户排名
def get_user_rank(username):
rank = r.zrank('leaderboard', username)
return rank + 1 if rank is not None else None
# 获取用户分数
def get_user_score(username):
return r.get(username)
# 更新用户分数
def update_user_score(username, new_score):
r.set(username, new_score)
r.zadd('leaderboard', {username: new_score})
# 点赞
def like_post(post_id, username):
r.sadd('post:{}'.format(post_id), username)
# 取消点赞
def unlike_post(post_id, username):
r.srem('post:{}'.format(post_id), username)
# 检查是否已点赞
def has_liked_post(post_id, username):
return r.sismember('post:{}'.format(post_id), username)
# 关注用户
def follow_user(follower, followed):
r.sadd('user:{}:following'.format(follower), followed)
# 取消关注
def unfollow_user(follower, followed):
r.srem('user:{}:following'.format(follower), followed)
# 检查是否关注了某用户
def has_followed_user(follower, followed):
return r.sismember('user:{}:following'.format(follower), followed)
# 获取关注者的列表
def get_following_list(username):
return r.smembers('user:{}:following'.format(username))
# 获取粉丝的列表
def get_followers_list(username):
return r.smembers('user:{}:followers'.format(username))
# 示例用法
add_user('alice')
update_user_score('alice', 100)
like_post('post1', 'alice')
follow_user('alice', 'bob')
print("Alice's rank:", get_user_rank('alice'))
print("Alice's score:", get_user_score('alice'))
print("Has Alice liked post1?", has_liked_post('post1', 'alice'))
print("Bob's following:", get_following_list('bob'))
print("Alice's followers:", get_followers_list('alice'))
这段代码提供了一个简化的Redis操作示例,用于实现社交网络服务中的用户排名、分数更新、点赞、关注和粉丝功能。代码中使用了Redis的String、Sorted Set和Set数据结构,并提供了相应的操作方法。这些方法可以直接被应用程序调用来实现相关的功能。
评论已关闭