首先,我们需要了解什么是数据库连接池。数据库连接池是数据库连接的缓存池,它的主要目的是减少数据库连接的创建和销毁次数,提升系统性能。使用数据库连接池可以减少每次连接数据库所需的时间和资源。Java实现MongoDB的数据库连接池有两种方式,分别是通过第三方连接池库和手动实现连接池。
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>com.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-core</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.4.1</version>
</dependency>
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import com.mongodb.MongoClientSettings;
import com.mongodb.ServerAddress;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoClients;
import com.zaxxer.hikari.HikariDataSource;
public class MongoDBConfig {
private static final String DATABASE_NAME = "test";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private static final String HOST = "localhost";
private static final int PORT = 27017;
public static HikariDataSource getDataSource() {
MongoClientSettings settings = MongoClientSettings.builder()
.applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress(HOST, PORT))))
.credential(MongoCredential.createCredential(USERNAME, DATABASE_NAME, PASSWORD.toCharArray()))
.build();
MongoDatabase database = MongoClients.create(settings).getDatabase(DATABASE_NAME);
HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setJdbcUrl("jdbc:mongodb://" + HOST + ":" + PORT + "/" + DATABASE_NAME);
hikariDataSource.setDataSourceClassName("org.mongodb.jdbc.MongoDataSource");
hikariDataSource.setUsername(USERNAME);
hikariDataSource.setPassword(PASSWORD);
return hikariDataSource;
}
public static MongoDatabase getMongoDatabase() {
HikariDataSource dataSource = getDataSource();
return dataSource.unwrap(MongoDatabase.class);
}
public static MongoCollection<Document> getMongoCollection(String collectionName) {
MongoDatabase database = getMongoDatabase();
return database.getCollection(collectionName);
}
}
MongoCollection<Document> collection = null;
try (Connection connection = MongoDBConfig.getDataSource().getConnection()) {
collection = MongoDBConfig.getMongoCollection("collectionName");
// do something with the collection
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (collection != null) collection.close();
}
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>com.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-core</artifactId>
<version>4.4.1</version>
</dependency>
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import java.util.Arrays;
public class MongoDBPool {
private static final String DATABASE_NAME = "test";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private static final String HOST = "localhost";
private static final int PORT = 27017;
private static final int MAX_TOTAL = 8;
private static final int MAX_IDLE = 4;
private static final GenericObjectPool<MongoDatabase> mongoPool;
static {
MongoClientSettings settings = MongoClientSettings.builder()
.applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress(HOST, PORT))))
.credential(MongoCredential.createCredential(USERNAME, DATABASE_NAME, PASSWORD.toCharArray()))
.build();
PooledObjectFactory<MongoDatabase> pooledObjectFactory = new MongoDBPoolFactory(settings);
GenericObjectPoolConfig<MongoDatabase> genericObjectPoolConfig = new GenericObjectPoolConfig<>();
genericObjectPoolConfig.setMaxTotal(MAX_TOTAL);
genericObjectPoolConfig.setMaxIdle(MAX_IDLE);
mongoPool = new GenericObjectPool<>(pooledObjectFactory, genericObjectPoolConfig);
}
public static MongoDatabase borrowObject() {
try {
return mongoPool.borrowObject();
} catch (Exception e) {
throw new RuntimeException("Error: Could not borrow connection from MongoDB connection pool");
}
}
public static void returnObject(MongoDatabase database) {
mongoPool.returnObject(database);
}
}
MongoDatabase database = null;
try {
database = MongoDBPool.borrowObject();
MongoCollection<Document> collection = database.getCollection("collectionName");
// do something with the collection
} finally {
if (database != null) {
MongoDBPool.returnObject(database);
}
}
本文链接:http://task.lmcjl.com/news/18722.html