欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot中使用MongoDB的连接池配置

程序员文章站 2022-06-19 15:09:06
目录配置文件映射为javabean覆盖mongodbfactorymongodb测试创建dao接口及实现在springboot中,我们可以通过引入 spring-boot-starter-data-m...

在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连接池配置内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!