In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the knowledge of "how to use the connection pool configuration of MongoDB in SpringBoot". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Catalogue
Introduce dependency
Configuration file
Profile is mapped to JavaBean
Override MongoDbFactory
MongoDB test
Create a data entity
Create Dao interface and its implementation
Write test code
In SpringBoot, we can implement the automatic configuration of spring-data-mongodb by introducing spring-boot-starter-data-mongodb dependency. By default, however, this dependency does not provide us with connection pooling configuration as it does with MySQL or Redis. Therefore, we need to rewrite the MongoDbFactory to implement the parameter configuration extension of the MongoDB client connection. It is important to note that the client of MongoDB is itself a connection pool, so we only need to configure the client.
Introduce dependency
Org.springframework.boot spring-boot-starter-parent 2.0.2.RELEASE org.springframework.boot spring-boot-starter-data-mongodb org.springframework.boot spring-boot-starter-test test profile
To facilitate the unified management of Mongodb, we extract the relevant configurations into mongo-pool.properties with the prefix spring.data.mongodb (the prefix can be configured by yourself):
Spring.data.mongodb.address=172.16.250.234:27017172.16.250.239:27017172.16.250.240:27017spring.data.mongodb.replica-set=rs0spring.data.mongodb.database=testspring.data.mongodb.username=adminspring.data.mongodb.password=admin # Configure spring.data.mongodbDB Poolspring.data.mongodb.min-connections-per-host=10spring.data.mongodb.max-connections-per-host=100spring.data.mongodb.threads-allowed-to-block-for-connection-multiplier=5spring.data.mongodb.server-selection-timeout=30000spring.data. Mongodb.max-wait-time=120000spring.data.mongodb.max-connection-idel-time=0spring.data.mongodb.max-connection-life-time=0spring.data.mongodb.connect-timeout=10000spring.data.mongodb.socket-timeout=0spring.data.mongodb.socket-keep-alive=falsespring.data.mongodb.ssl-enabled=falsespring.data.mongodb.ssl-invalid-host-name-allowed=falsespring.data.mongodb.always-use-m-beans=falsespring.data.mongodb.heartbeat-socket-timeout=20000spring.data.mongodb.heartbeat-connect-timeout=20000spring.data.mongodb.min-heartbeat- Frequency=500spring.data.mongodb.heartbeat-frequency=10000spring.data.mongodb.local-threshold=15spring.data.mongodb.authentication-database=auth_dev profile is mapped to JavaBean
For ease of calling, wrap the above configuration into a configuration entity class, as follows:
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 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; / / omit Getters and Setters methods} override MongoDbFactory
Create a custom MongoDbFactory to replace the MongoDbFactory that Springboot automatically assembles for us, as follows:
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 @ Configurationpublic class MongoConfig {private static final Logger logger = LoggerFactory.getLogger (MongoConfig.class); / / override the default MongoDbFacotry Bean @ Bean @ Autowired public MongoDbFactory mongoDbFactory (MongoSettingsProperties properties) {/ / client configuration (number of connections, replica cluster verification) 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 address list List serverAddresses = new ArrayList () 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 ()); / / connection authentication / / MongoCredential mongoCredential = null / / if (properties.getUsername ()! = null) {/ / mongoCredential = MongoCredential.createScramSha1Credential (/ / properties.getUsername (), properties.getAuthenticationDatabase ()! = null / /? Properties.getAuthenticationDatabase (): properties.getDatabase (), / / properties.getPassword (). ToCharArray (); / /} / / create authenticated client / / MongoClient mongoClient = new MongoClient (serverAddresses, mongoCredential, mongoClientOptions); / / create non-authenticated client MongoClient mongoClient = new MongoClient (serverAddresses, mongoClientOptions); / / create MongoDbFactory MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory (mongoClient, properties.getDatabase ()); return mongoDbFactory;}} MongoDB test
Create a data entity
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;}} create Dao interface and its implementation
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; @ Componentpublic 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;}} write test code
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) @ SpringBootTestpublic 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 example = Example.of (queryUser) Optional optional = userRepository.findOne (example); System.out.println (optional.get ());}}
Query results:
Id: 88,userName: XiaoMing,passWord: 123456
That's all for "how to use MongoDB connection Pool configuration in SpringBoot". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.