💡版本依赖
jdk 17
SpringBoot 3.1.0
Mongo 6.0.8
mybatis-plus 2.0.2
💡环境准备
🌵MongoDB安装
安装教程请查看:一文搞定(linux+windows+docker)安装MongoDB
🌵导入依赖
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.1.0</version>
</parent><groupId>com.example</groupId>
<artifactId>springboot-mongo-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-mongo-demo</name>
<description>springboot-mongo-demo</description>
<properties><java.version>17</java.version><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- mongo --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.32</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>2.0.2</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.15.2</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency>
</dependencies>
🌵application.yml配置
server:port: 8080 # 设置访问端口spring:data:mongodb:maxSize: 100 # 允许的最大连接数。这些连接在空闲时将保留在池中。一旦池耗尽,任何需要连接的操作都将阻塞等待可用连接 默认: 100minSize: 10 # 最小连接数。这些连接在空闲时将保留在池中,并且池将确保它至少包含这个最小数量 默认: 0maxConnectionLifeTime: 0 # 池连接可以存活的最长时间。零值表示寿命没有限制。超过其生命周期的池连接将被关闭并在必要时由新连接替换maxConnectionIdleTime: 5 # 池连接的最大空闲时间。零值表示对空闲时间没有限制。超过其空闲时间的池连接将被关闭并在必要时由新连接替换maxWaitTime: 60000 # 默认最大连接时间120s;one:uri: mongodb://47.98.123.147:27017/${spring.data.mongodb.one.database}database: mongo_db# 上方为明确指定某个数据的用户进行连接# 也可以使用admin 数据库中的用户进行连接 统一到admin 数据库进行认证# admin 用户认证 url 写法: mongodb://账户:密码%40@ip:端口/数据库名?authSource=admin&authMechanism=SCRAM-SHA-1two:uri: mongodb://47.98.123.147:27017/${spring.data.mongodb.two.database}database: mongo_db# 上方为明确指定某个数据的用户进行连接# 也可以使用admin 数据库中的用户进行连接 统一到admin 数据库进行认证# admin 用户认证 url 写法: mongodb://账户:密码%40@ip:端口/数据库名?authSource=admin&authMechanism=SCRAM-SHA-1
参数说明:
maxSize: 100 # 允许的最大连接数。这些连接在空闲时将保留在池中。一旦池耗尽,任何需要连接的操作都将阻塞等待可用连接 默认: 100
minSize: 10 # 最小连接数。这些连接在空闲时将保留在池中,并且池将确保它至少包含这个最小数量 默认: 0
maxConnectionLifeTime: 0 # 池连接可以存活的最长时间。零值表示寿命没有限制。超过其生命周期的池连接将被关闭并在必要时由新连接替换
maxConnectionIdleTime: 5 # 池连接的最大空闲时间。零值表示对空闲时间没有限制。超过其空闲时间的池连接将被关闭并在必要时由新连接替换
maxWaitTime: 60000 # 默认最大连接时间120s;
💡使用实例
🌵MongoConfiguration
/*** @author: coderJim* @description: mongodb连接池配置*/
@Configuration
public class MongoConfiguration {@Value("${spring.data.mongodb.maxSize}")private int maxSize;@Value("${spring.data.mongodb.minSize}")private int minSize;@Value("${spring.data.mongodb.maxConnectionLifeTime}")private int maxConnectionLifeTime;@Value("${spring.data.mongodb.maxConnectionIdleTime}")private int maxConnectionIdleTime;@Value("${spring.data.mongodb.maxWaitTime}")private int maxWaitTime;@Bean@Primary@ConfigurationProperties(prefix = "spring.data.mongodb.one")public MongoProperties masterMongoProperties() {return new MongoProperties();}@Bean@ConfigurationProperties(prefix = "spring.data.mongodb.two")public MongoProperties twoMongoProperties() {return new MongoProperties();}/*** 连接池配置1** @return*/@Bean@Primarypublic MongoDatabaseFactory mongoDatabaseFactory(@Qualifier("masterMongoProperties") MongoProperties properties) {return getSimpleMongoClientDatabaseFactory(properties);}/*** 连接池配置2** @return*/@Beanpublic MongoDatabaseFactory twoMongoDatabaseFactory(@Qualifier("twoMongoProperties") MongoProperties properties) {return getSimpleMongoClientDatabaseFactory(properties);}private SimpleMongoClientDatabaseFactory getSimpleMongoClientDatabaseFactory(MongoProperties properties){MongoClientSettings.Builder builder = MongoClientSettings.builder();builder.applyConnectionString(new ConnectionString(properties.getUri()));builder.applyToConnectionPoolSettings(b -> {b.maxSize(maxSize);b.minSize(minSize);b.maxConnectionLifeTime(maxConnectionLifeTime, TimeUnit.SECONDS);b.maxConnectionIdleTime(maxConnectionIdleTime, TimeUnit.MINUTES);b.maxWaitTime(maxWaitTime, TimeUnit.MILLISECONDS);});MongoClient mongoClient = MongoClients.create(builder.build(), SpringDataMongoDB.driverInformation());return new SimpleMongoClientDatabaseFactory(mongoClient, properties.getDatabase());}@Bean@Primarypublic MongoTemplate mongoTemplate(@Qualifier("mongoDatabaseFactory") MongoDatabaseFactory mongoDatabaseFactory) {return getMongoTemplate(mongoDatabaseFactory);}@Beanpublic MongoTemplate twoMongoTemplate(@Qualifier("twoMongoDatabaseFactory") MongoDatabaseFactory mongoDatabaseFactory) {return getMongoTemplate(mongoDatabaseFactory);}private MongoTemplate getMongoTemplate(MongoDatabaseFactory mongoDatabaseFactory){MongoTemplate mongoTemplate = new MongoTemplate(mongoDatabaseFactory);//去除保存实体时,spring data mongodb 自动添加的_class字段MappingMongoConverter mongoMapping = (MappingMongoConverter) mongoTemplate.getConverter();mongoMapping.setTypeMapper(new DefaultMongoTypeMapper(null));mongoMapping.afterPropertiesSet();return mongoTemplate;}
}
🌵User
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {private static final long serialVersionUID = -4328989516223829865L;/*** 用户ID*/private String id;/*** 用户账号*/private String userName;/*** 密码*/private String password;}
🌵MongoController
/*** mongo pool 实列* @author coderJim* @date 2023-05-15 00:03*/
@RestController
@RequestMapping("/mongopool")
public class MongoController {@Autowiredprivate MongoTemplate mongoTemplate;@Qualifier("twoMongoTemplate")@Autowiredprivate MongoTemplate twoMongoTemplate;/*** 新增*/@ResponseBody@GetMapping("/add")public void add(){User user = User.builder().id(UUID.randomUUID().toString()).userName("aa").password("111111").build();mongoTemplate.insert(user);User user2 = User.builder().id(UUID.randomUUID().toString()).userName("bb").password("2222").build();twoMongoTemplate.insert(user2);}
}