gpt4 book ai didi

mongodb - 在 JavaEE Web 服务中使用单个 MongoClient

转载 作者:IT老高 更新时间:2023-10-28 13:19:49 25 4
gpt4 key购买 nike

在阅读了 mongo 文档中说 MongoClient 的每个实例都处理自己的池之后,我将如何在整个应用程序中只拥有一个实例?

这似乎是使用单例 bean 的场景,但这似乎会破坏连接池的目的。如果一次只有一个用户能够访问包含 MongoClient 实例的 bean,那么肯定不会同时使用池中的多个连接。

我对单例的理解是否错误,或者这确实是正确的方法?

最佳答案

but this seems like it would defeat the purpose of connection pooling.If only one user would be able to access the bean that contains the MongoClient instance at a time, surely multiple connections in the pool would never be used at the same time.

javadoc 说:

The Java MongoDB driver is thread safe. If you are using in a web serving environment, for example, you should create a single MongoClient instance, and you can use it in every request. The MongoClient object maintains an internal pool of connections to the database (default maximum pool size of 100). For every request to the DB (find, insert, etc) the Java thread will obtain a connection from the pool, execute the operation, and release the connection. This means the connection (socket) used may be different each time.

因此,当您创建一个包含客户端的单例时。如 Javadoc 中所述,它可以重复使用。不需要同步,因为它是线程安全的。

how would I go about only having one instance across my whole application?

其中一种实现可能是:

public enum ConnectionFactory {
CONNECTION;
private MongoClient client = null;

private ConnectionFactory() {
try {
client = new MongoClient();
} catch (Exception e) {
// Log it.
}
}

public MongoClient getClient() {
if (client == null)
throw new RuntimeException();
return client;
}
}

并在整个应用程序中使用客户端。 Connection pooling 将由 MongoClient 照管。

MongoClient client = ConnectionFactory.CONNECTION.getClient();

或使用@singleton 注解:

@Singleton
public class SingletonA {

}

引用:http://tomee.apache.org/singleton-example.html

关于mongodb - 在 JavaEE Web 服务中使用单个 MongoClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26084965/

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