微服务Spring Boot 整合 Redis 实现 好友关注

超、凢脫俗 2024-05-01 04:36 140阅读 0赞

文章目录

  • ⛅引言
  • 一、Redis 实现好友关注 — 关注与取消关注
  • 二、Redis 实现好友关注 — 共同关注功能
  • ⛵小结

⛅引言

本博文参考 黑马 程序员B站 Redis课程系列

在点评项目中,有这样的需求,如何实现笔记的好友关注、以及发布笔记后推送消息功能?

使用Redis 的 好友关注、以及发布笔记后推送消息功能

一、Redis 实现好友关注 – 关注与取消关注

需求:针对用户的操作,可以对用户进行关注和取消关注功能。

在探店图文的详情页面中,可以关注发布笔记的作者

在这里插入图片描述

具体实现思路:基于该表数据结构,实现2个接口

  • 关注和取关接口
  • 判断是否关注的接口

关注是用户之间的关系,是博主与粉丝的关系,数据表如下:

tb_follow

  1. CREATE TABLE `tb_follow` (
  2. `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  3. `user_id` bigint(20) unsigned NOT NULL COMMENT '用户id',
  4. `follow_user_id` bigint(20) unsigned NOT NULL COMMENT '关联的用户id',
  5. `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  6. PRIMARY KEY (`id`) USING BTREE
  7. ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT;

id为自增长,简化开发

核心代码

FollowController

  1. //关注
  2. @PutMapping("/{id}/{isFollow}")
  3. public Result follow(@PathVariable("id") Long followUserId, @PathVariable("isFollow") Boolean isFollow) {
  4. return followService.follow(followUserId, isFollow);
  5. }
  6. //取消关注
  7. @GetMapping("/or/not/{id}")
  8. public Result isFollow(@PathVariable("id") Long followUserId) {
  9. return followService.isFollow(followUserId);
  10. }

FollowService

  1. @Override
  2. public Result follow(Long followUserId, Boolean isFollow) {
  3. // 1.获取登录用户
  4. Long userId = UserHolder.getUser().getId();
  5. String key = "follows:" + userId;
  6. // 1.判断到底是关注还是取关
  7. if (isFollow) {
  8. // 2.关注,新增数据
  9. Follow follow = new Follow();
  10. follow.setUserId(userId);
  11. follow.setFollowUserId(followUserId);
  12. boolean isSuccess = save(follow);
  13. if (isSuccess) {
  14. stringRedisTemplate.opsForSet().add(key, followUserId.toString());
  15. }
  16. } else {
  17. // 3.取关,删除 delete from tb_follow where user_id = ? and follow_user_id = ?
  18. boolean isSuccess = remove(new QueryWrapper<Follow>()
  19. .eq("user_id", userId).eq("follow_user_id", followUserId));
  20. if (isSuccess) {
  21. // 把关注用户的id从Redis集合中移除
  22. stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
  23. }
  24. }
  25. return Result.ok();
  26. }
  27. @Override
  28. public Result isFollow(Long followUserId) {
  29. // 1.获取登录用户
  30. Long userId = UserHolder.getUser().getId();
  31. // 2.查询是否关注 select count(*) from tb_follow where user_id = ? and follow_user_id = ?
  32. Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
  33. // 3.判断
  34. return Result.ok(count > 0);
  35. }

代码编写完毕,进行测试

代码测试

点击进行关注用户

在这里插入图片描述

关注成功

取消关注

在这里插入图片描述

测试成功

二、Redis 实现好友关注 – 共同关注功能

实现共同关注好友功能,首先,需要进入博主发布的指定笔记页,然后点击博主的头像去查看详细信息

在这里插入图片描述

核心代码如下

UserController

  1. // UserController 根据id查询用户
  2. @GetMapping("/{id}")
  3. public Result queryUserById(@PathVariable("id") Long userId){
  4. // 查询详情
  5. User user = userService.getById(userId);
  6. if (user == null) {
  7. return Result.ok();
  8. }
  9. UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
  10. // 返回
  11. return Result.ok(userDTO);
  12. }

BlogController

  1. @GetMapping("/of/user")
  2. public Result queryBlogByUserId(
  3. @RequestParam(value = "current", defaultValue = "1") Integer current,
  4. @RequestParam("id") Long id) {
  5. // 根据用户查询
  6. Page<Blog> page = blogService.query()
  7. .eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
  8. // 获取当前页数据
  9. List<Blog> records = page.getRecords();
  10. return Result.ok(records);
  11. }

那么如何实现共同好友关注功能呢?

需求:利用Redis中的数据结构,实现共同关注功能。 在博主个人页面展示出当前用户与博主的共同关注

思路分析: 使用Redis的Set集合实现,我们把两人关注的人分别放入到一个Set集合中,然后再通过API去查看两个Set集合中的交集数据

在这里插入图片描述

改造核心代码

当用户关注某位用户后,需要将数据存入Redis集合中,方便后续进行共同关注的实现,同时取消关注时,需要删除Redis中的集合

FlowServiceImpl

  1. @Override
  2. public Result follow(Long followUserId, Boolean isFollow) {
  3. // 1.获取登录用户
  4. Long userId = UserHolder.getUser().getId();
  5. String key = "follows:" + userId;
  6. // 1.判断到底是关注还是取关
  7. if (isFollow) {
  8. // 2.关注,新增数据
  9. Follow follow = new Follow();
  10. follow.setUserId(userId);
  11. follow.setFollowUserId(followUserId);
  12. boolean isSuccess = save(follow);
  13. if (isSuccess) {
  14. stringRedisTemplate.opsForSet().add(key, followUserId.toString());
  15. }
  16. } else {
  17. // 3.取关,删除 delete from tb_follow where user_id = ? and follow_user_id = ?
  18. boolean isSuccess = remove(new QueryWrapper<Follow>()
  19. .eq("user_id", userId).eq("follow_user_id", followUserId));
  20. if (isSuccess) {
  21. // 把关注用户的id从Redis集合中移除
  22. stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
  23. }
  24. }
  25. return Result.ok();
  26. }
  27. // 具体获取好友共同关注代码
  28. @Override
  29. public Result followCommons(Long id) {
  30. // 1.获取当前用户
  31. Long userId = UserHolder.getUser().getId();
  32. String key = "follows:" + userId;
  33. // 2.求交集
  34. String key2 = "follows:" + id;
  35. Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
  36. if (intersect == null || intersect.isEmpty()) {
  37. // 无交集
  38. return Result.ok(Collections.emptyList());
  39. }
  40. // 3.解析id集合
  41. List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
  42. // 4.查询用户
  43. List<UserDTO> users = userService.listByIds(ids)
  44. .stream()
  45. .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
  46. .collect(Collectors.toList());
  47. return Result.ok(users);
  48. }

进行测试

在这里插入图片描述

⛵小结

以上就是【Bug 终结者】对 微服务Spring Boot 整合 Redis 实现 好友关注 的简单介绍,Redis 实现好友关注功能也是 利用Set集合、ZSet集合实现这样一个需求,同时,采用Redis来实现更加的快速,减少系统的消耗,更加快速的实现数据展示! 下篇博文我们继续 关注 如何 使用Redis 实现推送消息到粉丝收件箱以及滚动分页查询!

如果这篇【文章】有帮助到你,希望可以给【Bug 终结者】点个赞?,创作不易,如果有对【后端技术】、【前端领域】感兴趣的小可爱,也欢迎关注❤️❤️❤️ 【Bug 终结者】❤️❤️❤️,我将会给你带来巨大的【收获与惊喜】???!

发表评论

表情:
评论列表 (有 0 条评论,140人围观)

还没有评论,来说两句吧...

相关阅读