• redis 实现互相关注功能


    突然想到平时的设计软件如何实现互相关注这个功能,然后查询后大致思路如下:

    可以使用 Redis 数据库来存储关注关系。

    社交网络应用程序中,互相关注功能(也称为双向关注或好友关系)是一种常见的功能,允许用户之间相互关注彼此。在Redis中,可以使用集合(Set)数据结构来实现互相关注功能。

    假设我们有两个用户,分别是用户A和用户B,他们之间可以相互关注。

    1. **用户A关注用户B:**
    SADD following:A B
    ```

    这个命令将用户A的关注列表中添加了用户B。

    2. **用户B关注用户A:**
    SADD following:B A
    ```

    这个命令将用户B的关注列表中添加了用户A。

    3. **检查两个用户是否互相关注:**
    SISMEMBER following:A B
    SISMEMBER following:B A
    ```

    以上两个命令分别检查用户A的关注列表中是否包含用户B,以及用户B的关注列表中是否包含用户A。如果返回1,表示互相关注,如果返回0,表示未互相关注。

    4. **获取用户A的关注列表:**
    SMEMBERS following:A
    ```

    这个命令将返回用户A关注的所有用户的列表。

    5. **获取用户B的关注列表:**
    SMEMBERS following:B
    ```

    这个命令将返回用户B关注的所有用户的列表。

    需要注意的是,以上示例假设用户ID是唯一的。可以将用户ID作为集合的键,以及关注的用户ID作为集合的成员。。

    然后用一个示例 Python 代码,演示了如何实现互相关注功能:

    首先,确保已经安装和启动了 Redis 服务器。然后,使用一个 Redis 客户端库(如 redis-py)来与 Redis 交互。

    1. import redis
    2. # 连接到 Redis 服务器
    3. r = redis.Redis(host='localhost', port=6379, db=0)
    4. # 定义关注和被关注的用户的键名
    5. def get_user_key(user_id):
    6. return f'user:{user_id}'
    7. # 实现关注功能
    8. def follow_user(user_id, target_user_id):
    9. user_key = get_user_key(user_id)
    10. target_user_key = get_user_key(target_user_id)
    11. # 将 target_user_id 添加到用户的关注列表中
    12. r.sadd(f'{user_key}:following', target_user_id)
    13. # 将用户的 user_id 添加到 target_user_id 的粉丝列表中
    14. r.sadd(f'{target_user_key}:followers', user_id)
    15. # 实现取消关注功能
    16. def unfollow_user(user_id, target_user_id):
    17. user_key = get_user_key(user_id)
    18. target_user_key = get_user_key(target_user_id)
    19. # 从用户的关注列表中移除 target_user_id
    20. r.srem(f'{user_key}:following', target_user_id)
    21. # 从 target_user_id 的粉丝列表中移除 user_id
    22. r.srem(f'{target_user_key}:followers', user_id)
    23. # 获取用户的关注列表
    24. def get_following(user_id):
    25. user_key = get_user_key(user_id)
    26. # 获取用户的关注列表
    27. return r.smembers(f'{user_key}:following')
    28. # 获取用户的粉丝列表
    29. def get_followers(user_id):
    30. user_key = get_user_key(user_id)
    31. # 获取用户的粉丝列表
    32. return r.smembers(f'{user_key}:followers')
    33. # 示例用法
    34. user1_id = 'user1'
    35. user2_id = 'user2'
    36. user3_id = 'user3'
    37. follow_user(user1_id, user2_id)
    38. follow_user(user1_id, user3_id)
    39. follow_user(user2_id, user1_id)
    40. print(f'User1 is following: {get_following(user1_id)}')
    41. print(f'User1 has followers: {get_followers(user1_id)}')

    使用 Redis 的集合(Set)来存储用户的关注列表和粉丝列表。sadd 用于将用户添加到关注列表,srem 用于从关注列表中移除用户。通过这些操作,我们可以实现用户之间的互相关注关系,并轻松地获取关注列表和粉丝列表。

  • 相关阅读:
    维格云小程序如何快速上手开发?
    由投影仪到智能会议平板,经历怎样的发展过程?
    Python+Appium移动端自动化测试框架实现
    Unity --- 滑动条,滚动条和滚动视图
    Day34力扣打卡
    银联扫码支付及静态码回调验签
    一张图理解MITRE ATT&CK框架
    一些常见的测度
    音视频从入门到精通——FFmpeg之av_seek_frame函数分析
    python print 格式化输出
  • 原文地址:https://blog.csdn.net/clayhell/article/details/133895962