redis 实现互相关注功能

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

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

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

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

  1. **用户A关注用户B:**

SADD following:A B

```

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

  1. **用户B关注用户A:**

SADD following:B A

```

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

  1. **检查两个用户是否互相关注:**

SISMEMBER following:A B

SISMEMBER following:B A

```

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

  1. **获取用户A的关注列表:**

SMEMBERS following:A

```

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

  1. **获取用户B的关注列表:**

SMEMBERS following:B

```

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

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

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

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

python 复制代码
import redis

# 连接到 Redis 服务器
r = redis.Redis(host='localhost', port=6379, db=0)

# 定义关注和被关注的用户的键名
def get_user_key(user_id):
    return f'user:{user_id}'

# 实现关注功能
def follow_user(user_id, target_user_id):
    user_key = get_user_key(user_id)
    target_user_key = get_user_key(target_user_id)

    # 将 target_user_id 添加到用户的关注列表中
    r.sadd(f'{user_key}:following', target_user_id)

    # 将用户的 user_id 添加到 target_user_id 的粉丝列表中
    r.sadd(f'{target_user_key}:followers', user_id)

# 实现取消关注功能
def unfollow_user(user_id, target_user_id):
    user_key = get_user_key(user_id)
    target_user_key = get_user_key(target_user_id)

    # 从用户的关注列表中移除 target_user_id
    r.srem(f'{user_key}:following', target_user_id)

    # 从 target_user_id 的粉丝列表中移除 user_id
    r.srem(f'{target_user_key}:followers', user_id)

# 获取用户的关注列表
def get_following(user_id):
    user_key = get_user_key(user_id)

    # 获取用户的关注列表
    return r.smembers(f'{user_key}:following')

# 获取用户的粉丝列表
def get_followers(user_id):
    user_key = get_user_key(user_id)

    # 获取用户的粉丝列表
    return r.smembers(f'{user_key}:followers')

# 示例用法
user1_id = 'user1'
user2_id = 'user2'
user3_id = 'user3'

follow_user(user1_id, user2_id)
follow_user(user1_id, user3_id)
follow_user(user2_id, user1_id)

print(f'User1 is following: {get_following(user1_id)}')
print(f'User1 has followers: {get_followers(user1_id)}')

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

相关推荐
R_AirMan1 小时前
深入浅出Redis:一文掌握Redis底层数据结构与实现原理
java·数据结构·数据库·redis
Hello.Reader1 小时前
RedisJSON 内存占用剖析与调优
数据库·redis·缓存
wkj0012 小时前
php 如何通过mysqli操作数据库?
android·数据库·php
九皇叔叔4 小时前
【9】PostgreSQL 之 vacuum 死元组清理
数据库·postgresql
风雅的远行者4 小时前
mysql互为主从失效,重新同步
数据库·mysql
晨岳4 小时前
CentOS 安装 JDK+ NGINX+ Tomcat + Redis + MySQL搭建项目环境
java·redis·mysql·nginx·centos·tomcat
执笔诉情殇〆5 小时前
前后端分离(java) 和 Nginx在服务器上的完整部署方案(redis、minio)
java·服务器·redis·nginx·minio
宇钶宇夕5 小时前
S7-1200 系列 PLC 中 SCL 语言的 PEEK 和 POKE 指令使用详解
运维·服务器·数据库·程序人生·自动化
绿蚁新亭5 小时前
Spring的事务控制——学习历程
数据库·学习·spring
都叫我大帅哥6 小时前
🌟 Redis缓存与数据库数据一致性:一场数据世界的“三角恋”保卫战
redis