繁体   English   中英

如何在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创建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所需的代码更改是什么?

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

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

要么

Context ctx = new InitialContext();
MongoClient mongoClient = (MongoClient) ctx.lookup("java:global/LocalMongoClient")
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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM