如何在java中通过JNDI连接MongoDB



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

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

我想使用 JNDI 创建 MongoClient 对象。以下是我在野蝇中的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");

最新更新