大众点评项目 好友关注 共同关注
- 需求:好友关注 共同关注
- 业务逻辑展示
- 点击关注功能实现
- 判断当前用户是否关注了此博主
- 共同好友列表查询
- 业务逻辑实现
- 双指针筛选DB数据
- Redis取交集
- 总结
SpringCloud章节复习已经过去,新的章节Redis开始了,这个章节中将会回顾Redis实战项目 大众点评
主要依照以下几个原则
- 基础+实战的Demo和Coding上传到我的代码仓库
- 在原有基础上加入一些设计模式,stream+lamdba等新的糖
- 通过DeBug调试,进入组件源码去分析底层运行的规则和设计模式
代码会同步在我的gitee中去,觉得不错的同学记得一键三连求关注,感谢:
Redis优化-链接: RedisCommonFollowProject
需求:好友关注 共同关注
成果展示:共同关注列表查询
这里给出两种方案,
- DB查询的话,两次数据库查询IO,并且可以通过基本的stream流处理数据,进行排序等处理,通过双指针筛选,保证时间复杂度为N
- Redis取交集,本身就是缓存数据库,通过封装的API操作,查询
后面可以通过通过一些压测工具,JMX进行对比和梳理,先天结构上猜测,在大部分情况下,Redis应该是更快的那个
业务逻辑展示
点击关注功能实现
判断当前用户是否关注了此博主
共同好友列表查询
业务逻辑实现
双指针筛选DB数据
** Controller层 - 实现 **
* @PathVariable主要用于接收http://host:port/path/{参数值}数据。* @RequestParam主要用于接收http://host:port/path?参数名=参数值数据,这里后面也可以不跟参数值。
@RestController
@RequestMapping("/blog")
public class BlogController {@Resourceprivate IBlogService blogService;@PostMappingpublic Result saveBlog(@RequestBody Blog blog) {// 获取登录用户UserDTO user = UserHolder.getUser();blog.setUserId(user.getId());// 保存探店博文blogService.save(blog);// 返回idreturn Result.ok(blog.getId());}@PutMapping("/like/{id}")public Result likeBlog(@PathVariable("id") Long id) {// 修改点赞数量return blogService.likeBlog(id);}@GetMapping("/of/me")public Result queryMyBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {// 获取登录用户UserDTO user = UserHolder.getUser();// 根据用户查询Page<Blog> page = blogService.query().eq("user_id", user.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));// 获取当前页数据List<Blog> records = page.getRecords();return Result.ok(records);}@GetMapping("/hot")public Result queryHotBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {return blogService.queryHotBlog(current);}@GetMapping("/{id}")public Result queryBlogById(@PathVariable("id") Long id){return blogService.queryBlogById(id);}@GetMapping("/likes/{id}")public Result likesBlog(@PathVariable("id") Long id) {// 修改点赞数量return blogService.queryBlogLikes(id);}/*** @RequestParam与@PathVariable为spring的注解,都可以用于在Controller层接收前端传递的数据,不过两者的应用场景不同。** @PathVariable主要用于接收http://host:port/path/{参数值}数据。* @RequestParam主要用于接收http://host:port/path?参数名=参数值数据,这里后面也可以不跟参数值。* @param current* @param id* @return*/@GetMapping("/of/user")public Result queryBlogByUserId(@RequestParam(value = "current", defaultValue = "1") Integer current,@RequestParam("id") Long id){return blogService.queryBlogByUserId(current, id);}}
** Service层 - 实现 **
@Slf4j
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {@Resourceprivate IUserService userService;@Overridepublic Result followJudge(Long id, Boolean isFollow) {UserDTO user = UserHolder.getUser();if(isFollow){Follow follow = new Follow();follow.setUserId(user.getId()).setFollowUserId(id);save(follow);}else{
// removeById(new QueryWrapper<Follow>().eq("user_id", user.getId())
// .eq("follow_user_id", id));log.debug("QueryChainWrapper" + query().select("id").eq("user_id", user.getId()).eq("follow_user_id", id));log.debug("Integer count = " + query().count());remove(new QueryWrapper<Follow>().eq("user_id", user.getId()).eq("follow_user_id", id));}return Result.ok();}@Overridepublic Result isFollowJudge(Long id) {UserDTO user = UserHolder.getUser();Integer idNum = query().eq("user_id", user.getId()).eq("follow_user_id", id).count();return Result.ok(idNum > 0);}
共同好友功能实现;
-
双指针
判断思想: 有序 数组A{ 1 5 8 15} B{ 8 9 15 17 22}逻辑判断大小, 选取A中最小的和B对比, 1<8 5 < 8 8=8 指针A 左移动,指针B左移,15 》9, 指针B左移,直至两边指针有一个结束为止
/*** @Function 共同好友* @param blogHostId* @return*/@Overridepublic Result isCommonFollow(Long blogHostId) {Long userId = UserHolder.getUser().getId();if(userId==null){return Result.fail("需要登录后进行");}List<Long> userFollowList = query().eq("user_id", userId).list().stream().map(s->s.getFollowUserId()).sorted().collect(Collectors.toList());List<Long> hostFollowList = query().eq("user_id", blogHostId).list().stream().map(s->s.getFollowUserId()).sorted().collect(Collectors.toList());List<Long> commonFollowList = new ArrayList<>();/*** 没啥暴力呗,两个For,直接n*n*/
/* userFollowList.stream().forEach(s->{for (int i = 0; i < hostFollowList.size(); i++) {//这里遍历的时间复杂度是n*n,我们可以使用双指针法,可以使时间复杂度 缩短为 nif(s.equals(hostFollowList.get(i))){commonFollowList.add(s);break;}}});*//*** 判断思想: 有序 数组A{ 1 5 8 15} B{ 8 9 15 17 22}* 逻辑判断大小, 选取A中最小的和B对比, 1<8 5 < 8 8=8 指针A 左移动,指针B左移,* 15 》9, 指针B左移,直至两边指针有一个结束为止*/int pointA = 0, pointB = 0;while(pointA<userFollowList.size() && pointB<hostFollowList.size()){if(userFollowList.get(pointA).equals(hostFollowList.get(pointB))){commonFollowList.add(userFollowList.get(pointA));pointA++;pointB++;}else if(userFollowList.get(pointA)<hostFollowList.get(pointB)){pointA++;}else{pointB++;}}List<UserDTO> userList = commonFollowList.stream().map(id -> {User user = userService.query().eq("id", id).one();return BeanUtil.copyProperties(user, UserDTO.class);}).collect(Collectors.toList());if (userList == null) {return Result.ok("没有共同关注的好友");}return Result.ok(userList);}
}
Redis取交集
存取类型:Set
通过Redis相关API:intersect
@Overridepublic Result followJudge(Long id, Boolean isFollow) {//id:博主ID userId:当前账号IDUserDTO user = UserHolder.getUser();if(user==null){return Result.fail("尚未登录");}String key = RedisConstants.FOLLOW_ID + user.getId();if(isFollow){Follow follow = new Follow();follow.setUserId(user.getId()).setFollowUserId(id);boolean isSave = save(follow);if (isSave) {stringRedisTemplate.opsForSet().add(key, id.toString());}}else{
// removeById(new QueryWrapper<Follow>().eq("user_id", user.getId())
// .eq("follow_user_id", id));log.debug("QueryChainWrapper" + query().select("id").eq("user_id", user.getId()).eq("follow_user_id", id));log.debug("Integer count = " + query().count());boolean isRemove = remove(new QueryWrapper<Follow>().eq("user_id", user.getId()).eq("follow_user_id", id));if (isRemove) {stringRedisTemplate.opsForSet().remove(key, id.toString());}}return Result.ok();}
/*** @Function 共同好友* @param blogHostId* @return*/@Overridepublic Result isCommonFollow(Long blogHostId) {Long userId = UserHolder.getUser().getId();String userKey = RedisConstants.FOLLOW_ID + userId;String blogHostKey = RedisConstants.FOLLOW_ID + blogHostId;Set<String> intersect = stringRedisTemplate.opsForSet().intersect(userKey, blogHostKey);if (intersect == null || intersect.isEmpty()) {return Result.ok(Collections.emptyList());}List<Long> idList = intersect.stream().map(Long::valueOf).collect(Collectors.toList());List<UserDTO> userList = userService.listByIds(idList).stream().map(user -> {return BeanUtil.copyProperties(user, UserDTO.class);}).collect(Collectors.toList());return Result.ok(userList);}
总结两个API使用:
求交集 stringRedisTemplate.opsForSet().intersect(userKey, blogHostKey);
set存数据:stringRedisTemplate.opsForSet().add(key, id.toString());
set删除数据: stringRedisTemplate.opsForSet().remove(key, id.toString()); }
MP的查询构造器:remove(new QueryWrapper<Follow>().eq("user_id", user.getId()) .eq("follow_user_id", id));