当前位置: 首页 > article >正文

如何用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框架实现了可交互的关注和取消关注按钮,并在用户主页上显示了关注和被关注的数量。希望本文能对大家有所帮助。


http://www.kler.cn/news/18106.html

相关文章:

  • 【Linux0.11代码分析】06 之 kernel 初始化 init 进程代码分析
  • 如何用ChatGPT做一门课?(包含大纲、脚本、PPT文本)
  • Android---启动速度优化
  • 了解MSIL汇编和IL汇编评估堆栈
  • 【思科、华为、华三、锐捷网络设备巡检命令】
  • PAT A1035 Password
  • 机器人控制系统学习和研究中数学的重要性
  • 数据库系列-什么是 JDBC?它的作用是什么?
  • centos7 安装python的命令
  • 【Halcon】找到设备上的 标识牌
  • Java设计模式(十八)中介者模式
  • Nacos注册中心一些配置说明
  • 《Netty》从零开始学netty源码(五十三)之PoolThreadCache的功能
  • MySQL面试八股文:索引篇
  • 我把Solon打包成了native image,速度快的惊人
  • 【linux的学习与软件安装】
  • 计算机操作系统实验:页面置换算法的实现
  • 充电桩测试设备TK4800充电桩现校仪检定装置
  • MySQL优化二索引使用
  • 信息安全从业人员职业规划(甲方乙方分别说明)
  • 中兴B860AV2.1-T(M)-高安版-当贝纯净桌面线刷固件包
  • Facebook 用户量十分庞大,为什么还使用 MySQL 数据库?
  • IDEA沉浸式编程体验
  • 锁相环技术,单边带信号,信号的调制
  • MySQL数据库之索引
  • 【SpringMVC】三、SpringMVC获取请求参数与域数据共享
  • Ubuntu20.04安装Vtk9.2.6+PCL1.12.1(成功无报错)
  • 使用asp.net core web api创建web后台,并连接和使用Sql Server数据库
  • Flink dataStream,如何开窗,如何进行窗口内计算
  • BM54-三数之和