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

文章目录

⛅引言

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

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

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

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

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

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

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

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

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

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

tb_follow

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

id为自增长,简化开发

核心代码

FollowController


@PutMapping("/{id}/{isFollow}")
public Result follow(@PathVariable("id") Long followUserId, @PathVariable("isFollow") Boolean isFollow) {
    return followService.follow(followUserId, isFollow);
}

@GetMapping("/or/not/{id}")
public Result isFollow(@PathVariable("id") Long followUserId) {
    return followService.isFollow(followUserId);
}

FollowService

@Override
public Result follow(Long followUserId, Boolean isFollow) {

    Long userId = UserHolder.getUser().getId();
    String key = "follows:" + userId;

    if (isFollow) {

        Follow follow = new Follow();
        follow.setUserId(userId);
        follow.setFollowUserId(followUserId);
        boolean isSuccess = save(follow);
        if (isSuccess) {
            stringRedisTemplate.opsForSet().add(key, followUserId.toString());
        }
    } else {

        boolean isSuccess = remove(new QueryWrapper<Follow>()
                                   .eq("user_id", userId).eq("follow_user_id", followUserId));
        if (isSuccess) {

            stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
        }
    }
    return Result.ok();
}

@Override
public Result isFollow(Long followUserId) {

    Long userId = UserHolder.getUser().getId();

    Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();

    return Result.ok(count > 0);
}

代码编写完毕,进行测试

代码测试

点击进行关注用户

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

关注成功

取消关注

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

测试成功

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

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

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

核心代码如下

UserController


@GetMapping("/{id}")
public Result queryUserById(@PathVariable("id") Long userId){

    User user = userService.getById(userId);
    if (user == null) {
        return Result.ok();
    }
    UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

    return Result.ok(userDTO);
}

BlogController

@GetMapping("/of/user")
public Result queryBlogByUserId(
    @RequestParam(value = "current", defaultValue = "1") Integer current,
    @RequestParam("id") Long id) {

    Page<Blog> page = blogService.query()
        .eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));

    List<Blog> records = page.getRecords();
    return Result.ok(records);
}

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

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

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

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

改造核心代码

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

FlowServiceImpl

@Override
public Result follow(Long followUserId, Boolean isFollow) {

    Long userId = UserHolder.getUser().getId();
    String key = "follows:" + userId;

    if (isFollow) {

        Follow follow = new Follow();
        follow.setUserId(userId);
        follow.setFollowUserId(followUserId);
        boolean isSuccess = save(follow);
        if (isSuccess) {
            stringRedisTemplate.opsForSet().add(key, followUserId.toString());
        }
    } else {

        boolean isSuccess = remove(new QueryWrapper<Follow>()
                                   .eq("user_id", userId).eq("follow_user_id", followUserId));
        if (isSuccess) {

            stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
        }
    }
    return Result.ok();
}

@Override
public Result followCommons(Long id) {

    Long userId = UserHolder.getUser().getId();
    String key = "follows:" + userId;

    String key2 = "follows:" + id;
    Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
    if (intersect == null || intersect.isEmpty()) {

        return Result.ok(Collections.emptyList());
    }

    List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());

    List<UserDTO> users = userService.listByIds(ids)
        .stream()
        .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
        .collect(Collectors.toList());
    return Result.ok(users);
}

进行测试

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

⛵小结

以上就是【 Bug 终结者】对 微服务Spring Boot 整合 Redis 实现 好友关注 的简单介绍, Redis 实现好友关注功能也是 利用Set集合、ZSet集合实现这样一个需求,同时,采用Redis来实现更加的快速,减少系统的消耗,更加快速的实现数据展示! &#x4E0B;&#x7BC7;&#x535A;&#x6587;&#x6211;&#x4EEC;&#x7EE7;&#x7EED; &#x5173;&#x6CE8; &#x5982;&#x4F55; &#x4F7F;&#x7528;Redis &#x5B9E;&#x73B0;&#x63A8;&#x9001;&#x6D88;&#x606F;&#x5230;&#x7C89;&#x4E1D;&#x6536;&#x4EF6;&#x7BB1;&#x4EE5;&#x53CA;&#x6EDA;&#x52A8;&#x5206;&#x9875;&#x67E5;&#x8BE2;&#xFF01;

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

Original: https://blog.csdn.net/weixin_45526437/article/details/128276229
Author: Bug 终结者
Title: 微服务Spring Boot 整合 Redis 实现 好友关注

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/795234/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球