在JavaEE Web服务中使用单个MongoClient [英] Use a single MongoClient across a JavaEE web service

查看:157
本文介绍了在JavaEE Web服务中使用单个MongoClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了mongo文档后,说明MongoClient的每个实例都处理了自己的池,我怎样才能在整个应用程序中只有一个实例?

After reading the mongo documentation that says each instance of a MongoClient handles its own pooling, how would I go about only having one instance across my whole application?

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

This seems like it could be a scenario for using a singleton 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.

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

Have I got my understanding of singletons wrong, or is that indeed the right way to go about it?

推荐答案


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

javadoc 说:


Java MongoDB驱动程序是线程安全的。例如,如果您在网络
服务环境中使用,应该创建一个
MongoClient实例,并且您可以在每个请求中使用它。
MongoClient对象维护与
数据库的内部连接池(默认最大池大小为100)。对于
DB(查找,插入等)的每个请求,Java线程将从
池中获取连接,执行操作并释放连接。

表示每次使用的连接(套接字)可能不同。

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中提到的那样重复使用。不需要同步,因为它是线程安全的。

So, when you create a singleton with the client in it. It can be re-used as mentioned in the Javadoc. No synchronization is required, since it is thread safe.


我如何在整个应用程序中只有一个实例?

其中一个实现可能是:

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;
    }
}

并在整个申请过程中使用客户端。 连接池将由记录的 MongoClient 处理。

and use the client as, throughout the application. Connection pooling will be taken care by the MongoClient as documented.

MongoClient client = ConnectionFactory.CONNECTION.getClient();

或使用@singleton注释:

or use the @singleton annotation:

@Singleton
public class SingletonA {

}

参考: http://tomee.apache.org/singleton-example.html

这篇关于在JavaEE Web服务中使用单个MongoClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆