关注和取消关注
在查看笔记详情时,会自动发送请求,调用接口来检查当前用户是否已经关注了笔记作者,我们要实现这两个接口
关注是User之间的关系,是博主与粉丝的关系,数据库中有一张tb_follow表来标识,我们要将用户与博主关联起来,只需要向这张表插入数据即可,需要将主键设为自增加,降低开发难度
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);
}
判断当前用户与博主是否已经关注了博主我们只需要查询follow表中是否有记录即可,等值查询建议进行非空判断,防止出现异常
@Override
public Result isFollow(Long followUserId) {
Long userId = UserHolder.getUser().getId();
LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(followUserId != null, Follow::getFollowUserId, followUserId)
.eq(userId != null, Follow::getUserId, userId);
Integer count = followMapper.selectCount(queryWrapper);
return Result.ok(count > 0);
}
前端发送请求时,会发送isFollow这个boolean值,用来让后端判断当前用户是否已经关注了博主,如果为true,则直接插入数据库,表示关注成功,如果为false,表示已经关注要取消关注了
@Override
public Result follow(Long followUserId, Boolean isFollow) {
Long userId = UserHolder.getUser().getId();
String key = "follows:" + userId;
if (isFollow) {
//封装follow对象
Follow follow = new Follow();
follow.setFollowUserId(followUserId);
follow.setUserId(userId);
follow.setCreateTime(LocalDateTime.now());
//插入数据库
boolean isSuccess = save(follow);
} else {
LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Follow::getFollowUserId, followUserId)
.eq(Follow::getUserId, userId);
boolean isSuccess = remove(queryWrapper);
}
return Result.ok();
}
共同关注
// 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 根据id查询博主的探店笔记
@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);
}
首先对添加关注进行改造,在插入数据的同时也要将当前用户关注的博主用户id插入到set集合中去,用于查找交集
@Override
public Result follow(Long followUserId, Boolean isFollow) {
Long userId = UserHolder.getUser().getId();
String key = "follows:" + userId;
if (isFollow) {
//封装follow对象
Follow follow = new Follow();
follow.setFollowUserId(followUserId);
follow.setUserId(userId);
follow.setCreateTime(LocalDateTime.now());
//插入数据库
boolean isSuccess = save(follow);
if (isSuccess) {
stringRedisTemplate.opsForSet().add(key, followUserId.toString());
}
} else {
LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Follow::getFollowUserId, followUserId)
.eq(Follow::getUserId, userId);
boolean isSuccess = remove(queryWrapper);
if (isSuccess) {
stringRedisTemplate.opsForSet().remove(key);
}
}
return Result.ok();
}
controller层,定义common接口,传入的id是笔记博主的id
@GetMapping("/common/{id}")
public Result common(@PathVariable("id") Long id){
System.out.println(id);
return followService.commonFollow(id);
}
service层
@Override
public Result commonFollow(Long id) {
//获取当前用户
Long userId = UserHolder.getUser().getId();
String key1 = "follows:" + userId;
String key2 = "follows:" + id;
Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
if(intersect == null || intersect.isEmpty()) {
// 无交集
return Result.ok(Collections.emptyList());
}
//解析用户id集合
List<Long> userIds = intersect.stream().map(item -> Long.valueOf(item)).collect(Collectors.toList());
List<UserDTO> users = userService.selectByIds(userIds).stream().map(
user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
return Result.ok(users);
}
Feed流实现方案
当我们关注了用户后,这个用户发了动态,那么我们应该把这些数据推送给用户,这个需求,其实我们又把他叫做Feed流,关注推送也叫做Feed流,直译为投喂。为用户持续的提供“沉浸式”的体验,通过无限下拉刷新获取新的信息。
对于传统的模式的内容解锁:我们是需要用户去通过搜索引擎或者是其他的方式去解锁想要看的内容
对于新型的Feed流的的效果:不需要我们用户再去推送信息,而是系统分析用户到底想要什么,然后直接把内容推送给用户,从而使用户能够更加的节约时间,不用主动去寻找。类似B站,抖音等平台的大数据推送机制
Feed流的两种模式
Feed流的实现有两种模式:
Feed流产品有两种常见模式: Timeline:不做内容筛选,简单的按照内容发布时间排序,常用于好友或关注。例如朋友圈
-
优点:信息全面,不会有缺失。并且实现也相对简单
-
缺点:信息噪音较多,用户不一定感兴趣,内容获取效率低
智能排序:利用智能算法屏蔽掉违规的、用户不感兴趣的内容。推送用户感兴趣信息来吸引用户
-
优点:投喂用户感兴趣信息,用户粘度很高,容易沉迷
-
缺点:如果算法不精准,可能起到反作用。 本例中的个人页面,是基于关注的好友来做Feed流,因此采用Timeline的模式。该模式的实现方案有三种
Timeline模式的实现方案
拉模式:也叫做读扩散
推模式:也叫做写扩散。
推拉结合模式:也叫做读写混合,兼具推和拉两种模式的优点。
推送到粉丝收件箱
分页查询方案
分页演示
首先创建一个Zset集合
通过这一命令我们可以通过score值降序排的方式取出前三条记录,这么看似乎没有问题,我们下一页要查询的就是后四条记录,但feed流的数据是不断更新,恰好此时set集合中加入m8
zrevrange z1 0 2 withscores
后三条记录的查询理论上是再查三条,这时候按照角标查m5就已经重复查询了,这在业务中是不允许的
按照score值来查就可以避免该问题,我们只需要记住上一次查询的最小分数,让它在下次查询时最为max,即可实现分页查询,limit 后面的第一个参数即是偏移量,0表示要包含max,1表示小于max分数的下一个元素
zrevrangebyscore z1 6 0 withscores limit 1 3
推送收件箱
当用户发送完笔记后,也要将笔记推送粉丝的收件箱中,即用户id为key的zest集合中
@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.查询笔记作者的所有粉丝 select * from tb_follow where follow_user_id = ?
List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
// 4.推送笔记id给所有粉丝
for (Follow follow : follows) {
// 4.1.获取粉丝id
Long userId = follow.getUserId();
// 4.2.推送
String key = FEED_KEY + userId;
stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
}
// 5.返回id
return Result.ok(blog.getId());
}
实现分页查询收邮箱
定义返回实体类
@Data
public class ScrollResult {
private List<?> list;
private Long minTime;
private Integer offset;
}
BlogController
注意:RequestParam 表示接受url地址栏传参的注解,当方法上参数的名称和url地址栏不相同时,可以通过RequestParam 来进行指定
@GetMapping("/of/follow")
public Result queryBlogOfFollow(
@RequestParam("lastId") Long max, @RequestParam(value = "offset", defaultValue = "0") Integer offset){
return blogService.queryBlogOfFollow(max, offset);
}
BlogServiceImpl
@Override
public Result queryBlogOfFollow(Long max, Integer offset) {
// 1.获取当前用户
Long userId = UserHolder.getUser().getId();
// 2.查询收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset count
String key = FEED_KEY + userId;
Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
.reverseRangeByScoreWithScores(key, 0, max, offset, 2);
// 3.非空判断
if (typedTuples == null || typedTuples.isEmpty()) {
return Result.ok();
}
// 4.解析数据:blogId、minTime(时间戳)、offset
List<Long> ids = new ArrayList<>(typedTuples.size());
long minTime = 0; // 2
int os = 1; // 2
for (ZSetOperations.TypedTuple<String> tuple : typedTuples) { // 5 4 4 2 2
// 4.1.获取id
ids.add(Long.valueOf(tuple.getValue()));
// 4.2.获取分数(时间戳)
long time = tuple.getScore().longValue();
if(time == minTime){
os++;
}else{
minTime = time;
os = 1;
}
}
os = minTime == max ? os : os + offset;
// 5.根据id查询blog
String idStr = StrUtil.join(",", ids);
List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
for (Blog blog : blogs) {
// 5.1.查询blog有关的用户
queryBlogUser(blog);
// 5.2.查询blog是否被点赞
isBlogLiked(blog);
}
// 6.封装并返回
ScrollResult r = new ScrollResult();
r.setList(blogs);
r.setOffset(os);
r.setMinTime(minTime);
return Result.ok(r);
}