服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Redis - 微服务Spring Boot 整合 Redis 实现好友关注功能

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

2022-12-15 16:50Bug 终结者 Redis

这篇文章主要介绍了微服务Spring Boot 整合 Redis 实现 好友关注,本文结合示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

引言

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

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

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

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

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

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

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

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

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

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

tb_follow

?
1
2
3
4
5
6
7
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

?
1
2
3
4
5
6
7
8
9
10
//关注
@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

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

代码编写完毕,进行测试

代码测试

点击进行关注用户

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

关注成功

取消关注

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

测试成功

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

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

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

核心代码如下

UserController

?
1
2
3
4
5
6
7
8
9
10
11
12
// UserController 根据id查询用户
@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

?
1
2
3
4
5
6
7
8
9
10
11
@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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@Override
public Result follow(Long followUserId, Boolean isFollow) {
    // 1.获取登录用户
    Long userId = UserHolder.getUser().getId();
    String key = "follows:" + userId;
    // 1.判断到底是关注还是取关
    if (isFollow) {
        // 2.关注,新增数据
        Follow follow = new Follow();
        follow.setUserId(userId);
        follow.setFollowUserId(followUserId);
        boolean isSuccess = save(follow);
        if (isSuccess) {
            stringRedisTemplate.opsForSet().add(key, followUserId.toString());
        }
    } else {
        // 3.取关,删除 delete from tb_follow where user_id = ? and follow_user_id = ?
        boolean isSuccess = remove(new QueryWrapper<Follow>()
                                   .eq("user_id", userId).eq("follow_user_id", followUserId));
        if (isSuccess) {
            // 把关注用户的id从Redis集合中移除
            stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
        }
    }
    return Result.ok();
}
 
// 具体获取好友共同关注代码
 
@Override
public Result followCommons(Long id) {
    // 1.获取当前用户
    Long userId = UserHolder.getUser().getId();
    String key = "follows:" + userId;
    // 2.求交集
    String key2 = "follows:" + id;
    Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
    if (intersect == null || intersect.isEmpty()) {
        // 无交集
        return Result.ok(Collections.emptyList());
    }
    // 3.解析id集合
    List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
    // 4.查询用户
    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来实现更加的快速,减少系统的消耗,更加快速的实现数据展示! 下篇博文我们继续 关注 如何 使用Redis 实现推送消息到粉丝收件箱以及滚动分页查询!

到此这篇关于微服务Spring Boot 整合 Redis 实现 好友关注的文章就介绍到这了,更多相关Spring Boot 整合 Redis 内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_45526437/article/details/128276229

延伸 · 阅读

精彩推荐
  • Redisredis中队列消息实现应用解耦的方法

    redis中队列消息实现应用解耦的方法

    这篇文章主要给大家介绍了关于redis中队列消息实现应用解耦的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习...

    macccc3262019-11-16
  • RedisRedis配置文件详解

    Redis配置文件详解

    这篇文章主要介绍了Redis配置文件详解,本文详细完整的用中文解释了Redis配置文件中各种参数的作用和功能,需要的朋友可以参考下 ...

    Redis教程网5002019-10-23
  • Redis详解centos7 yum安装redis及常用命令

    详解centos7 yum安装redis及常用命令

    这篇文章主要介绍了centos7 yum安装redis及常用命令,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...

    钢铁侠的知识库1592020-12-20
  • RedisRedis之sql缓存的具体使用

    Redis之sql缓存的具体使用

    本文主要介绍了Redis之sql缓存的具体使用,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    yzm439910012022-01-24
  • Redisredis中热key问题该如何解决

    redis中热key问题该如何解决

    这篇文章主要给大家介绍了关于redis中热key问题该如何解决的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用redis具有一定的参考学习价...

    孤独烟8792019-11-24
  • RedisRedis热点之底层实现篇

    Redis热点之底层实现篇

    Redis提供了Java、C/C++、C#、 PHP 、JavaScript、 Perl 、Object-C、Python、Ruby、Erlang、Golang等多种主流语言的客户端,因此无论使用者是什么语言栈总会找到属于自己...

    今日头条2072020-05-27
  • RedisRedis中的数据过期策略详解

    Redis中的数据过期策略详解

    这篇文章主要介绍了Redis中的数据过期策略,文中通过示例代码介绍的很详细,相信对大家的理解和学习具有一定的参考借鉴价值,有需要的朋友可以参考借...

    chen5312019-11-01
  • RedisRedis消息队列发展历程

    Redis消息队列发展历程

    Redis从2010年发布1.0版本就具备一个消息队列的雏形,随着10多年的迭代,其消息队列的功能也越来越完善,作为一个全内存的消息队列,适合应用与要求高...

    阿里技术10382022-04-12