当前,我正在使用以下代码通过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所需的代码更改是什么。
答案 0 :(得分:1)
您可以使用以下代码调用mongodb客户端,
@Resource(lookup = "java:global/LocalMongoClient")
private MongoClient mongoClient;
或
Context ctx = new InitialContext();
MongoClient mongoClient = (MongoClient) ctx.lookup("java:global/LocalMongoClient")
答案 1 :(得分:0)
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");