What you need is a connection pool that you can easily configure out of the box in Tomcat
, this way the connection pool will be managed directly by Tomcat
which avoids a lot of integration issues, guarantees a full compatibility and avoids adding new dependencies.
Here are the steps to follow:
1. Define the connection pool globally
In conf/contex.xml
you need to define your connection pool as Resource
so for example in you case it could be something like that:
<Context>
...
<Resource name="jdbc/myPool" auth="Container" type="javax.sql.DataSource"
initialSize="5" maxActive="20" minIdle="5" maxIdle="15" maxWait="10000"
validationQuery="SELECT 1" validationQueryTimeout="5"
testWhileIdle="true" testOnBorrow="true" testOnReturn="false"
timeBetweenEvictionRunsMillis="30000" minEvictableIdleTimeMillis="60000"
removeAbandoned="true" removeAbandonedTimeout="300" logAbandoned="false"
poolPreparedStatements="true"
username="myUsername" password="myPassword"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://182.31.456.32:3306/mydb?autoReconnect=true" />
</Context>
2. Declare your connection pool for your webapp
In the web.xml
of your webapp, you need to define it locally using a resource-ref
as next:
<web-app>
...
<resource-ref>
<res-ref-name>jdbc/myPool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
...
</web-app>
3. Access to my datasource from my code
You can then access to your DataSource
using JNDI
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myPool");
Connection conn = ds.getConnection();
4. Deploy your JDBC
driver
Your JDBC
driver needs to be available in the Common ClassLoader of Tomcat as it is a global resource, such that you need to put the jar of your driver in tomcat/lib
More details about JNDI
Datasource in Tomcat
here