黑马点评 实现滚动分页查询关注博客

实现代码

首先,想要实现关注的人,并且按照时间戳排序,可以选择redis中的sorted set数据结构。详细代码如下:

controller层

    @GetMapping("/of/follow")
    public Result queryBlogOfFollow(@RequestParam("lastId") Long max,@RequestParam(value = "offset",defaultValue = "0")Integer offset){
        return blogService.queryBlogOfFollow(max,offset);
    }

service层

public interface IBlogService extends IService<Blog> {

    Result queryBlog(Long id);

    Result likeBlog(Long id);

    Result queryHotBlog(Integer current);

    Result queryBlogLikes(Long id);

    Result saveblog(Blog blog);

    Result queryBlogOfFollow(Long max, Integer offset);
}

serviceImpl

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1 获取当前用户ID
        Long userId = UserHolder.getUser().getId();
        //2 查询收件箱
        String key="feed:"+userId.toString();
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);

        //3 非空判断
        if(typedTuples == null ||typedTuples.isEmpty()){
            return Result.ok();
        }
        //4 解析数据 这里的ids存放的实际上是博客 id
        List<Long> ids=new ArrayList<>(typedTuples.size());
        long minTime=0;
        int os=1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //获取id
            ids.add(Long.valueOf(typedTuple.getValue()));
            //获取分数(时间戳)
            long time=typedTuple.getScore().longValue();
            if(time==minTime){
                os++;
            }else {
                minTime=time;
                os=1;
            }

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

        for (Blog blog : blogs) {
            isBlogLiked(blog);
        }
        //6 封装并返回
        ScrollResult scrollResult=new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);

        return Result.ok(scrollResult);
    }

我的一些理解:

对于实现冬天查询关注的人博客来说,我们需要一个数据结构

@Data
public class ScrollResult {
    private List<?> list;
    private Long minTime;
    private Integer offset;
}

我们对list做了泛型处理,确保以后在别的地方也可以用到这种数据结构。

在serviceImpl中,我们的思路如下:

首先我们查询的肯定是当前登录用户的关注的人的博客动态,因此可以用

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

来获取当前用户的id。

之后我们通过redis中的收件箱去拿到数据,最后封装成ScrollResult这样一个结果返回。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值