gpt4 book ai didi

java - 以面向对象的方式管理 Java 中的 Mongodb 连接

转载 作者:行者123 更新时间:2023-12-01 18:30:05 25 4
gpt4 key购买 nike

如何使用多个类正确管理 mongo 连接?

例如,我有 4 个类管理 4 个集合。

Collection1.classCollection2.class等等..

我所做的是在每个类中创建一个连接和关闭方法,这会减慢应用程序中某些事务的连接

除了创建每个类的对象并分别连接每个类之外,将应用程序连接到数据库一次并开始使用所有类实例的最佳方法是什么?

最佳答案

在应用程序中,具有所需连接数的单个 MongoClient 对象(使用连接池)将在这种情况下工作。连接池的默认值为100,并且可以根据需要修改(或配置)。

mongo客户端对象可以在应用程序启动时创建,并且仅在应用程序关闭时关闭。这节省了与每个集合访问类中的 mongo 客户端对象创建连接相关的资源。

可以在整个应用程序中使用相同的 mongo 客户端对象。 singleton 类(维护 mongo 客户端对象的一个​​实例)可以被应用程序中需要连接到 MongoDB 数据库服务器的任何其他对象访问。

<小时/> What is connection pooling?

In software engineering, a connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required. Connection pools are used to enhance the performance of executing commands on a database. Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources. In connection pooling, after a connection is created, it is placed in the pool and it is used again so that a new connection does not have to be established. If all the connections are being used, a new connection is made and is added to the pool. Connection pooling also cuts down on the amount of time a user must wait to establish a connection to the database.

<小时/>

示例代码:

/*
* Manages the MongoClient object and its settings like host, port, connection pool, etc.
*/
public class DBAccess {

private static MongoClient mongoClient;
private static DBAccess dbAccess;

// MongoClient with default settings
// NOTE: the code will have only one of the constructors
//private DBAccess() {
// final String connectionString = "mongodb://localhost:27017";
// this.mongoClient = MongoClients.create(connectionString);
//}

// MongoClient with custom settings.
// Private constructor, so that the class can be instantiated outside this class.
// NOTE: the code will have only one of the constructors
private DBAccess() {

MongoClientSettings settings =
MongoClientSettings.builder()
.applyToConnectionPoolSettings(builder ->
builder.maxSize(40).minSize(10))
.applyToClusterSettings(builder ->
builder.hosts(Arrays.asList(new ServerAddress("localhost", 27017))))
.build();

mongoClient = MongoClients.create(settings);
}

public static MongoClient getConnection() {

if (dbAccess == null) {
dbAccess = new DBAccess();
}

return mongoClient;
}

public static void closeDatabase() {
mongoClient.close();
}
}

/*
* Class manages a collection.
*/
public class CollectionOneAccess {

public static String COLLECTION_ONE = "collection_one";
private MongoCollection<Document> collection;

public CollectionOneAccess(MongoDatabase db) {
collection = db.getCollection(COLLECTION_ONE);
}

public void printOneDocument() {
Document myDoc = collection.find().first();
System.out.println(myDoc.toJson());
}

// other CRUD operations ...

}


// Usage of DBAcess and CollectionOneAccess classes:

private static final String APP_DATABASE = "abc_db";

public static void main(String [] args) {
MongoDatabase database = DBAccess.getConnection().getDatabase(APP_DATABASE);
CollectionOneAccess one = new CollectionOneAccess(database);
one.printOneDocument();
// ...
}
<小时/>

Mongo 客户端

MongoClient 对象用于连接到 MongoDB 服务器,使用 getDatebase() 方法访问数据库并使用集合。

com.mongodb.client.MongoClient接口(interface):

A client-side representation of a MongoDB cluster. Instances can represent either a standalone MongoDB instance, a replica set, or a sharded cluster. Instance of this class are responsible for maintaining an up-to-date state of the cluster, and possibly cache resources related to this, including background threads for monitoring, and connection pools.

来自MongoDB Java documentation :

MongoClient实例代表数据库的连接池;即使有多个线程,您也只需要 MongoClient 类的一个实例。

IMPORTANT: Typically you only create one MongoClient instance for a given MongoDB deployment (e.g. standalone, replica set, or a sharded cluster) and use it across your application. However, if you do create multiple instances:

  • All resource usage limits (e.g. max connections, etc.) apply per MongoClient instance.
  • To dispose of an instance, call MongoClient.close() to clean up resources.

以下代码使用默认设置(例如主机(“localhost”)和端口(27017)、连接池等)创建 MongoDB 客户端连接对象,并连接到 MongoDB 实例获取对 testDB 数据库的访问权限。

MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("testDB");

Mongo 客户端设置:

您可以使用 MongoClientSettings 显式指定其他设置来控制 MongoClient 的行为。

MongoClient mongoClient = MongoClients.create(MongoClientSettings settings)

ConnectionPoolSettings 对象指定与 MongoDB 服务器连接池相关的所有设置。应用程序在创建客户端对象时创建此连接池。 ConnectionPoolSettings.BuilderConnectionPoolSettings 的构建器,具有指定连接池属性的方法。例如,maxSize​(int maxSize):允许的最大连接数(默认为100)。其他方法包括 minSizemaxConnectionIdleTime 等。

使用连接池设置实例化 MongoClient 的代码:

MongoClientSettings settings = MongoClientSettings.builder()
.applyToConnectionPoolSettings(builder ->
builder.maxSize(20))
.build();
MongoClient mongoClient = MongoClients.create(settings);
// ...
// Verify the connection pool settings
System.out.println("Pool size: " +
settings.getConnectionPoolSettings().getMaxSize());

关于java - 以面向对象的方式管理 Java 中的 Mongodb 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60180119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com