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

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介: 微服务技术系列教程(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方法
相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
3天前
|
机器学习/深度学习 负载均衡 Java
【SpringBoot系列】微服务远程调用Open Feign深度学习
【4月更文挑战第9天】微服务远程调度open Feign 框架学习
|
9天前
|
Java API 微服务
【Spring Boot系列】通过OpenAPI规范构建微服务服务接口
【4月更文挑战第5天】通过OpenAPI接口构建Spring Boot服务RestAPI接口
|
1月前
|
Kubernetes 开发者 Docker
基于容器技术的微服务架构
基于容器技术的微服务架构
33 0
|
1月前
|
监控 负载均衡 安全
构建高效微服务架构的五大核心技术实践
【2月更文挑战第14天】 在当今软件开发领域,微服务架构已成为构建复杂系统的首选模式。它通过将大型单体应用拆分成一系列小型、自治的服务来提高可维护性和扩展性。本文深入探讨了构建高效微服务架构的五大核心技术实践,包括服务拆分策略、API网关设计、服务发现与注册、熔断机制以及分布式追踪与监控。文章不仅分享了实践中的经验教训,还提供了实施这些技术时的具体建议和最佳实践。
28 1
|
2月前
|
Java Nacos Maven
从零搭建微服务架构:Spring Boot与Nacos完美整合
从零搭建微服务架构:Spring Boot与Nacos完美整合
169 0
|
2月前
|
NoSQL Java MongoDB
springboot整合MongoDB(简单demo实现包含注意点及踩坑)
springboot整合MongoDB(简单demo实现包含注意点及踩坑)
93 0
|
3月前
|
JSON Dubbo Java
微服务框架(二十)Dubbo Spring Boot 生产就绪特性
  此系列文章将会描述Java框架Spring Boot、服务治理框架Dubbo、应用容器引擎Docker,及使用Spring Boot集成Dubbo、Mybatis等开源框架,其中穿插着Spring Boot中日志切面等技术的实现,然后通过gitlab-CI以持续集成为Docker镜像。   本文为Dubbo Spring Boot 生产就绪特性
|
5天前
|
存储 Java 时序数据库
【SpringBoot系列】微服务监测(常用指标及自定义指标)
【4月更文挑战第6天】SpringBoot微服务的监测指标及自定义指标讲解
|
4天前
|
Java 关系型数据库 数据库
【SpringBoot系列】微服务集成Flyway
【4月更文挑战第7天】SpringBoot微服务集成Flyway
【SpringBoot系列】微服务集成Flyway
|
19天前
|
消息中间件 监控 Java
微服务技术发展
微服务技术发展