概述
在Spring Boot中MongoDB不像 MySQL一样自动配置连接池,虽然MonggoDB的驱动程序中自带了连接池,但是需要我们自己去配置。
在官方的文档的内容发现一个连接池的参数,而它是在MongoClientOptions中配置。
从MongoClientOptions查看参数我们发现
我们继续往下看,最后发现Builder是MongoClientOptions类的内部类,在该内部类中发现默认的最大连接数为100,而最小连接数为空
所以我们可以试着去修改这2个参数
在配置文件中进行配置
spring:
data:
mongodb:
custom:
host: localhost
port: 27017
username: book-admin
password: 123456
database: book
# 用户认证的数据库
authentication-database: admin
# 连接池大小
connections-per-host: 10
# 最小连接池大小
min-connections-per-host: 10
创建 MongoProperties
类用于存储配置参数
public class MongoProperties {
private String database;
private String host;
private Integer port;
private String username;
private String password;
private String authenticationDatabase;
private Integer minConnectionsPerHost;
private Integer connectionsPerHost = 100;
// 省略 geter/seter 方法
}
创建 MongoConfig
类配置MongoDbFactory类的Bean对象
@Configuration
public class MongoConfig {
@Resource
private MongoProperties mongoProperties;
@Bean
@ConfigurationProperties(prefix = "spring.data.mongodb.custom")
MongoProperties mongoSettingsProperties() {
return new MongoProperties();
}
@Bean
MongoDbFactory mongoDbFactory() {
// 配置连接池
MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
builder.connectionsPerHost(mongoProperties.getConnectionsPerHost());
builder.minConnectionsPerHost(mongoProperties.getMinConnectionsPerHost());
MongoClientOptions mongoClientOptions = builder.build();
// 配置MongoDB地址
ServerAddress serverAddress = new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort());
// 配置连接认证
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(
mongoProperties.getUsername(),
mongoProperties.getAuthenticationDatabase() != null ? mongoProperties.getAuthenticationDatabase() : mongoProperties.getDatabase(),
mongoProperties.getPassword().toCharArray()
);
// 创建客户端和Factory
MongoClient mongoClient = new MongoClient(serverAddress, mongoCredential, mongoClientOptions);
return new SimpleMongoDbFactory(mongoClient, mongoProperties.getDatabase());
}
}
根据几次测试发现必须要配置最小连接池大小才能使连接池生效,否则只会生成一个连接。
builder.minConnectionsPerHost(mongoProperties.getMinConnectionsPerHost());
完整运行项目后根据日志我们可以看到
网友评论