微服务技术系列教程(46)-SpringBoot整合MongoDB(文章评论案例)

简介: 微服务技术系列教程(46)-SpringBoot整合MongoDB(文章评论案例)

01 引言

本文的代码已上传至Github,有兴趣的同学可以Clone下来看看https://github.com/ylw-github/SpringBoot-Mongo-Demo.git

讲解本文前,先熟悉MongoDB中常用的几种数据类型:

数据类型 描述
Object ID 文档ID
String 字符串,最常用,必须是有效的UTF-8
Boolean 存储一个布尔值,true或false
Integer 整数可以是32位或64位,这取决于服务器
Double 存储浮点值
Arrays 数组或列表,多个值存储到一个键
Object 用于嵌入式的文档,即一个值为一个文档
Null 存储Null值
Timestamp 时间戳
Date 存储当前日期或时间的UNIX时间格式

本文主要讲解在SpringBoot下整合MongoDB,实现文章评论的“增”、“删”、“改”、“查”功能,其中文章评论MongoDB的表结构设计如下:

专栏文章评论 comment
字段名称 字段含义 字段类型 备注
_id ID ObjectId或String Mongo的主键的字段
articleid 文章ID String
content 评论内容 String
userid 评论人ID String
nickname 评论人昵称 String
createdatetime 评论的日期时间 Date
likenum 点赞数 Int32
replynum 回复数 Int32
state 状态 String 0:不可见;1:可见;
parentid 上级ID String 如果为0表示文章的顶级评论

本文目录结构如下:

l____ 01 引言

l____ 02 环境搭建

l____ 03 配置

l____ 04 编码实现

l____ 05 单元测试

02 环境搭建

① 首先在Linux下搭建MongoDB服务,可参考之前写过的一篇文章《Linux下安装MongoDB》

② 新建一个SpringBoot-Mongo-Demo的maven项目:

03 配置

① 添加maven依赖,如下:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
</dependencies>

② 配置application.yml,配置内容如下:

spring:
  #数据源配置
  data:
    mongodb:
      # 主机地址
      host: 192.168.162.137
      # 数据库
      database: articledb
      # 默认端口是27017
      port: 27017
      #也可以使用uri连接
      #uri: mongodb://bobo:123456@180.76.159.126:27017,180.76.159.126:27018,180.76.159.126:27019/articledb?connect=replicaSet&slaveOk=true&replicaSet=myrs

③ 配置启动类:

@SpringBootApplication
public class ArticleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ArticleApplication.class, args);
    }
}

04 编码实现

① 定义实体类Comment

/**
 * 文章评论实体类
 * 
 * ① @Document 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
 * 
 * 
 * 
 * description: 
 *             - Document 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
 *             - 格式:@Document(collection="mongodb 对应 collection 名")
 * 
 * create by: YangLinWei
 * create time: 2020/7/15 3:28 下午
 */
//若未加 @Document ,该 bean save 到 mongo 的 comment collection
//若添加 @Document ,则 save 到 comment collection
@Document(collection="comment")//可以省略,如果省略,则默认使用类名小写映射集合
//复合索引
@CompoundIndex( def = "{'userid': 1, 'nickname': -1}")
public class Comment implements Serializable {
    //主键标识,该属性的值会自动对应mongodb的主键字段"_id",如果该属性名就叫“id”,则该注解可以省略,否则必须写
//    @Id
    private String id;//主键
    //该属性对应mongodb的字段的名字,如果一致,则无需该注解
    @Field("content")
    private String content;//吐槽内容
    private Date publishtime;//发布日期
    //添加了一个单字段的索引
    @Indexed
    private String userid;//发布人ID
    private String nickname;//昵称
    private LocalDateTime createdatetime;//评论的日期时间
    private Integer likenum;//点赞数
    private Integer replynum;//回复数
    private String state;//状态
    private String parentid;//上级ID
    private String articleid;
    //getter and setter.....
}

② 定义CommentRepository数据库:

public interface CommentRepository extends MongoRepository<Comment, String> {
    Page<Comment> findByParentid(String parentid, Pageable pageable);
}

③定义Service类:

@Service
public class CommentService {
    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存一个评论
     * @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();
    }
    public Page<Comment> findCommentListByParentid(String parentid, int page, int size) {
        return commentRepository.findByParentid(parentid,PageRequest.of(page-1,size));
    }
    public void updateCommentLikenum(String id){
        //  查询条件
        Query query = Query.query(Criteria.where("_id").is(id));
        //  更新条件
        Update update = new Update();
        update.inc("likenum");
        mongoTemplate.updateFirst(query,update,Comment.class);
    }
}

05 单元测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ArticleApplication.class)
public class CommentServiceTest {
    @Autowired
    private CommentService commentService;
    @Test
    public void testFindCommentList() {
        List<Comment> commentList = commentService.findCommentList();
        System.out.println(commentList);
    }
    @Test
    public void testFindCommentById() {
        Comment commentById = commentService.findCommentById("5f0eb6d74cc07a82bf818c79");
        System.out.println(commentById);
    }
    @Test
    public void testSaveComment(){
        Comment comment=new Comment();
        comment.setArticleid("100000");
        comment.setContent("测试添加的数据");
        comment.setCreatedatetime(LocalDateTime.now());
        comment.setUserid("1001");
        comment.setNickname("ylw");
        comment.setState("1");
        comment.setLikenum(0);
        comment.setReplynum(0);
        commentService.saveComment(comment);
    }
    @Test
    public void testFindCommentListByParentid() {
        Page<Comment> page = commentService.findCommentListByParentid("3", 1, 2);
        System.out.println(page.getTotalElements());
        System.out.println(page.getContent());
    }
    @Test
    public void testUpdateCommentLikenum() {
        commentService.updateCommentLikenum("5f0eb6d74cc07a82bf818c79");
    }
}

测试:

  • 测试插入,运行testSaveComment方法,在数据库中可以看到有一条数据
  • 测试查询,运行testFindCommentById方法,可以看到结果能查询出来来
  • 测试修改,修改点赞数量,运行testUpdateCommentLikenum方法
目录
相关文章
|
8月前
|
人工智能 安全 Nacos
Nacos 3.0:微服务与AI融合的技术新纪元
Nacos 3.0:微服务与AI融合的技术新纪元
387 83
|
6月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
1122 5
|
6月前
|
监控 安全 Java
Spring Cloud 微服务治理技术详解与实践指南
本文档全面介绍 Spring Cloud 微服务治理框架的核心组件、架构设计和实践应用。作为 Spring 生态系统中构建分布式系统的标准工具箱,Spring Cloud 提供了一套完整的微服务解决方案,涵盖服务发现、配置管理、负载均衡、熔断器等关键功能。本文将深入探讨其核心组件的工作原理、集成方式以及在实际项目中的最佳实践,帮助开发者构建高可用、可扩展的分布式系统。
392 1
|
6月前
|
Kubernetes Java 微服务
Spring Cloud 微服务架构技术解析与实践指南
本文档全面介绍 Spring Cloud 微服务架构的核心组件、设计理念和实现方案。作为构建分布式系统的综合工具箱,Spring Cloud 为微服务架构提供了服务发现、配置管理、负载均衡、熔断器等关键功能的标准化实现。本文将深入探讨其核心组件的工作原理、集成方式以及在实际项目中的最佳实践,帮助开发者构建高可用、可扩展的分布式系统。
593 0
|
8月前
|
缓存 负载均衡 NoSQL
基于微服务架构的唯品会商品详情接口技术解析
本文介绍了唯品会电商平台商品详情接口的微服务化实现方案,涵盖架构设计、代码示例与性能优化策略。采用FastAPI构建服务,结合Redis缓存、异步处理、Nginx负载均衡等技术,实现高并发、低延迟的接口性能。
|
8月前
|
缓存 Cloud Native Java
Java 面试微服务架构与云原生技术实操内容及核心考点梳理 Java 面试
本内容涵盖Java面试核心技术实操,包括微服务架构(Spring Cloud Alibaba)、响应式编程(WebFlux)、容器化(Docker+K8s)、函数式编程、多级缓存、分库分表、链路追踪(Skywalking)等大厂高频考点,助你系统提升面试能力。
850 0
|
5月前
|
JavaScript Java 关系型数据库
基于springboot的项目管理系统
本文探讨项目管理系统在现代企业中的应用与实现,分析其研究背景、意义及现状,阐述基于SSM、Java、MySQL和Vue等技术构建系统的关键方法,展现其在提升管理效率、协同水平与风险管控方面的价值。
|
5月前
|
搜索推荐 JavaScript Java
基于springboot的儿童家长教育能力提升学习系统
本系统聚焦儿童家长教育能力提升,针对家庭教育中理念混乱、时间不足、个性化服务缺失等问题,构建科学、系统、个性化的在线学习平台。融合Spring Boot、Vue等先进技术,整合优质教育资源,提供高效便捷的学习路径,助力家长掌握科学育儿方法,促进儿童全面健康发展,推动家庭和谐与社会进步。