实现代码
首先,想要实现关注的人,并且按照时间戳排序,可以选择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这样一个结果返回。