SpringBoot中使⽤MongoDB的连接池配置
⽬录
引⼊依赖
配置⽂件
配置⽂件映射为JavaBean
覆盖MongoDbFactory
MongoDB测试
创建数据实体
创建Dao接⼝及实现
编写测试代码
在SpringBoot中,我们可以通过引⼊ spring-boot-starter-data-mongodb 依赖来实现spring-data-mongod
b 的⾃动配置。但是,默认情况下,该依赖并没有像使⽤MySQL或者Redis那样为我们提供连接池配置的功能。因此,我们需要⾃⾏重写MongoDbFactory,实现MongoDB客户端连接的参数配置扩展。需要说明的是,MongoDB的客户端本⾝就是⼀个连接池,因此,我们只需要配置客户端即可。
引⼊依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
配置⽂件
为了⽅便对Mongodb进⾏统⼀管理,我们将相关的配置抽取到 mongo-pool.properties 中,前缀为db(前缀可⾃⼰随意配置):
db.address=172.16.250.234:27017,172.16.250.239:27017,172.16.250.240:27017
db.replica-set=rs0
db.database=test
db.username=admin
db.password=admin
# Configure dbDB Pool
db.min-connections-per-host=10
db.max-connections-per-host=100
db.threads-allowed-to-block-for-connection-multiplier=5
db.server-selection-timeout=30000
db.max-wait-time=120000
db.max-connection-idel-time=0
db.max-connection-life-time=0
db.connect-timeout=10000
db.socket-timeout=0
db.socket-keep-alive=false
db.ssl-enabled=false
db.ssl-invalid-host-name-allowed=false
db.always-use-m-beans=false
db.heartbeat-socket-timeout=20000
db.heartbeat-connect-timeout=20000
db.min-heartbeat-frequency=500
db.heartbeat-frequency=10000
db.local-threshold=15
db.authentication-database=auth_dev
配置⽂件映射为JavaBean
为⽅便调⽤,将上述配置包装成⼀个配置实体类,代码如下:
import java.util.List;
import org.t.properties.ConfigurationProperties;
import t.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = "classpath:mongo-pool.properties")
@ConfigurationProperties(prefix = "db")
public class MongoSettingsProperties {
private List<String> address;
private String replicaSet;
private String database;
private String username;
private String password;
private Integer minConnectionsPerHost = 0;
private Integer maxConnectionsPerHost = 100;
private Integer threadsAllowedToBlockForConnectionMultiplier = 5;
private Integer serverSelectionTimeout = 30000;
private Integer maxWaitTime = 120000;
private Integer maxConnectionIdleTime = 0;
private Integer maxConnectionLifeTime = 0;
private Integer connectTimeout = 10000;
private Integer socketTimeout = 0;
private Boolean socketKeepAlive = false;
private Boolean sslEnabled = false;
private Boolean sslInvalidHostNameAllowed = false;
private Boolean alwaysUseMBeans = false;
private Integer heartbeatConnectTimeout = 20000;
private Integer heartbeatSocketTimeout = 20000;
private Integer minHeartbeatFrequency = 500;
private Integer heartbeatFrequency = 10000;
private Integer localThreshold = 15;
private String authenticationDatabase;
// 省略Getters和Setters⽅法
}
覆盖MongoDbFactory
⾃定义创建⼀个MongoDbFactory⽤来替代Springboot为我们⾃动装配的MongoDbFactory,代码如下:import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.db.MongoDbFactory;
import org.db.core.SimpleMongoDbFactory;
db.MongoClient;
db.MongoClientOptions;
db.MongoCredential;
db.ServerAddress;
@Configuration
public class MongoConfig {
private static final Logger logger = Logger(MongoConfig.class);
/
/ 覆盖容器中默认的MongoDbFacotry Bean
@Bean
@Autowired
public MongoDbFactory mongoDbFactory(MongoSettingsProperties properties) {
// 客户端配置(连接数,副本集验证)
MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
builder.MinConnectionsPerHost());
if (ReplicaSet() != null) {
}
builder.threadsAllowedToBlockForConnectionMultiplier(
builder.ServerSelectionTimeout());
builder.MaxWaitTime());
builder.MaxConnectionIdleTime());
builder.MaxConnectionLifeTime());
builder.SocketTimeout());
// builder.SocketKeepAlive());
builder.SslEnabled());
builder.SslInvalidHostNameAllowed());
builder.AlwaysUseMBeans());
builder.HeartbeatFrequency());
builder.MinHeartbeatFrequency());
builder.HeartbeatConnectTimeout());
builder.HeartbeatSocketTimeout());
mongodb和mysql结合builder.LocalThreshold());
MongoClientOptions mongoClientOptions = builder.build();
// MongoDB地址列表
List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
for (String address : Address()) {
String[] hostAndPort = address.split(":");
String host = hostAndPort[0];
Integer port = Integer.parseInt(hostAndPort[1]);
ServerAddress serverAddress = new ServerAddress(host, port);
serverAddresses.add(serverAddress);
}
logger.info("serverAddresses:" + String());
// 连接认证
// MongoCredential mongoCredential = null;
// if (Username() != null) {
//  mongoCredential = ateScramSha1Credential(
//    Username(), AuthenticationDatabase() != null
/
/      ? AuthenticationDatabase() : Database(),
//    Password().toCharArray());
// }
// 创建认证客户端
// MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredential, mongoClientOptions);  // 创建⾮认证客户端
MongoClient mongoClient = new MongoClient(serverAddresses, mongoClientOptions);
// 创建MongoDbFactory
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, Database());  return mongoDbFactory;
}
}
MongoDB测试
创建数据实体
import java.io.Serializable;
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String userName;
private String passWord;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String toString() {
return "id: " + id + ",userName: " + userName + ",passWord: " + passWord; }
}
创建Dao接⼝及实现
public interface UserDao {
void saveUser(UserEntity user);
UserEntity findUserByName(String userName);
}
import org.springframework.beans.factory.annotation.Autowired;
import org.db.core.MongoTemplate;
import org.db.core.query.Criteria;
import org.db.core.query.Query;
import org.springframework.stereotype.Component;
@Component
public class UserDaoImpl implements UserDao {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public void saveUser(UserEntity user) {
mongoTemplate.save(user);
}
@Override
public UserEntity findUserByName(String userName) {
Query query = new Query(Criteria.where("userName").is(userName));
UserEntity user = mongoTemplate.findOne(query, UserEntity.class);
return user;
}
}
编写测试代码
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.st.context.SpringBootTest;
import org.springframework.data.domain.Example;
import st.context.junit4.SpringRunner;
import com.pengjunlee.UserDao;
import com.pengjunlee.UserEntity;
import com.pengjunlee.UserRepository;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MongoTest {
@Autowired
private UserDao userDao;
@Autowired
private UserRepository userRepository;
@Test
public void testSaveUser() {
UserEntity user = new UserEntity();
user.setId(88L);
user.setUserName("XiaoMing");
user.setPassWord("123456");
userDao.saveUser(user);
}
@Test
public void testFindUser01() {
UserEntity user = userDao.findUserByName("XiaoMing");
System.out.println(user);
}
@Test
public void testFindUser02() {
UserEntity queryUser = new UserEntity();
queryUser.setUserName("XiaoMing");
Example<UserEntity> example = Example.of(queryUser);
Optional<UserEntity> optional = userRepository.findOne(example);
System.out.());
}
}
查询结果:
id: 88,userName: XiaoMing,passWord: 123456
到此这篇关于SpringBoot中使⽤MongoDB的连接池配置的⽂章就介绍到这了,更多相关SpringBoot MongoDB连接池配置内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。