5.1 需求分析
某头条的文章评论业务如下:
需要实现以下功能:
1)基本增删改查API
2)根据文章id查询评论
3)评论点赞
数据库:articledb
5.3 技术选型
5.3.1 mongodb-driver(了解)
mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。我们通过一个入门的案例来了解mongodb-driver的基本使用。 5.3.2 SpringDataMongoDB
SpringData家族成员之一,用于操作MongoDB的持久层框架,封装了底层的mongodb-driver。
官网主页: https://projects.spring.io/spring-data-mongodb/ 5.4 文章微服务模块搭建
(1)搭建项目工程article,pom.xml引入依赖:
(2)创建application.yml
(3)创建启动类cn.itcast.article.ArticleApplication
(4)启动项目,看是否能正常启动,控制台没有错误。
5.5 文章评论实体类的编写
创建实体类 创建包cn.itcast.article,包下建包po用于存放实体类,创建实体类
cn.itcast.article.po.Comment

说明:
索引可以大大提升查询效率,一般在查询字段上添加索引,索引的添加可以通过Mongo的命令来添加,也可以在Java的实体类中通过注解添加。
1)单字段索引注解@Indexed
org.springframework.data.mongodb.core.index.Indexed.class
声明该字段需要索引,建索引可以大大的提高查询效率。
Mongo命令参考:
db.comment.createIndex({"userid":1})
2)复合索引注解@CompoundIndex
org.springframework.data.mongodb.core.index.CompoundIndex.class
复合索引的声明,建复合索引可以有效地提高多字段的查询效率。
Mongo命令参考:
db.comment.createIndex({"userid":1,"nickname":-1}) 5.6 文章评论的基本增删改查**
(1)创建数据访问接口 cn.itcast.article包下创建dao包,包下创建接口 cn.itcast.article.dao.CommentRepository
package cn.itcast.article.dao;
import cn.itcast.article.po.Comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
//评论的持久层接口
public interface CommentRepository extends MongoRepository {
}
(2)创建业务逻辑类 cn.itcast.article包下创建service包,包下创建类 cn.itcast.article.service.CommentService
package cn.itcast.article.service;
import cn.itcast.article.dao.CommentRepository;
import cn.itcast.article.po.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
//评论的业务层
@Service
public class CommentService {
//注入dao
@Autowired
private CommentRepository commentRepository;
/**
* 保存一个评论
* @param comment
*/
public void saveComment(Comment comment){
//如果需要自定义主键,可以在这里指定主键;如果不指定主键,MongoDB会自动生成主键
//设置一些默认初始值。。。
//调用dao
commentRepository.save(comment);
}
/**
* 更新评论
* @param comment
*/
public void updateComment(Comment comment){
//调用dao
commentRepository.save(comment);
}
/**
* 根据id删除评论
* @param id
*/
public void deleteCommentById(String id){
//调用dao
commentRepository.deleteById(id);
}
/**
* 查询所有评论
* @return
*/
public List<Comment> findCommentList(){
//调用dao
return commentRepository.findAll();
}
/**
* 根据id查询评论
* @param id
* @return
*/
public Comment findCommentById(String id){
//调用dao
return commentRepository.findById(id).get();
}
}
(3)新建Junit测试类,测试保存和查询所有:
cn.itcast.article.service.CommentServiceTest
package cn.itcast.article.service;
import cn.itcast.article.ArticleApplication;
import cn.itcast.article.po.Comment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.LocalDateTime;
import java.util.List;
//测试评论的业务层
//SpringBoot的Junit集成测试
@RunWith(SpringRunner.class)
//SpringBoot的测试环境初始化,参数:启动类
@SpringBootTest(classes = ArticleApplication.class)
public class CommentServiceTest {
//注入Service
@Autowired
private CommentService commentService;
/**
* 保存一个评论
*/
@Test
public void testSaveComment(){
Comment comment=new Comment();
comment.setArticleid("100000");
comment.setContent("测试添加的数据");
comment.setCreatedatetime(LocalDateTime.now());
comment.setUserid("1003");
comment.setNickname("凯撒大帝");
comment.setState("1");
comment.setLikenum(0);
comment.setReplynum(0);
commentService.saveComment(comment);
}
/**
* 查询所有数据
*/
@Test
public void testFindAll(){
List<Comment> list = commentService.findCommentList();
System.out.println(list);
}
/**
* 测试根据id查询
*/
@Test
public void testFindCommentById(){
Comment comment = commentService.findCommentById("5d6a27b81b8d374798cf0b41");
System.out.println(comment);
}
}
结果:
5.7 根据上级ID查询文章评论的分页列表 (1)CommentRepository新增方法定义
//根据父id,查询子评论的分页列表
Page findByParentid(String parentid, Pageable pageable);<br>(2)CommentService新增方法<br>/**</p> <ul> <li>根据父id查询分页列表</li> <li>@param parentid</li> <li>@param page</li> <li>@param size</li> <li>@return<br><em>/<br>public Page<Comment> findCommentListPageByParentid(String parentid,int page ,int size){<br> return commentRepository.findByParentid(parentid, PageRequest.of(page-1,size));<br>}<br>(3)junit测试用例:<br>cn.itcast.article.service.CommentServiceTest<br>/*</em><ul> <li>测试根据父id查询子评论的分页列表<br><em>/<br>@Test<br>public void testFindCommentListPageByParentid(){<br>Page<Comment> pageResponse = commentService.findCommentListPageByParentid("3", 1, 2);<br>System.out.println("----总记录数:"+pageResponse.getTotalElements());<br>System.out.println("----当前页数据:"+pageResponse.getContent());<br>}<br>(4)测试<br>使用compass快速插入一条测试数据,数据的内容是对3号评论内容进行评论。<br><img src="https://ucc.alicdn.com/pic/developer-ecology/ifuxgytxbekgq_2c6b717bbab649dbbd10aae7bcf52ca1.png" alt="image.png"><br>执行测试结果:<br>----总记录数:1<br>----当前页数据:[Comment{id='33', content='你年轻,火力大', publishtime=null, userid='1003', nickname='凯撒大帝', createdatetime=null, likenum=null, replynum=null, state='null', parentid='3', articleid='100001'}]<br><strong>5.8 MongoTemplate实现评论点赞</strong><br>我们看一下以下点赞的临时示例代码: CommentService 新增updateThumbup方法<br>/*</em></li> </ul> </li> <li>点赞-效率低</li> <li>@param id<br>*/<br>public void updateCommentThumbupToIncrementingOld(String id){<br> Comment comment = CommentRepository.findById(id).get();<br> comment.setLikenum(comment.getLikenum()+1);<br> CommentRepository.save(comment);<br>}<br>以上方法虽然实现起来比较简单,但是执行效率并不高,因为我只需要将点赞数加1就可以了,没必要查询出所有字段修改后再更新所有字段。我们可以使用MongoTemplate类来实现对某列的操作。<br>(1)修改CommentService<br>//注入MongoTemplate<br>@Autowired<br>private MongoTemplate mongoTemplate;</li> </ul> <p>/**</p> <ul> <li>点赞数+1</li> <li>@param id<br><em>/<br>public void updateCommentLikenum(String id){<br> //查询对象<br> Query query=Query.query(Criteria.where("_id").is(id));<br> //更新对象<br> Update update=new Update();<br> //局部更新,相当于$set<br> // update.set(key,value)<br> //递增$inc<br> // update.inc("likenum",1);<br> update.inc("likenum");<br> //参数1:查询对象<br> //参数2:更新对象<br> //参数3:集合的名字或实体类的类型Comment.class<br> mongoTemplate.updateFirst(query,update,"comment");<br>}<br>(2)测试用例:<br>cn.itcast.article.service.CommentServiceTest<br>/*</em></li> <li>点赞数+1<br>*/<br>@Test<br>public void testUpdateCommentLikenum(){<br> //对3号文档的点赞数+1<br> commentService.updateCommentLikenum("3");<br>}<br>执行测试用例后,发现点赞数+1了:<br><img src="https://ucc.alicdn.com/pic/developer-ecology/ifuxgytxbekgq_872bf52a411e4eea8b98e7aa598f87ad.png" alt="image.png"></li> </ul>