Connection Pooling in Tomcat
Connection Pool
In my younger days,I used to go for fishing on a near by Lake.I used to wonder can I catch a shark today.My friend said we dont have any shark in this Lake.I wondered why?Then he explained me fishes are of 2 type
1 cold blooded:-Those who live in fresh water like river,ponds
2.warm blooded:-Those who live in Oceans
That means inside river,we can have only cold blooded fishes,and in ocean and sea,we can have only warm blooded fishes
Story is over.Lets go back to Java.
A connection Pool is a Pool or area where we can have various connection object readily available.This connection objects represents the same database,which means in Oracle related connection pool we can have only oracle connection object but not mysql connection object.
How To work with connection Pool in Tomcat
Tomcat by default gives support for DBCP Connection Pool.If you want you can also work with other connection pools like C3P0,BoneCP.But to work with connection Pool,you need to download the following jar files.
- tomcat-jdbc.jar
- tomcat-juli.jar
Download them here
Configuring Built-in Connection Pool along with oracle database.
1.Copy tomcat-jdbc.jar,tomcat-juli.jar,ojdbc14.jar to Tomcat_home\lib folder
2.Edit Tomcat_home\conf\context.xml file and add <resource>….</resource> tag under <context> tag
<context> - - - - - - - - - - - - <Resource name="mypool" type="javax.sql.DataSource" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:XE" username="system" password="manager" initialSize="10" maxActive="20" maxIdle="10" minIdle="5" maxWait="100" validationQuery="select SYSDATE from Dual"/> </context>
Develop the ClientApplication that uses the connection Pool
web.xml
<web-app></web-app>
index.jsp
<%@page import="javax.naming.*,javax.sql.*,java.sql.*"%>
<%
try
{
Context ic=new InitialContext();
DataSource ds=(DataSource)ic.lookup("java:/comp/env/mypool");
Connection con=ds.getConnection();
System.out.println(con);
//use the connection as usual
}
catch(Exception e)
{
System.out.println(e);
}
%>
Download Example Here
No comments:
Post a Comment