服务实现类 @author 虎哥 @since 2021-12-22
| 43 | * @since 2021-12-22 |
| 44 | */ |
| 45 | @Service |
| 46 | public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService { |
| 47 | |
| 48 | @Resource |
| 49 | private IUserService userService; |
| 50 | |
| 51 | @Resource |
| 52 | private IFollowService followService; |
| 53 | |
| 54 | @Resource |
| 55 | private StringRedisTemplate stringRedisTemplate; |
| 56 | @Override |
| 57 | public Result queryHotBlog(Integer current) { |
| 58 | // 根据用户查询 |
| 59 | Page<Blog> page = query() |
| 60 | .orderByDesc("liked") |
| 61 | .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE)); |
| 62 | // 获取当前页数据 |
| 63 | List<Blog> records = page.getRecords(); |
| 64 | // 查询用户 |
| 65 | records.forEach(blog -> { |
| 66 | this.isBlogLiked(blog); |
| 67 | this.queryBlogUser(blog); |
| 68 | }); |
| 69 | return Result.ok(records); |
| 70 | } |
| 71 | |
| 72 | @Override |
| 73 | public Result updateLike(Long id){ |
| 74 | //1.获取当前用户 |
| 75 | Long userId = UserHolder.getUser().getId(); |
| 76 | //2.判断当前用户有没有点赞 |
| 77 | String key=BLOG_LIKED_KEY+id; |
| 78 | Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString()); |
| 79 | if(score==null) { |
| 80 | //3.如果未点赞,可以点赞 |
| 81 | //3.1.数据库点赞数+1 |
| 82 | boolean isSuccess = update().setSql("liked=liked+1").eq("id", id).update(); |
| 83 | //3.2.保存用户到redis的set集合 zadd key value score |
| 84 | if(isSuccess){ |
| 85 | stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis()); |
| 86 | } |
| 87 | }else { |
| 88 | //4.如果已经点赞,取消点赞 |
| 89 | //4.1.数据库点赞数-1 |
| 90 | boolean isSuccess = update().setSql("liked=liked-1").eq("id", id).update(); |
| 91 | if(isSuccess) { |
| 92 | //4.2.将用户从set集合中移除 |
| 93 | stringRedisTemplate.opsForZSet().remove(key,userId.toString()); |
| 94 | } |
| 95 | } |
| 96 | return Result.ok(); |
| 97 | } |
| 98 | |
| 99 | @Override |
| 100 | public Result queryBlogLikes(Long id) { |
| 101 | //1.查询top5的点赞用户 |
| 102 | String key=BLOG_LIKED_KEY+id; |
nothing calls this directly
no outgoing calls
no test coverage detected