springboot集成mongodb(1)

102 阅读1分钟

背景

重拾mongodb之第一篇。

多年前,我曾经在项目中使用过mongodb,但是记忆只停留在有使用过。最近项目中要用到,并且是独立开发的项目,所以从零开始重拾,并在过程中做个笔记,仅此。

1、pom.xml引入jar包

<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>2.7.9</version>
   <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

另外,如果需要在项目中,配置MongoDB的最大连接时长、服务器选择超时时间,最大空闲时间等,可以再引入下面的增强管理jar包:

<dependency>
    <groupId>com.spring4all</groupId>
    <artifactId>mongodb-plus-spring-boot-starter</artifactId>
    <version>1.0.0.RELEASE</version>
</dependency>

并在启动类加上下面的注解:

@EnableMongoPlus

2、application.yaml配置

spring:
  data:
    mongodb:
      uri: xxx
      auto-index-creation: true # 是否自动创建索引
      option: # 可选配置
        server-selection-timeout: 30000 # 指定服务器选择超时的时间,单位为毫秒。当应用程序尝试连接到 MongoDB 服务器时,如果在指定的超时时间内无法选择到可用的服务器,将抛出异常。
        max-connection-idle-time: 30000 # 指定连接的最大空闲时间,单位为毫秒。如果连接在指定的时间内没有被使用,将被认为是空闲连接,并可能被关闭或重新使用。

3、启动类配置

在启动类加注解,@EnableMongoPlus是一个自定义注解,用于启用扩展功能的 MongoDB 配置。它可能包含一些自定义配置或启用一些自定义的功能,以满足特定的业务需求。具体的功能和配置选项会根据项目的实际情况而有所不同。 @ServletComponentScan这个注解用于扫描指定包(eg;com.sum.mongo)下的 Servlet 组件。

@EnableMongoPlus
@ServletComponentScan(basePackages = {"com.sum.mongo", "com.sum"})