Redis之如何实现用户关注

 更新时间:2025年03月20日 16:53:29   作者:沙漠真有鱼  
这篇文章主要介绍了Redis之如何实现用户关注问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

Redis实现互相关注功能

在实现社交网络功能中,实现互相关注是必不可少的。在这里,我们将使用Redis来实现这个功能,前端使用Vue框架实现。

功能要求

我们需要实现以下几个功能:

  1. 用户能够关注其他用户
  2. 用户能够取消关注其他用户
  3. 用户能够查看自己关注的人和被谁关注
  4. 在用户的主页上,能够显示关注和被关注的数量

Redis存储结构设计

我们使用Redis的set数据结构来存储用户关注的人和被关注的人。

具体来说,每个用户都有一个followingfollowers属性,分别表示该用户关注的人和被谁关注。

然后在Redis中使用set类型来存储这些关注信息,在set中,我们将每个关注对象的id存储下来,方便后续的查询。

后端实现

添加关注

我们需要通过API来让用户实现添加关注和取消关注。

下面是添加关注的API代码:

// 添加关注
router.post('/followers/:id', async (req, res) => {
  try {
    const followerId = req.user.id;
    const followingId = req.params.id;

    // 获取被关注的用户和关注该用户的用户
    const following = await User.findById(followingId);
    const follower = await User.findById(followerId);

    // 添加关注对象
    await redis.sadd(`user:${followerId}:following`, followingId);
    await redis.sadd(`user:${followingId}:followers`, followerId);

    res.json({ message: `You are now following ${following.username}` });
  } catch (error) {
    console.error(error.message);
    res.status(500).send('Server Error');
  }
});

在这个代码中,我们使用了redis.sadd方法将关注对象的id添加到set中。

取消关注

接下来是取消关注的API代码:

// 取消关注
router.delete('/followers/:id', async (req, res) => {
 try {
    const followerId = req.user.id;
    const followingId = req.params.id;

    // 获取被取消关注的用户和取消关注该用户的用户
    const following = await User.findById(followingId);
    const follower = await User.findById(followerId);

    // 删除关注对象
    await redis.srem(`user:${followerId}:following`, followingId);
    await redis.srem(`user:${followingId}:followers`, followerId);

    res.json({ message: `You have unfollowed ${following.username}` });
  } catch (error) {
    console.error(error.message);
    res.status(500).send('Server Error');
  }
});

这个代码与添加关注的代码类似,只是使用了redis.srem方法来将关注对象的id从set中删除。

查看关注对象

最后,我们需要实现查看关注对象的API。这个API需要分别获取关注和被关注的set,然后将id转换为用户对象。

// 获取关注和粉丝
router.get('/followers', async (req, res) => {
  try {
    const userId = req.user.id;

    // 获取关注和被关注的set
    const [following, followers] = await Promise.all([
      redis.smembers(`user:${userId}:following`),
      redis.smembers(`user:${userId}:followers`),
    ]);

    // 将id转换为用户对象
    const followingUsers = await Promise.all(
      following.map((id) => User.findById(id))
    );
    const followerUsers = await Promise.all(
      followers.map((id) => User.findById(id))
    );

    res.json({ following: followingUsers, followers: followerUsers });
  } catch (error) {
    console.error(error.message);
    res.status(500).send('Server Error');
  }
});

前端实现

在前端中,我们使用Vue框架来实现。需要提供以下功能:

  1. 用户可以通过点击按钮来添加和取消关注操作
  2. 用户的主页可以显示关注和被关注的数量

添加关注和取消关注操作

在Vue中,我们可以使用@click监听用户点击事件,并在方法中发送API请求来进行添加和取消关注。

下面是代码示例:

<!-- 添加关注 -->
<button @click="followUser(user._id)" v-if="!isFollowing(user._id)">关注</button>

<!-- 取消关注 -->
<button @click="unfollowUser(user._id)" v-else>取消关注</button>
methods: {
  // 添加关注
  async followUser(id) {
    await axios.post(`/api/followers/${id}`);
    // 更新关注状态
    this.isFollowingUsers[id] = true;
  },
  // 取消关注
  async unfollowUser(id) {
    await axios.delete(`/api/followers/${id}`);
    // 更新关注状态
    this.isFollowingUsers[id] = false;
  },
  // 判断是否关注
  isFollowing(id) {
    return this.isFollowingUsers[id];
  }
}

在这个代码中,我们使用了isFollowingUsers对象来存储所有用户的关注状态。

显示关注和被关注数量

为了在用户的主页上显示关注和被关注的数量,我们需要在后端添加相应的API,并在前端调用数据显示。

下面是相关代码:

// 获取关注和粉丝数量
router.get('/followers/count', async (req, res) => {
  try {
    const userId = req.user.id;

    // 获取关注和被关注数量
    const [followingCount, followerCount] = await Promise.all([
      redis.scard(`user:${userId}:following`),
      redis.scard(`user:${userId}:followers`),
    ]);

    res.json({ followingCount, followerCount });
  } catch (error) {
    console.error(error.message);
    res.status(500).send('Server Error');
  }
});
<!-- 显示关注和被关注数量 -->
<div>
  <p>关注 {{followingCount}}</p>
  <p>被关注 {{followerCount}}</p>
</div>

在这个代码中,我们使用了redis.scard方法来获取set的数量。

总结

以上就是使用Redis实现互相关注功能的全部内容。通过使用Redis的set数据结构来存储关注对象,方便高效地进行添加和取消关注操作。同时,在前端中使用Vue框架实现了可交互的关注和取消关注按钮,并在用户主页上显示了关注和被关注的数量。

这些仅为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Redis源码设计剖析之事件处理示例详解

    Redis源码设计剖析之事件处理示例详解

    这篇文章主要为大家介绍了Redis源码设计剖析之事件处理示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • Redis设置密码以及设置后不生效的解决过程

    Redis设置密码以及设置后不生效的解决过程

    这段描述主要讲解了如何修改Redis配置文件以设置自定义密码,并强调了在启动Redis时需使用配置文件的重要性,通过修改`redis.windows.conf`中的`requirepass`参数并重启Redis服务,可以实现自定义密码设置
    2026-05-05
  • Redis的使用模式之计数器模式实例

    Redis的使用模式之计数器模式实例

    这篇文章主要介绍了Redis的使用模式之计数器模式实例,本文讲解了汇总计数器、按时间汇总的计数器、速度控制、使用 Hash 数据类型维护大量计数器等内容,需要的朋友可以参考下
    2015-03-03
  • Redis数据存储原理和结构解读

    Redis数据存储原理和结构解读

    这篇文章详细介绍了Redis的数据结构和过期机制,包括键值对存储、哈希表、字典、跳表等,并探讨了大Key问题和解决方法
    2026-03-03
  • 浅谈Redis内存回收策略

    浅谈Redis内存回收策略

    本文主要介绍了浅谈Redis内存回收策略,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06
  • Redis缓存击穿的用法及说明

    Redis缓存击穿的用法及说明

    文章介绍了缓存击穿的概念、核心原因及其对系统的危害,并提出了两种解决方案:互斥锁方案和逻辑过期方案,互斥锁方案能保证数据一致性但性能较低,逻辑过期方案则能提供高可用性和性能
    2026-04-04
  • redis简单介绍及安装使用小结

    redis简单介绍及安装使用小结

    本文主要是对于redis初步学习的小结内容,包括了redis介绍,redis安装以及最简单的使用,希望大家能够喜欢
    2018-11-11
  • 深度剖析Redis双写一致性问题的解决方案

    深度剖析Redis双写一致性问题的解决方案

    在高并发场景下,缓存与数据库的双写一致性是每个开发者必须直面的核心挑战,本文通过5大解决方案,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下
    2025-09-09
  • Redis增减库存避坑的实现

    Redis增减库存避坑的实现

    在电商平台或者仓库管理系统中,库存的管理是非常重要的一项任务,本文主要介绍了Redis增减库存避坑的实现,具有一定的参考价值,感兴趣的可以了解一下
    2024-02-02
  • Redis实现查看服务状态、关闭和启动方式

    Redis实现查看服务状态、关闭和启动方式

    本文介绍了如何在Linux系统中查看、关闭和启动Redis服务,包括使用命令行工具和配置文件进行相关操作
    2025-11-11

最新评论