1 场景
springBoot集成mongoDb
2 版本说明
springboot:2.2.9.RELEASE
mongoDb:4.0
(集群模式)
3 步骤
3.1 maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
3.2 配置文件
application.yml
文件中进行如下配置:
mongodb:
## 连接配置
dbconfig:
# 库名
database: my_db
# 地址(集群方式)
addresses:
- 127.0.0.1:50001
- 127.0.0.1:50002
# 用户名
username: myUser
# 密码
password: myPwd
## 数据库参数配置
option:
always-use-m-beans: false
connect-timeout: 10000
heartbeat-connect-timeout: 20000
heartbeat-socket-timeout: 20000
local-threshold: 15
max-connection-idle-time: 0
max-connection-life-time: 0
max-connections-per-host: 100
min-connections-per-host: 10
max-wait-time: 120000
heartbeat-frequency: 10000
min-heartbeat-frequency: 500
server-selection-timeout: 30000
socket-keep-alive: false
socket-timeout: 0
ssl-enabled: false
ssl-invalid-host-name-allowed: false
threads-allowed-to-block-for-connection-multiplier: 5
3.3 spring配置
配置文件映射:
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 数据库参数配置
**/
@Data
@Component
@ConfigurationProperties(prefix = "mongodb.option")
public class MongoOptionProperties {
private Boolean alwaysUseMBeans = false;
private Integer connectTimeout = 10000;
private Integer heartbeatConnectTimeout = 20000;
private Integer heartbeatSocketTimeout = 20000;
private Integer localThreshold = 15;
private Integer maxConnectionIdleTime = 0;
private Integer maxConnectionLifeTime = 0;
private Integer maxConnectionsPerHost = 100;
private Integer minConnectionsPerHost = 0;
private Integer maxWaitTime = 120000;
private Integer heartbeatFrequency = 10000;
private Integer minHeartbeatFrequency = 500;
private Integer serverSelectionTimeout = 30000;
private Boolean socketKeepAlive = false;
private Integer socketTimeout = 0;
private Boolean sslEnabled = false;
private Boolean sslInvalidHostNameAllowed = false;
private Integer threadsAllowedToBlockForConnectionMultiplier = 5;
}
mongo配置:
import com.mongodb.*;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import java.util.ArrayList;
import java.util.List;
/**
* mongo配置
**/
@Setter
@Configuration
@ConfigurationProperties(prefix = "mongodb.dbconfig")
public class MongoConfiguration {
/**
* 数据库
*/
private String database;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 连接地址(IP:端口)
*/
private ArrayList<String> addresses;
/**
* 连接配置
*/
@Autowired
private MongoOptionProperties mongoOptionProperties;
/**
* mongo工厂
* @return org.springframework.data.mongodb.MongoDbFactory
*/
@Bean
public MongoDbFactory mongoDbFactory(){
//==========客户端配置==========
MongoClientOptions.Builder builder=new MongoClientOptions.Builder();
builder.connectionsPerHost(mongoOptionProperties.getMaxConnectionsPerHost());
builder.minConnectionsPerHost(mongoOptionProperties.getMinConnectionsPerHost());
builder.threadsAllowedToBlockForConnectionMultiplier(mongoOptionProperties.getThreadsAllowedToBlockForConnectionMultiplier());
builder.serverSelectionTimeout(mongoOptionProperties.getServerSelectionTimeout());
builder.maxWaitTime(mongoOptionProperties.getMaxWaitTime());
builder.maxConnectionIdleTime(mongoOptionProperties.getMaxConnectionIdleTime());
builder.maxConnectionLifeTime(mongoOptionProperties.getMaxConnectionLifeTime());
builder.connectTimeout(mongoOptionProperties.getConnectTimeout());
builder.socketTimeout(mongoOptionProperties.getSocketTimeout());
builder.socketKeepAlive(mongoOptionProperties.getSocketKeepAlive());
builder.sslEnabled(mongoOptionProperties.getSslEnabled());
builder.sslInvalidHostNameAllowed(mongoOptionProperties.getSslInvalidHostNameAllowed());
builder.alwaysUseMBeans(mongoOptionProperties.getAlwaysUseMBeans());
builder.heartbeatFrequency(mongoOptionProperties.getHeartbeatFrequency());
builder.minHeartbeatFrequency(mongoOptionProperties.getMinHeartbeatFrequency());
builder.heartbeatConnectTimeout(mongoOptionProperties.getHeartbeatConnectTimeout());
builder.heartbeatSocketTimeout(mongoOptionProperties.getHeartbeatSocketTimeout());
builder.localThreshold(mongoOptionProperties.getLocalThreshold());
MongoClientOptions mongoClientOptions=builder.build();
//==========地址配置==========
List<ServerAddress> serverAddressArrayList = new ArrayList<>();
for (String address : addresses) {
String[] hostAndPort = address.split(":");
String host = hostAndPort[0];
Integer port = Integer.parseInt(hostAndPort[1]);
ServerAddress serverAddress = new ServerAddress(host, port);
serverAddressArrayList.add(serverAddress);
}
//连接认证
MongoCredential mongoCredential=MongoCredential.createScramSha1Credential(username, database, password.toCharArray());
//创建认证客户端
MongoClient mongoClient = new MongoClient(serverAddressArrayList, mongoCredential, mongoClientOptions);
// 创建MongoDbFactory
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, database);
return mongoDbFactory;
}
/**
* 默认mongo句柄(写关注为SAFE)
* @param mongoDbFactory
* @return org.springframework.data.mongodb.core.MongoTemplate
*/
@Bean
public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory) {
MongoTemplate mongoTemplate=new MongoTemplate(mongoDbFactory);
mongoTemplate.setWriteConcern(WriteConcern.SAFE);
return mongoTemplate;
}
}
3.4 使用
项目中可以直接使用配置好的MongoTemplate
句柄,来操作mongo:
@Autowired
private MongoTemplate mongoTemplate;
@Test
public void myTest(){
System.out.println(mongoTemplate.getCollectionNames());
}