Saturday, 19 October 2013

Tomcat connection pooling

->This Tomcat connection pool Depends on Tomcat web server

->First configure database details and connection pool details in the context.xml file in META-INF folder of our web project

->Use ojdbc14.jar

Context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/Client" docBase="ClientModule" crossContext="true" reloadable="false" debug="1">
    <Resource name="jdbcResource" auth="Container" type="javax.sql.DataSource"
       username="dbuser"
       password="dbpassword"
        driverClassName="oracle.jdbc.driver.OracleDriver"
        url="jdbc:oracle:thin:@192.168.0.178:1521:orcl"
        initialSize="25"
        maxActive="25"
        maxIdle="25"
        minIdle="10"
        maxWait="5000"
        removeAbandonedTimeout="50"
        removeAbandoned="true"
        testOnBorrow="true">
   </Resource>
</Context>

username:database username

password:database password

driverClassName:We are using oracle database so 
oracle.jdbc.driver.OracleDriver class

url: database url and database name

initialSize:That means at the time of pool creating it will create 25(we can give any number) connections,after that automatically pool creates new connections based on request.
maxActive:That means at the same time 25(we can give any number) connections only in active mode,so at the same time 26th person can’t get new connection from pool.

maxIdle:Idle means not used objects available in the pool,maximum the pool can have 25(we can give any number) idle objects

minIdle:Any time pool will have minimum of 10 idle objects.

maxWait:We are ready to getting new connection from pool,but pool don’t have connections,so we will wait for 5000 milliseconds(5 seconds),After that time also pool don’t have connections to give us then only displaying error like  org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object.

removeAbandonedTimeout:50(we can give any number)means when the pool give the connection to us,and we didn’t return back the connection to pool,it will wait for 50 seconds for that connection,After 50 seconds this object is eligible for eviction.

romoveAbondoned: true means After removeAbondonedTime(50 seconds) pool forcefully get that object from us(from java program),If our program execution is not completed also pool will close the connection and get the connection.

testOnBorrow:true means at the time of getting connection from pool it will validate that connection.If validation fails,that connection will remove from the pool and create new connection.

testOnReturn:true means at the time of returning the connection to pool ,it will check that connection,
If validation fails,that connection will not return to pool.

minEvictableIdleTimeMillis:(int) The minimum amount of time an object may sit idle in the pool before it is eligible for eviction. The default value is 60000(60 seconds).This property uses pool internally for idle objects.

timeBetweenEvictionRunsMillis:(int) The number of milliseconds to sleep between runs of the idle connection validation/cleaner thread. This value should not be set under 1 second. It dictates how often we check for idle, abandoned connections, and how often we validate idle connections. The default value is 5000 (5 seconds).

->Create Web based Application

ConnectionPoolClass.java

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;


public class ConnectionPoolClass {
      
       public static InitialContext initialContext=null;
       public static DataSource datasource=null;
       Connection con=null;
      
        static {
                try{
                    initialContext = new InitialContext();
                    datasource = (DataSource)initialContext.lookup("java:/comp/env/jdbcResource");
                   
                }catch(Exception e)
                {
                e.printStackTrace();
                }
        }
        
        public boolean getConnection() {
               
                     try {
                           con=(Connection)datasource.getConnection();
                           System.out.println("connection is:"+con);
                     } catch (SQLException e) {
                           e.printStackTrace();
                     }
                      
               return true;
        }
        
        public void closeConnection() {
               try {
                     con.close();
              } catch (SQLException e) {
                     e.printStackTrace();
              }
        }
}

MyServlet.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {
      
       public void doGet(HttpServletRequest request,HttpServletResponse response) {
              PrintWriter out=null;
              try {
                     out=response.getWriter();
              } catch (IOException e) {
                     e.printStackTrace();
              }
              ConnectionPoolClass cp=new ConnectionPoolClass();
             
              cp.getConnection();
              cp.closeConnection();
      
       }
}


Web.xml
<servlet>
       <servlet-name>xxx</servlet-name>
       <servlet-class>com.iton.MyServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
       <servlet-name>xxx</servlet-name>
       <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>


->This program only getting the connection from connection pool,If we get the connection remaining code is normal like perfoming CURD operations to create,update,retrieve,delete with database.

No comments:

Post a Comment