Friday, October 06, 2006

Pool connection

Here is a quick way to make a connection pool...
  1. Get the jar file, that will be specific to the database to which you want to connect and place it in the /WEB-INF/lib folder.

  2. And edit /META-INF/context.xml...
    <Context reloadable="true">
    ....
    <Resource
    name = "jdbc/dbtest"
    auth = "Container"
    type = "javax.sql.DataSource"
    factory = "org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
    driverClassName = "org.postgresql.Driver"
    url = "jdbc:postgresql://IPAddress:port/databasename"
    username = "root"
    password = "root"
    maxActive = "5"
    initialSize = "3"
    maxIdle = "2"
    maxWait = "10000"
    removeAbandoned = "true"
    removeAbandonedTimeout = "60"
    logAbandoned = "true"
    />
    ....
    </Context>

  3. Java code to get connection from the pool...
    InitialContext initCtx = new InitialContext();
    Context ctx = (Context) initCtx.lookup("java:comp/env");
    DataSource ds = (DataSource) ctx.lookup("jdbc/dbtest");
    conn = ds.getConnection();
That's it. Start the tomcat server and launch the application...
Here are the details of the attributes used in xml file.
  1. Name: The java:comp/env prefix is the name of the JNDI context for the component. This is used in the Java code. The jdbc/dbtest string is the JNDI name for the resource reference. The JNDI names for JDBC DataSource objects are stored in the java:comp/env/jdbc subcontext.

  2. auth: Authration will be done by container. I don't know much about this. Will update soon.

  3. driverClassName: Fully qualified Java class name of the JDBC driver to be used.

  4. url: Connection URL to be passed to JDBC driver.

  5. username: Database login username.

  6. password: Database login password.

  7. maxActive: (Default: 8) The maximum number of active instances that can be allocated from this pool at the same time.

  8. maxIdle: (Default: 8) The maximum number of connections that can sit idle in this pool at the same time.

  9. maxWait: (Deafult: indefinitely) The maximum number of milliseconds that the pool will wait (when there are no available connections) for a connection to be returned before throwing an exception.

  10. initialSize: (Default: 0) The initial size of the pool.

  11. removeAbandoned: (Default: false) Flag to remove abandoned connections if they exceed the removeAbandonedTimout. If set to true a connection is considered abandoned and eligible for removal if it has been idle longer than the removeAbandonedTimeout. Setting this to true can recover db connections from poorly written applications which fail to close a connection.

  12. removeAbandonedTimeout: (Default 300) Timeout in seconds before an abandoned connection can be removed.

  13. logAbandoned: (Default: false) Flag to log stack traces for application code which abandoned a Statement or Connection.


Note: For more details check commons-dbcp documentation.
Thanks
E ñ j Ô ÿ !!! iN D
p
0 o l
:-)