当前位置: 首页 > article >正文

(黑马点评)六、好友关注系列功能实现

6.1 关注与取关功能实现

        在博客应用里,关注和取关功能不可缺少。当你点击到一篇感兴趣的笔记,可以选择关注博主本人,添加关注后的用户,在后续关注用户发帖的时候,也能第一时间收到推送消息。

【接口说明】

关注或取关接口
判断是否关注接口

 【代码实现】

/**
     * 关注或取关
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {

        // 1. 取出当前登录的用户id 作为关注者的id
        Long userId = UserHolder.getUser().getId();

        // 2. 判断isFollow的值,判断实现关注 还是 取关
        if(BooleanUtil.isTrue(isFollow)){
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            follow.setCreateTime(LocalDateTime.now());
            // 3. 关注用户,则将followUserId 和 userid 添加到 tb_follow表中
            save(follow);
        }else{
            // 4. 取关用户,则将followUserId 和 userid 从 tb_follow表中删除
            remove(new QueryWrapper<Follow>()
                            .eq("user_id" ,userId)
                            .eq("follow_user_id",followUserId));
        }
        return Result.ok();
    }

【功能测试】 

6.2 共同关注功能实现

6.2.1 查看用户首页及笔记列表功能

        这个功能在前面已经实现过了,但是课程放在这里才实现。为了共同关注功能的展示,这部分需要实现。主要分两个功能:

1. 查询用户首页信息 -getUserById()

2. 查询用户的博客列表 -queryBlogByUserId()

查看用户首页实现 
查看用户首页
    /**
     * 根据id查询用户
     * @param userId
     * @return
     */
    @GetMapping("/{id}")
    public Result getUserById(@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);
    }
查看博客笔记列表实现 
查看博客列表
/**
     * 根据用户id查询探店笔记列表
     * @param current
     * @param id
     * @return
     */
    @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);
    }

 6.2.2 实现共同关注列表功能

        发起请求,查询两个人的列表,求列表的交集部分,作为共同关注列表返回。因此我们可以使用Redis中set集合的求交集的功能去完成。

1. 修改关注取关功能,将信息同步到Redis的Set集合之中
/**
     * 关注或取关
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {

        // 1. 取出当前登录的用户id 作为关注者的id
        Long userId = UserHolder.getUser().getId();

        // 2. 判断isFollow的值,判断实现关注 还是 取关
        if(BooleanUtil.isTrue(isFollow)){
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            follow.setCreateTime(LocalDateTime.now());
            // 3. 关注用户,则将followUserId 和 userid 添加到 tb_follow表中
            boolean isSuccess = save(follow);
            if(isSuccess){
                // 把关注用户信息存入Redis的set集合中
                stringRedisTemplate.opsForSet().add(RedisConstants.FOLLOWER_KEY + userId , followUserId.toString());
            }
        }else{
            // 4. 取关用户,则将followUserId 和 userid 从 tb_follow表中删除
            boolean isSuccess =  remove(new QueryWrapper<Follow>()
                                    .eq("user_id" ,userId)
                                    .eq("follow_user_id",followUserId));
            if(isSuccess){
                // 把关注用户信息从Redis的set集合中移除
                stringRedisTemplate.opsForSet().remove(RedisConstants.FOLLOWER_KEY + userId , followUserId.toString());
            }

        }
        return Result.ok();
    }

2. 实现共同关注接口
共同关注接口
/**
     * 查询共同关注
     * @param id
     * @return
     */
    @Override
    public Result followCommons(Long id) {
        // 获取用户信息
        Long userId = UserHolder.getUser().getId();
        String key1 = RedisConstants.FOLLOWER_KEY + userId;
        String key2 = RedisConstants.FOLLOWER_KEY + id;

        // 2. 求两者关注列表的交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);

        if(intersect==null || intersect.isEmpty() ){
            // 3. 如果没有共同关注,则返回空集合
            return Result.ok(Collections.emptyList());
        }

        // 3. 解析id集合
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());

        // 4. 查询数据库
        List<UserDTO> userDTOs = userService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOs);
        }
共同关注

6.3 关注推送功能实现

6.3.1 Feed流推送方案学习

        关注推送也叫Feed流,直译为投喂。为用户提供“沉浸式”的体验,通过无线下拉刷新获取新的信息。

Feed流常见的两中模式

Timeline:不做内容筛选,简单的按照内容发布时间排序,常用于好友或关注。例如朋友圈:  

        Ø优点:信息全面,不会有缺失。并且实现也相对简单

        Ø缺点:信息噪音较多,用户不一定感兴趣,内容获取效率低

智能排序:利用智能算法屏蔽掉违规的、用户不感兴趣的内容。推送用户感兴趣信息来吸引用户

        Ø优点:投喂用户感兴趣信息,用户粘度很高,容易沉迷

        Ø缺点:如果算法不精准,可能起到反作用

        本例中的个人页面,是基于关注的好友来做Feed流,因此采用Timeline的模式。该模式的实现方案有三种:

1. 拉模式 --- 也叫读扩散

每个消息只有一份。只有在读的时候才会拷贝一份出来,因此叫做读扩散。

        优点:节省空间,收件箱收完就可以扔掉,消息只需要存储一份。

        缺点:读取延迟高,每次拉去如果关注信息很多,排序、处理耗时长

2. 推模式  --- 也叫写扩散

博主给每个关注自己的用户都发一份信息到他们的收件箱

        优点:延迟低,登录及看

        缺点:内存占用极大,如果粉丝多,拷贝保存的信息就特别多了

3. 推拉结合 --- 读写混合

将粉丝群体分成普通粉丝和活跃粉丝,普通粉丝使用拉模式,活跃粉丝使用推模式

6.3.2 基于推模式实现关注推送功能

1. 实现向粉丝收件箱投放笔记
/**
     * 发布探店笔记
     * @param blog
     * @return
     */
    @PostMapping
    public Result saveBlog(@RequestBody Blog blog) {
        return blogService.saveBlog(blog);
    }

/**
     * 发布博客笔记
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        //1. 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //2. 保存探店博文
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("发布失败");
        }
        //3. 查询粉丝列表
        List<Follow> fansList = followService.query().eq("follow_user_id", user.getId()).list();

        //4. 将笔记发送到粉丝收件箱
        for (Follow fan : fansList) {
            Long userId = fan.getUserId();
            // 4.1 收件箱key
            String key = RedisConstants.FEED_KEY + userId;
            // 4.2 发送消息
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }
feed收件箱

 

2. 实现关注推送页面的滚动分页查询功能

Redis滚动分页查询一共有4个参数,分别为

MAX

        第一次:当前时间戳;

        后续:上一次的最小值

MIN: 0 (时间戳的最小值)

OFFSET

        第一次:0

        后续:取决于上一次查询的结果,上一次结果中,与最小值一样元素个数是几,就是几

COUN:3(前后端规定好,每次查3条)

请求分页接口

实现步骤

0. 准备封装类

1. 获取当前用户

2. 根据当前用户id,获得收件箱

3. 使用Redis命令,滚动分页查询收件箱内容

4. 解析收件箱数据,包括(blogId 、minTime、offset)

5. 根据blogIdlist 查询相应的blog

6. 对于每一条blog,查询博主和是否点赞

        queryBlogUser(blog);

        isBlogLiked(blog);

// DTO对象中添加封装类
@Data
public class ScrollResult {
    // 当前页数据
    private List<?> list;
    // 上次查询最小时间
    private Long minTime;
    // 偏移量
    private Integer offset;
}



    /**
     *滚动分页查询关注推送笔记
     * @param max
     * @param offset
     * @return
     */
    @GetMapping("/of/follow")
    public Result queryBlogOfFollow(
            @RequestParam("lastId") Long max,
            @RequestParam(value = "offset" ,defaultValue = "0") Integer offset) {
        return blogService.queryBlogOfFollow(max,offset);
    }



/**
     * 滚动分页查询推送关注笔记
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 1. 获取当前登录用户
        Long userId = UserHolder.getUser().getId();

        // 2. 获取收件箱信息 ----> 博客id、score(时间戳)
        String key = RedisConstants.FEED_KEY + userId;

        // 滚动分页查询 Z_REV_RANGE_BY_SCORE key min max LIMIT offset count
        Set<ZSetOperations.TypedTuple<String>> typedTuples =  stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key,0, max, offset, 3);

        // 非空判断
        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok(Collections.emptyList());
        }

        // 3. 解析收件箱数据 blogId 、minTime、offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for(ZSetOperations.TypedTuple<String> tuple : typedTuples){
            // 3.1 获取id
            String idStr = tuple.getValue();
            // 将id放到list集合
            ids.add(Long.valueOf(idStr));
            //3.2 获取分数
            long time = tuple.getScore().longValue();
            if(time == minTime){
                os++;
            }
            else{
                os=1;
                minTime = time;
            }
        }

        // 4. 根据id查询blog
        List<Blog> blogs = query().in("id",ids).last("ORDER BY FIELD(id," + StrUtil.join(",", ids) + ")").list();

        for(Blog blog : blogs){
            //4.2 查询blog相关的用户
            queryBlogUser(blog);
            //4.2 查询blog是否点赞
            isBlogLiked(blog);
        }

        //5. 封装返回
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(minTime);

        return Result.ok(r);
    }


    /**
     * 查询点赞状态
     * @param blog
     */
    private void isBlogLiked(Blog blog) {
        // 1.判断当前用户有没点赞
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return;
        }
        Long userId = user.getId();
        // 2.查询点赞状态
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        Double score =  stringRedisTemplate.opsForZSet().score(key,userId.toString());
        blog.setIsLike(score != null);
    }


    /**
     * 复用方法封装
     * @param blog
     */
    private void queryBlogUser(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }


测试

 


http://www.kler.cn/news/309505.html

相关文章:

  • C语言 | Leetcode C语言接雨水II
  • vscode中前端项目文件格式化备份
  • Apple M3编译OpenSSL安卓平台SO库
  • django orm查询优化
  • Unity常用随机数算法
  • linux-Shell 编程-常用 Shell 脚本技巧
  • Python--数据格式转换
  • 在react中 使用redux
  • ubuntu安装wordpress(基于LNMP环境)
  • GBase8c主备版500升级步骤
  • 演示:基于WPF自绘的中国省份、城市、区县矢量地图
  • android 识别设备是否为模拟器
  • MySQL 按照条件(分组)只取一个形成列表 group max
  • PostgresML:通过 PostgreSQL 集成简化 AI 模型部署
  • git reset 几点疑问
  • 50ETF期权可以当天买卖吗?
  • 2024年10月蓝桥杯青少组的Stema考试开始报名
  • React两种路由模式的实现原理
  • 高防IP是如何防御攻击
  • 苹果电脑也可以清除垃圾吗?苹果电脑清理垃圾用什么软件哪个好?
  • 运用Java实现倒计时功能
  • 工业智能网关未来工业智能化的核心枢纽-天拓四方
  • 战神诸神黄昏9月19日登录PC端! 手机怎么玩战神诸神黄昏
  • 记录开发一个英语听力训练网站
  • 中断和异常处理
  • 【信息论基础第二讲】离散信源的数学模型及其信息测度包括信源的分类、信源的数学模型、离散信源的信息测度、二元信源的条件熵联合熵
  • 相亲交友小程序:轻松找到你的另一半
  • postgresql|数据库|pg_repack和idle_in_transaction_session_timeout参数的关系
  • rabbitmq备份还原
  • Qt QSerialPort串口编程