【探花交友】day05—圈子互动(下)

本文涉及的产品
云原生内存数据库 Tair,内存型 2GB
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Redis 版,经济版 1GB 1个月
简介: 【探花交友】day05—圈子互动(下)

2.2、动态评论

功能包括:查询评论列表,发布评论,对评论点赞和取消点赞。

2.2.1 分页列表查询

CommentController

1. //分页查询评理列表
2. @GetMapping
3. public ResponseEntity findComments(@RequestParam(defaultValue = "1") Integer page,
4.                                 @RequestParam(defaultValue = "10") Integer pagesize,
5.                                    String movementId) {
6. PageResult pr = commentsService.findComments(movementId,page,pagesize);
7. return ResponseEntity.ok(pr);
8. }

CommentService

1. //分页查询评理列表
2. public PageResult findComments(String movementId, Integer page, Integer pagesize) {
3. //1、调用API查询评论列表
4.     List<Comment> list = commentApi.findComments(movementId,CommentType.COMMENT,page,pagesize);
5. //2、判断list集合是否存在
6. if(CollUtil.isEmpty(list)) {
7. return new PageResult();
8.     }
9. //3、提取所有的用户id,调用UserInfoAPI查询用户详情
10.     List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
11.     Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
12. //4、构造vo对象
13.     List<CommentVo> vos = new ArrayList<>();
14. for (Comment comment : list) {
15. UserInfo userInfo = map.get(comment.getUserId());
16. if(userInfo != null) {
17. CommentVo vo = CommentVo.init(userInfo, comment);
18.             vos.add(vo);
19.         }
20.     }
21. //5、构造返回值
22. return new PageResult(page,pagesize,0l,vos);
23. }

CommentAPI

1. //分页查询
2. public List<Comment> findComments(String movementId, CommentType commentType, Integer page, Integer pagesize) {
3. //1、构造查询条件
4. Query query = Query.query(Criteria.where("publishId").is(new ObjectId(movementId)).and("commentType")
5.             .is(commentType.getType()))
6.             .skip((page -1) * pagesize)
7.             .limit(pagesize)
8.             .with(Sort.by(Sort.Order.desc("created")));
9. //2、查询并返回
10. return mongoTemplate.find(query,Comment.class);
11. }

 

2.2.2 发布评论

CommentController

1. @RestController
2. @RequestMapping("/comments")
3. public class CommentsController {
4. 
5. 
6. @Autowired
7. private CommentsService commentsService;
8. 
9. /**
10.      * 发布评论
11.      */
12. @PostMapping
13. public ResponseEntity saveComments(@RequestBody Map map) {
14. String movementId = (String )map.get("movementId");
15. String comment = (String)map.get("comment");
16.         commentsService.saveComments(movementId,comment);
17. return ResponseEntity.ok(null);
18.     }
19. }

CommentService

1. @Service
2. @Slf4j
3. public class CommentsService {
4. 
5. @DubboReference
6. private CommentApi commentApi;
7. 
8. //发布评论
9. public void saveComments(String movementId, String comment) {
10. //1、获取操作用户id
11. Long userId = UserHolder.getUserId();
12. //2、构造Comment
13. Comment comment1 = new Comment();
14.         comment1.setPublishId(new ObjectId(movementId));
15.         comment1.setCommentType(CommentType.COMMENT.getType());
16.         comment1.setContent(comment);
17.         comment1.setUserId(userId);
18.         comment1.setCreated(System.currentTimeMillis());
19. //3、调用API保存评论
20. Integer commentCount = commentApi.save(comment1);
21.         log.info("commentCount = " + commentCount);
22.     }
23. }

CommentAPI

1. //发布评论,并获取评论数量
2. public Integer save(Comment comment) {
3. //1、查询动态
4. Movement movement = mongoTemplate.findById(comment.getPublishId(), Movement.class);
5. //2、向comment对象设置被评论人属性
6. if(movement != null) {
7.         comment.setPublishUserId(movement.getUserId());
8.     }
9. //3、保存到数据库
10.     mongoTemplate.save(comment);
11. //4、更新动态表中的对应字段
12. Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
13. Update update = new Update();
14. if(comment.getCommentType() == CommentType.LIKE.getType()) {
15.         update.inc("likeCount",1);
16.     }else if (comment.getCommentType() == CommentType.COMMENT.getType()){
17.         update.inc("commentCount",1);
18.     }else {
19.         update.inc("loveCount",1);
20.     }
21. //设置更新参数
22. FindAndModifyOptions options = new FindAndModifyOptions();
23.     options.returnNew(true) ;//获取更新后的最新数据
24. Movement modify = mongoTemplate.findAndModify(query, update, options, Movement.class);
25. //5、获取最新的评论数量,并返回
26. return modify.statisCount(comment.getCommentType() );
27. }

测试API代码

1. @RunWith(SpringRunner.class)
2. @SpringBootTest(classes = AppServerApplication.class)
3. public class CommentApiTest {
4. 
5. @DubboReference
6. private CommentApi commentApi;
7. 
8. @Test
9. public void testSave() {
10. Comment comment = new Comment();
11.         comment.setCommentType(CommentType.COMMENT.getType());
12.         comment.setUserId(106l);
13.         comment.setCreated(System.currentTimeMillis());
14.         comment.setContent("测试评论");
15.         comment.setPublishId();
16.         commentApi.save(comment);
17.     }
18. }

2.3、点赞

2.3.1、编写Controller

修改MovementsController代码,添加点赞与取消点赞方法

1. /**
2.  * 点赞
3.  */
4. @GetMapping("/{id}/like")
5. public ResponseEntity like(@PathVariable("id") String movementId) {
6. Integer likeCount = commentsService.likeComment(movementId);
7. return ResponseEntity.ok(likeCount);
8. }
9. 
10. /**
11.  * 取消点赞
12.  */
13. @GetMapping("/{id}/dislike")
14. public ResponseEntity dislike(@PathVariable("id") String movementId) {
15. Integer likeCount = commentsService.dislikeComment(movementId);
16. return ResponseEntity.ok(likeCount);
17. }

2.3.2、编写Service

创建CommentService,添加点赞与取消点赞方法

1. //动态点赞
2. public Integer likeComment(String movementId) {
3. //1、调用API查询用户是否已点赞
4. Boolean hasComment = commentApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LIKE);
5. //2、如果已经点赞,抛出异常
6. if(hasComment) {
7. throw  new BusinessException(ErrorResult.likeError());
8.     }
9. //3、调用API保存数据到Mongodb
10. Comment comment = new Comment();
11.     comment.setPublishId(new ObjectId(movementId));
12.     comment.setCommentType(CommentType.LIKE.getType());
13.     comment.setUserId(UserHolder.getUserId());
14.     comment.setCreated(System.currentTimeMillis());
15. Integer count = commentApi.save(comment);
16. //4、拼接redis的key,将用户的点赞状态存入redis
17. String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
18. String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
19.     redisTemplate.opsForHash().put(key,hashKey,"1");
20. return count;
21. }
22. 
23. 
24. //取消点赞
25. public Integer dislikeComment(String movementId) {
26. //1、调用API查询用户是否已点赞
27. Boolean hasComment = commentApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LIKE);
28. //2、如果未点赞,抛出异常
29. if(!hasComment) {
30. throw new BusinessException(ErrorResult.disLikeError());
31.     }
32. //3、调用API,删除数据,返回点赞数量
33. Comment comment = new Comment();
34.     comment.setPublishId(new ObjectId(movementId));
35.     comment.setCommentType(CommentType.LIKE.getType());
36.     comment.setUserId(UserHolder.getUserId());
37. Integer count = commentApi.delete(comment);
38. //4、拼接redis的key,删除点赞状态
39. String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
40. String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
41.     redisTemplate.opsForHash().delete(key,hashKey);
42. return count;
43. }

2.3.3、修改API服务

判断Comment数据是否存在

1. //判断comment数据是否存在
2. public Boolean hasComment(String movementId, Long userId, CommentType commentType) {
3. Criteria criteria = Criteria.where("userId").is(userId)
4.             .and("publishId").is(new ObjectId(movementId))
5.             .and("commentType").is(commentType.getType());
6. Query query = Query.query(criteria);
7. return mongoTemplate.exists(query,Comment.class); //判断数据是否存在
8. }

删除互动数据

1. //删除
2. public Integer delete(Comment comment) {
3. //1、删除Comment表数据
4. Criteria criteria = Criteria.where("userId").is(comment.getUserId())
5.             .and("publishId").is(comment.getPublishId())
6.             .and("commentType").is(comment.getCommentType());
7. Query query = Query.query(criteria);
8.     mongoTemplate.remove(query,Comment.class);
9. //2、修改动态表中的总数量
10. Query movementQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
11. Update update = new Update();
12. if(comment.getCommentType() == CommentType.LIKE.getType()) {
13.         update.inc("likeCount",-1);
14.     }else if (comment.getCommentType() == CommentType.COMMENT.getType()){
15.         update.inc("commentCount",-1);
16.     }else {
17.         update.inc("loveCount",-1);
18.     }
19. //设置更新参数
20. FindAndModifyOptions options = new FindAndModifyOptions();
21.     options.returnNew(true) ;//获取更新后的最新数据
22. Movement modify = mongoTemplate.findAndModify(movementQuery, update, options, Movement.class);
23. //5、获取最新的评论数量,并返回
24. return modify.statisCount(comment.getCommentType() );
25. }

2.3.4、修改查询动态点赞数

修改之前的查询圈子列表代码,从redis查询是否具有操作记录

2.4、喜欢

喜欢和取消喜欢:和刚才的点赞与取消点赞基本上市一模一样的!操作的类型comment_type=3,操作的字段loveCount

MovementsController

修改MovementsController代码,添加喜欢与取消喜欢方法

1. /**
2.  * 喜欢
3.  */
4. @GetMapping("/{id}/love")
5. public ResponseEntity love(@PathVariable("id") String movementId) {
6. Integer likeCount = commentsService.loveComment(movementId);
7. return ResponseEntity.ok(likeCount);
8. }
9. 
10. /**
11.  * 取消喜欢
12.  */
13. @GetMapping("/{id}/unlove")
14. public ResponseEntity unlove(@PathVariable("id") String movementId) {
15. Integer likeCount = commentsService.disloveComment(movementId);
16. return ResponseEntity.ok(likeCount);
17. }

CommentService

修改CommentService,添加点赞与取消点赞方法

1. /**
2.  * 喜欢
3.  */
4. @GetMapping("/{id}/love")
5. public ResponseEntity love(@PathVariable("id") String movementId) {
6. Integer likeCount = commentsService.loveComment(movementId);
7. return ResponseEntity.ok(likeCount);
8. }
9. 
10. /**
11.  * 取消喜欢
12.  */
13. @GetMapping("/{id}/unlove")
14. public ResponseEntity unlove(@PathVariable("id") String movementId) {
15. Integer likeCount = commentsService.disloveComment(movementId);
16. return ResponseEntity.ok(likeCount);
17. }

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
1月前
|
NoSQL 搜索推荐 API
day05—圈子互动
day05—圈子互动
33 0
|
8月前
|
双11
为什么头条和抖音上这么多人月入好几万?
为什么头条和抖音上这么多人月入好几万?
|
11月前
|
存储 NoSQL 搜索推荐
【探花交友】day05—圈子互动(上)
【探花交友】day05—圈子互动
91 0
|
11月前
|
存储 NoSQL API
【探花交友】day04—圈子功能实现(二)
【探花交友】day04—圈子功能实现(二)
109 0
|
11月前
|
API
【探花交友】day04—圈子功能实现(三)
【探花交友】day04—圈子功能实现(三)
63 0
|
11月前
|
存储 SQL 缓存
【探花交友】day04—圈子功能实现(一)
【探花交友】day04—圈子功能实现
88 0
|
11月前
|
NoSQL 程序员 API
【探花交友】day06—即时通信(三)
【探花交友】day06—即时通信(三)
87 0
|
11月前
|
Dubbo NoSQL 应用服务中间件
【探花交友】day06—即时通信(四)
【探花交友】day06—即时通信(四)
138 0
|
11月前
|
JSON 测试技术 API
【探花交友】day06—即时通信(二)
【探花交友】day06—即时通信(二)
85 0
|
11月前
|
消息中间件 NoSQL 前端开发
【探花交友】day06—即时通信(一)
【探花交友】day06—即时通信
142 0