简体   繁体   中英

Placing MongoDB server properties in context.xml

In an JAVA web project hosted in Tomcat with a backend ORACLE/MYSQL We could add a <Resource> like below (consider connection an Oracle Server)

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/myProject">

  <Resource auth="Container" driverClassName="oracle.jdbc.driver.OracleDriver" 
  factory="oracle.jdbc.pool.OracleDataSourceFactory" 
  maxActive="20" maxIdle="10" 
  maxWait="-1" name="jdbc/TestDB" password="dbPAss" type="oracle.jdbc.pool.OracleDataSource" 
  url="jdbc:oracle:thin:@DBHOST:PORT:SERVICENAME" 
  user="dbUser"/>

  <Loader delegate="true"/>
</Context>

in the context.xml of the project and only changing a few things if its connecting a MySQL and can used in a JAVA SERVLET by using

Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/TestDB");

and then creating its Connection Object

What should be the correct syntax for using it for MongoDB ?

I am intending to store the HOST,PORT, USERNAME and PASSWORD for the MongoDB server.

Tomcat only supports JDBC DataSources when using <Resource> elements (well, it supports other things like SMTP sessions, etc. but for databases, they must be JDBC-based). There is currently no JDBC driver for MongoDB (because it's not a relational database, and the JDBC API makes no sense for it) (unless you want to try this thing: https://github.com/erh/mongo-jdbc ), so you'll have to manage your own resource pool for it.

actually there is a JDBC driver for MongoDB. one was just released by a company called UnityJDBC. you can download the program and driver for free at...

http://www.unityjdbc.com/mongojdbc/mongo_jdbc.php

Tomcat (or more specifically, JNDI) does in fact support arbitrary resources ( <Resource> elements in config.xml ), including connection information for MongoDB without requiring that MongoDB (or any other non-RDBMS) be wrangled to use JDBC. All that's required is an implementation of the javax.naming API to define the properties of your custom resource (see Adding Custom Resource Factories in the Tomcat JNDI HOW-TO reference).

I recently found this GitHub project which aims to store MongoDB datasource connection information as a JNDI resource while using the official MongoDB Java client.

If you're using Spring, this other answer provides information for MongoDB datasource configuration via a JNDI resource when using Spring (and that code could also be used as a guide to creating your own custom JNDI resource loader for MongoDB or any other configuration properties you with to store in the Tomcat context.xml ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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