WHCSRL 技术网

mongodb父节点消息回复消息点赞及Redis标识是否重复点赞(springboot)

  1. //引入MongoDB依赖
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. <version>2.0.1.RELEASE</version>
  6. </dependency>
  7. //引入Redis依赖
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-data-redis</artifactId>
  11. <version>2.0.1.RELEASE</version>
  12. </dependency>
SpitController层
  1. @Autowired
  2. private RedisTemplate redisTemplate;
  3. //回复消息
  4. @RequestMapping(method = RequestMethod.POST)
  5. public Result save(@RequestBody Spit spit){
  6. spitService.save(spit);
  7. return new Result(true,StatusCode.OK,"保存成功");
  8. }
  9. //点赞
  10. @RequestMapping(value = "/thumbup/{spitid}",method = RequestMethod.PUT)
  11. public Result Thumbup(@PathVariable String spitid){
  12. //判斷用户是否已经点赞,用户ID暂且写死
  13. String userid="123";
  14. if (redisTemplate.opsForValue().get("thumbup_"+userid)!=null){
  15. return new Result(false,StatusCode.REPERROR,"不能重复点赞");
  16. }
  17. spitService.thumbup(spitid);
  18. redisTemplate.opsForValue().set("thumbup_"+userid,1);
  19. return new Result(true,StatusCode.OK,"点赞成功");
  20. }

service层 

  1. @Autowired
  2. private MongoTemplate mongoTemplate;
  3. public void save(Spit spit){
  4. spit.set_id(idWorker.nextId()+"");
  5. spit.setPublishtime(new Date());//发布日期
  6. spit.setVisits(0);//浏览量
  7. spit.setShare(0);//分享数
  8. spit.setThumbup(0);//点赞数
  9. spit.setComment(0);//回复数
  10. spit.setState("1");//状态
  11. //如果当前添加的吐槽有父节点,那么回复的父节点的回复数+1
  12. if(spit.get_id()!=null && ! "".equals(spit.get_id())){
  13. Query query = new Query();
  14. query.addCriteria(Criteria.where("_id").is(spit.getParentid()));
  15. Update updata = new Update();
  16. updata.inc("comment",1);
  17. mongoTemplate.updateFirst(query,updata,"spit"); //spit mongodb吐槽表名
  18. }
  19. spitDao.save(spit);
  20. }
  21. public void thumbup(String spitid) {
  22. //方式一:效率低,点赞需要经过两次数据库
  23. /* Spit spit = spitDao.findById(spitid).get();
  24. spit.setThumbup((spit.getThumbup() == null ? 0:spit.getThumbup())+1);
  25. spitDao.save(spit);*/
  26. //方式二:
  27. Update update = new Update();
  28. update.inc("thumbup",1);
  29. Query query = new Query();
  30. query.addCriteria(Criteria.where("_id").is(spitid));
  31. mongoTemplate.updateFirst(query,update,"spit");
  32. }

推荐阅读