SpringBoot中使用MongoDB的连接池配置

目录
  • 引入依赖
  • 配置文件
  • 配置文件映射为JavaBean
  • 覆盖MongoDbFactory
  • MongoDB测试
    • 创建数据实体
    • 创建Dao接口及实现
    • 编写测试代码

在SpringBoot中,我们可以通过引入 spring-boot-starter-data-mongodb 依赖来实现spring-data-mongodb 的自动配置。但是,默认情况下,该依赖并没有像使用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 中,前缀为spring.data.mongodb(前缀可自己随意配置):

spring.data.mongodb.address=172.16.250.234:27017,172.16.250.239:27017,172.16.250.240:27017
spring.data.mongodb.replica-set=rs0
spring.data.mongodb.database=test
spring.data.mongodb.username=admin
spring.data.mongodb.password=admin

# Configure spring.data.mongodbDB Pool
spring.data.mongodb.min-connections-per-host=10
spring.data.mongodb.max-connections-per-host=100
spring.data.mongodb.threads-allowed-to-block-for-connection-multiplier=5
spring.data.mongodb.server-selection-timeout=30000
spring.data.mongodb.max-wait-time=120000
spring.data.mongodb.max-connection-idel-time=0
spring.data.mongodb.max-connection-life-time=0
spring.data.mongodb.connect-timeout=10000
spring.data.mongodb.socket-timeout=0
spring.data.mongodb.socket-keep-alive=false
spring.data.mongodb.ssl-enabled=false
spring.data.mongodb.ssl-invalid-host-name-allowed=false
spring.data.mongodb.always-use-m-beans=false
spring.data.mongodb.heartbeat-socket-timeout=20000
spring.data.mongodb.heartbeat-connect-timeout=20000
spring.data.mongodb.min-heartbeat-frequency=500
spring.data.mongodb.heartbeat-frequency=10000
spring.data.mongodb.local-threshold=15
spring.data.mongodb.authentication-database=auth_dev

配置文件映射为JavaBean

为方便调用,将上述配置包装成一个配置实体类,代码如下:

import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = "classpath:mongo-pool.properties")
@ConfigurationProperties(prefix = "spring.data.mongodb")
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 org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

@Configuration
public class MongoConfig {

 private static final Logger logger = LoggerFactory.getLogger(MongoConfig.class);

 // 覆盖容器中默认的MongoDbFacotry Bean
 @Bean
 @Autowired
 public MongoDbFactory mongoDbFactory(MongoSettingsProperties properties) {

  // 客户端配置(连接数,副本集群验证)
  MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
  builder.connectionsPerHost(properties.getMaxConnectionsPerHost());
  builder.minConnectionsPerHost(properties.getMinConnectionsPerHost());
  if (properties.getReplicaSet() != null) {
   builder.requiredReplicaSetName(properties.getReplicaSet());
  }
  builder.threadsAllowedToBlockForConnectionMultiplier(
    properties.getThreadsAllowedToBlockForConnectionMultiplier());
  builder.serverSelectionTimeout(properties.getServerSelectionTimeout());
  builder.maxWaitTime(properties.getMaxWaitTime());
  builder.maxConnectionIdleTime(properties.getMaxConnectionIdleTime());
  builder.maxConnectionLifeTime(properties.getMaxConnectionLifeTime());
  builder.connectTimeout(properties.getConnectTimeout());
  builder.socketTimeout(properties.getSocketTimeout());
  // builder.socketKeepAlive(properties.getSocketKeepAlive());
  builder.sslEnabled(properties.getSslEnabled());
  builder.sslInvalidHostNameAllowed(properties.getSslInvalidHostNameAllowed());
  builder.alwaysUseMBeans(properties.getAlwaysUseMBeans());
  builder.heartbeatFrequency(properties.getHeartbeatFrequency());
  builder.minHeartbeatFrequency(properties.getMinHeartbeatFrequency());
  builder.heartbeatConnectTimeout(properties.getHeartbeatConnectTimeout());
  builder.heartbeatSocketTimeout(properties.getHeartbeatSocketTimeout());
  builder.localThreshold(properties.getLocalThreshold());
  MongoClientOptions mongoClientOptions = builder.build();

  // MongoDB地址列表
  List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
  for (String address : properties.getAddress()) {
   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:" + serverAddresses.toString());

  // 连接认证
  // MongoCredential mongoCredential = null;
  // if (properties.getUsername() != null) {
  //  mongoCredential = MongoCredential.createScramSha1Credential(
  //    properties.getUsername(), properties.getAuthenticationDatabase() != null
  //      ? properties.getAuthenticationDatabase() : properties.getDatabase(),
  //    properties.getPassword().toCharArray());
  // }

  // 创建认证客户端
  // MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredential, mongoClientOptions);

  // 创建非认证客户端
  MongoClient mongoClient = new MongoClient(serverAddresses, mongoClientOptions);

  // 创建MongoDbFactory
  MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, properties.getDatabase());
  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.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.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.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Example;
import org.springframework.test.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.println(optional.get());
 }
}

查询结果:

id: 88,userName: XiaoMing,passWord: 123456

到此这篇关于SpringBoot中使用MongoDB的连接池配置的文章就介绍到这了,更多相关SpringBoot MongoDB连接池配置内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • springboot配置mongodb连接池的方法步骤

    application.yml 配置 mongodb: address: localhost:27017 database: soms username: admin password: 123456 # 连接池配置 clientName: soms-task # 客户端的标识,用于定位请求来源等 connectionTimeoutMs: 10000 # TCP连接超时,毫秒 readTimeoutMs: 15000 # TCP读取超时,毫秒 poolMaxWaitTimeMs: 3000 #当

  • SpringBoot中使用MongoDB的连接池配置

    目录 引入依赖 配置文件 配置文件映射为JavaBean 覆盖MongoDbFactory MongoDB测试 创建数据实体 创建Dao接口及实现 编写测试代码 在SpringBoot中,我们可以通过引入 spring-boot-starter-data-mongodb 依赖来实现spring-data-mongodb 的自动配置.但是,默认情况下,该依赖并没有像使用MySQL或者Redis那样为我们提供连接池配置的功能.因此,我们需要自行重写 MongoDbFactory,实现MongoDB客

  • Spring Boot中使用MongoDB的连接池配置的方法

    因为今天开发遇到了性能问题,可能与MongoDB的连接有关,所以稍稍深入看了一下,正好搜到原来有人写过这篇相关的内容,所以转载过来.回头有时间可以写个扩展到SpringForAll里,主体思路还是一样的.感谢这位美女程序媛的文章! 说明 Spring Boot中通过依赖 spring-boot-starter-data-mongodb ,来实现 spring-data-mongodb 的自动配置. 但是默认情况下,Spring Boot 中,并没有像使用MySQL或者Redis一样,提供了连接池

  • springboot集成druid连接池配置的方法

    在开发项目中如果数据库选型为mysql,很大概率下连接池会使用druid 这里介绍springboot集成durid springboot : 2.1.9 druid : 1.1.10 案例地址 github地址 springboot集成druid配置 需要引入的pom <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactI

  • JSP Spring中Druid连接池配置详解

    JSP Spring中Druid连接池配置 jdbc.properties url=jdbc:postgresql://***.***.***.***:****/**** username=*** password=*** applicationContext.xml中配置bean <!-- 阿里 druid 数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSou

  • SpringBoot集成FTP与SFTP连接池流程

    目录 简介 FTP 简介 FTPS 简介 SFTP 简介 FTP SFTP FTPS区别 实战代码 公共配置文件 pom.xml 配置 application.yml 配置 FTP 连接池 FTP 配置文件 ftp.properties FTP 配置实体类 FTP 连接工厂 FTP 连接池服务接口 FTP 工具类 SFTP 连接池 SFTP 配置文件 sftp.properties SFTP 配置实体类 SFTP 连接工厂 SFTP 连接池服务接口 SFTP 工具类 SFTP 工具类 测试代码

  • tomcat 几种连接池配置代码(包括tomcat5.0,tomcat5.5x,tomcat6.0)

    Tomcat6.0连接池配置 1.配置tomcat下的conf下的context.xml文件,在之间添加连接池配置: 复制代码 代码如下: <Resource name="jdbc/oracle" auth="Container" type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver" url=" jdbc:or

  • JDBC数据源连接池配置及应用

    使用JDBC建立数据库连接的两种方式: 1.在代码中使用DriverManager获得数据库连接.这种方式效率低,并且其性能.可靠性和稳定性随着用户访问量得增加逐渐下降. 2.使用配置数据源的方式连接数据库,该方式其实质就是在上述方法的基础上增加了数据库连接池,这种方式效率高. 数据源连接池的方式连接数据库与在代码中使用DriverManager获得数据库连接存在如下差别: 1)数据源连接池的方式连接数据库是在程序中,通过向一个JNDI(Java Naming and  Directory In

  • Redis连接池配置及初始化实现

    加入db选择后的redis连接池配置代码 public class RedisPoolConfigure { //Redis服务器IP private String ADDR ; //Redis的端口号 private int PORT ; //可用连接实例的最大数目 private int MAX_ACTIVE ; //pool中的idle jedis实例数 private int MAX_IDLE ; //等待可用连接的最大时间,单位毫秒 private int MAX_WAIT ; //超

  • 详解在SpringBoot中使用MongoDb做单元测试的代码

    先评价: 功能倒是不错,但是总觉得耽误时间 先引入pom依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> 代码1 public class MongoUser implemen

  • SpringBoot中shiro过滤器的重写与配置详解

    目录 问题 解决方案 实现代码 1.重写shiro 登录 过滤器 2.重写role权限 过滤器 3.配置过滤器 问题 遇到问题:在前后端分离跨域访问的项目中shiro进行权限拦截失效 (即使有正确权限的访问也会被拦截) 时造成302重定向错误等问题报错:Response for preflight is invalid (redirect) 1.302原因:使用ajax访问后端项目时无法识别重定向操作 2.shiro拦截失效原因:跨域访问时有一种带预检访问的跨域,即访问时先发出一条methods

随机推荐