• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    Redis之如何实现用户关注

    发布者: 福建二哥 | 发布时间: 2025-6-19 12:42| 查看数: 99| 评论数: 0|帖子模式

    Redis实现互相关注功能

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

    功能要求

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

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

    Redis存储结构设计

    我们使用Redis的
    1. set
    复制代码
    数据结构来存储用户关注的人和被关注的人。
    具体来说,每个用户都有一个
    1. following
    复制代码
    1. followers
    复制代码
    属性,分别表示该用户关注的人和被谁关注。
    然后在Redis中使用
    1. set
    复制代码
    类型来存储这些关注信息,在set中,我们将每个关注对象的id存储下来,方便后续的查询。

    后端实现


    添加关注

    我们需要通过API来让用户实现添加关注和取消关注。
    下面是添加关注的API代码:
    1. // 添加关注
    2. router.post('/followers/:id', async (req, res) => {
    3.   try {
    4.     const followerId = req.user.id;
    5.     const followingId = req.params.id;

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

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

    12.     res.json({ message: `You are now following ${following.username}` });
    13.   } catch (error) {
    14.     console.error(error.message);
    15.     res.status(500).send('Server Error');
    16.   }
    17. });
    复制代码
    在这个代码中,我们使用了
    1. redis.sadd
    复制代码
    方法将关注对象的id添加到set中。

    取消关注

    接下来是取消关注的API代码:
    1. // 取消关注
    2. router.delete('/followers/:id', async (req, res) => {
    3. try {
    4.     const followerId = req.user.id;
    5.     const followingId = req.params.id;

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

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

    12.     res.json({ message: `You have unfollowed ${following.username}` });
    13.   } catch (error) {
    14.     console.error(error.message);
    15.     res.status(500).send('Server Error');
    16.   }
    17. });
    复制代码
    这个代码与添加关注的代码类似,只是使用了
    1. redis.srem
    复制代码
    方法来将关注对象的id从set中删除。

    查看关注对象

    最后,我们需要实现查看关注对象的API。这个API需要分别获取关注和被关注的set,然后将id转换为用户对象。
    1. // 获取关注和粉丝
    2. router.get('/followers', async (req, res) => {
    3.   try {
    4.     const userId = req.user.id;

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

    10.     // 将id转换为用户对象
    11.     const followingUsers = await Promise.all(
    12.       following.map((id) => User.findById(id))
    13.     );
    14.     const followerUsers = await Promise.all(
    15.       followers.map((id) => User.findById(id))
    16.     );

    17.     res.json({ following: followingUsers, followers: followerUsers });
    18.   } catch (error) {
    19.     console.error(error.message);
    20.     res.status(500).send('Server Error');
    21.   }
    22. });
    复制代码
    前端实现

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

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

    添加关注和取消关注操作

    在Vue中,我们可以使用
    1. @click
    复制代码
    监听用户点击事件,并在方法中发送API请求来进行添加和取消关注。
    下面是代码示例:
    1. <!-- 添加关注 -->
    2. <button @click="followUser(user._id)" v-if="!isFollowing(user._id)">关注</button>

    3. <!-- 取消关注 -->
    4. <button @click="unfollowUser(user._id)" v-else>取消关注</button>
    复制代码
    1. methods: {
    2.   // 添加关注
    3.   async followUser(id) {
    4.     await axios.post(`/api/followers/${id}`);
    5.     // 更新关注状态
    6.     this.isFollowingUsers[id] = true;
    7.   },
    8.   // 取消关注
    9.   async unfollowUser(id) {
    10.     await axios.delete(`/api/followers/${id}`);
    11.     // 更新关注状态
    12.     this.isFollowingUsers[id] = false;
    13.   },
    14.   // 判断是否关注
    15.   isFollowing(id) {
    16.     return this.isFollowingUsers[id];
    17.   }
    18. }
    复制代码
    在这个代码中,我们使用了
    1. isFollowingUsers
    复制代码
    对象来存储所有用户的关注状态。

    显示关注和被关注数量

    为了在用户的主页上显示关注和被关注的数量,我们需要在后端添加相应的API,并在前端调用数据显示。
    下面是相关代码:
    1. // 获取关注和粉丝数量
    2. router.get('/followers/count', async (req, res) => {
    3.   try {
    4.     const userId = req.user.id;

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

    10.     res.json({ followingCount, followerCount });
    11.   } catch (error) {
    12.     console.error(error.message);
    13.     res.status(500).send('Server Error');
    14.   }
    15. });
    复制代码
    1. <!-- 显示关注和被关注数量 -->
    2. <div>
    3.   <p>关注 {{followingCount}}</p>
    4.   <p>被关注 {{followerCount}}</p>
    5. </div>
    复制代码
    在这个代码中,我们使用了
    1. redis.scard
    复制代码
    方法来获取set的数量。

    总结

    以上就是使用Redis实现互相关注功能的全部内容。通过使用Redis的
    1. set
    复制代码
    数据结构来存储关注对象,方便高效地进行添加和取消关注操作。同时,在前端中使用Vue框架实现了可交互的关注和取消关注按钮,并在用户主页上显示了关注和被关注的数量。
    这些仅为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    来源:https://www.jb51.net/database/338117q0a.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    最新评论

    浏览过的版块

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表