如何在 java 中通过 JNDI 连接 MongoDB

How to connect MongoDB via JNDI in java

目前我正在使用以下代码通过 java 连接到 MongoDB。

MongoClientURI uri = new MongoClientURI("mongodb://10.0.8.78:27017/mydb");          
MongoClient mongoClient = new MongoClient(uri);

我想使用 JNDI.Following 创建 MongoClient 对象是我在 wildfly 中的 jndi 配置。

<subsystem xmlns="urn:jboss:domain:naming:2.0">
    <bindings>
        <object-factory name="java:global/MyMongoClient" module="org.mongodb" class="com.mongodb.client.jndi.MongoClientFactory">
            <environment>
                <property name="connectionString" value="mongodb://10.0.8.78:27017/mydb" />
            </environment>
        </object-factory>
    </bindings>
    <remote-naming />
</subsystem>

创建 MongoClient 对象以通过 JNDI 连接到 MongoDB 需要更改什么代码。

1) In a Tomcat installation, copy the mongo-java-driver jar file into the lib directory.

2) In context.xml of a web application, add a resource that references the MongoClientFactory class, and the connection string for the MongoDB cluster:


    <Resource name="jdbc/MyMongo"
              auth="Container"
              type="com.mongodb.MongoClient"
              closeMethod="close"
              factory="com.mongodb.client.jndi.MongoClientFactory"
              singleton="true"
              connectionString="mongodb://localhost"/>

3) In web.xml of a web application, add a reference to the above resource:

<resource-ref>
    <res-ref-name>
        jdbc/MyMongo
    </res-ref-name>
    <res-type>
        com.mongodb.MongoClient
    </res-type>
    <res-auth>
        Container
    </res-auth>
</resource-ref>


and at last mongoClient instance will be accessible via tha JNDI 

DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/MyMongo");

您可以使用下面的代码调用 mongodb 客户端,

@Resource(lookup = "java:global/LocalMongoClient")
private MongoClient mongoClient;

Context ctx = new InitialContext();
MongoClient mongoClient = (MongoClient) ctx.lookup("java:global/LocalMongoClient")