Redis实现用户关注的项目实践

 更新时间:2024年02月28日 14:45:49   作者:Blet-  
本文主要介绍了Redis实现用户关注的项目实践,通过使用Redis的set数据结构来存储关注对象,方便高效地进行添加和取消关注操作,具有一定的参考价值,感兴趣的可以了解一下

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

功能要求

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

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

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框架来实现。需要提供以下功能:

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

添加关注和取消关注操作

在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 Cluster原理及配置详解

    Redis Cluster原理及配置详解

    这篇文章主要为大家介绍了Redis Cluster原理及配置详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-11-11
  • redis Template.opsForValue()中方法实例详解

    redis Template.opsForValue()中方法实例详解

    这篇文章主要介绍了redis Template.opsForValue()中方法讲解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-05-05
  • redis GEO数据结构、实现附近商铺功能实践

    redis GEO数据结构、实现附近商铺功能实践

    文章介绍了Redis中的GEO命令及其用途,包括地理坐标存储、距离计算、坐标转换和位置搜索等功能,还分享了如何使用Redis实现查询附近商铺的功能,包括导入商铺信息和根据类型及距离进行搜索
    2025-12-12
  • Redis List列表的详细介绍

    Redis List列表的详细介绍

    这篇文章主要介绍了Redis List列表的详细介绍的相关资料,Redis列表是简单的字符串列表,按照插入顺序排序,需要的朋友可以参考下
    2017-08-08
  • 如何使用 redis 消息队列完成秒杀过期订单处理操作(二)

    如何使用 redis 消息队列完成秒杀过期订单处理操作(二)

    这篇文章主要介绍了如何使用 redis 消息队列完成秒杀过期订单处理操作,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2024-07-07
  • 关于Redis单线程的正确理解

    关于Redis单线程的正确理解

    很多同学对Redis的单线程和I/O多路复用技术并不是很了解,所以我用简单易懂的语言让大家了解下Redis单线程和I/O多路复用技术的原理,对学好和运用好Redis打下基础,感兴趣的朋友跟随小编一起看看吧
    2021-11-11
  • Redis数据一致性问题的三种解决方案

    Redis数据一致性问题的三种解决方案

    Redis(Remote Dictionary Server ),是一个高性能的基于Key-Value结构存储的NoSQL开源数据库,大部分公司采用Redis来实现分布式缓存,用来提高数据查询效率,本文就给大家介绍三种Redis数据一致性问题的解决方案,需要的朋友可以参考下
    2023-07-07
  • 详解Redis缓存与Mysql如何保证双写一致

    详解Redis缓存与Mysql如何保证双写一致

    缓存和数据库如何保证数据的一致是个很经典的问题,这篇文章就来和大家一起探讨一下Redis缓存与Mysql如何保证双写一致,感兴趣的小伙伴可以参考下
    2023-12-12
  • Redis瞬时高并发秒杀方案总结

    Redis瞬时高并发秒杀方案总结

    本文讲述了Redis瞬时高并发秒杀方案总结,具有很好的参考价值,感兴趣的小伙伴们可以参考一下,具体如下:
    2018-05-05
  • 如何打造redis缓存组件

    如何打造redis缓存组件

    文章介绍了如何使用热插拔AOP、反射、Redis自定义注解和SpringEL表达式来打造一个优雅的Redis缓存组件,通过这种方式,可以重构和简化缓存代码,并提供了Redis配置和自定义注解的详细说明,文章还包含了AOP测试的总结,并鼓励读者参考和支持
    2024-12-12

最新评论