connection pool 같이 성능에 지대한 영향을 미치는것들은 이런 유명라이브러리를 사용하여 만드는게 맞다고 본다. 일단 믿을수 있으니까.

그런데 문제는 apache 의 commons-dbcp 는 여러 컨테이너나 웹 프레임워크 상에서 지원하지만, 정작 그런 컨테이너나 프레임워크의 도움 없이는 사용하는방법을 몰랐었다.

나중에도 유용할꺼 같아서 네이버를 뒤져서 만들어봤다.

먼저 필요한 라이브러리를 받자.

1. commons-dbcp  --> http://commons.apache.org/dbcp/
2. commons-pool  -->  http://commons.apache.org/pool/

<ConnectionPool.java>

[code]package common.util;

import java.sql.Connection;
import java.sql.DriverManager;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.pool.impl.GenericObjectPool;

public class ConnectionPool {
 private String driverName = null;

 private String poolingDriverClassName = "org.apache.commons.dbcp.PoolingDriver";
 private String poolUrl = "jdbc:apache:commons:dbcp:";

 public ConnectionPool(String driverName, String driverClassName,String dbUrl, String dbUserId, String dbUserPass) {
  this(driverName, driverClassName, dbUrl, dbUserId, dbUserPass, 30, 10,100, false, true);
 }

 public ConnectionPool(String driverName, String driverClassName,String dbUrl, String dbUserId, String dbUserPass, int maxActive,int maxIdle, int maxWait) {
  this(driverName, driverClassName, dbUrl, dbUserId, dbUserPass,maxActive, maxIdle, maxWait, false, true);
 }

 public ConnectionPool(String driverName, String driverClassName,String dbUrl, String dbUserId, String dbUserPass, int maxActive,int maxIdle, int maxWait, boolean isReadOnly, boolean isAutoCommit) {
  this.driverName = driverName;
  try {
   Class.forName(driverClassName);
   GenericObjectPool connectionPool = new GenericObjectPool(null);
   connectionPool.setMaxActive(maxActive);
   connectionPool.setMaxIdle(maxIdle);
   connectionPool.setMaxWait(maxWait);

   ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(dbUrl, dbUserId, dbUserPass);

   PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, isReadOnly,isAutoCommit);
   Class.forName(poolingDriverClassName);

   PoolingDriver driver = (PoolingDriver) DriverManager.getDriver(poolUrl);

   driver.registerPool(driverName, connectionPool);
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }

 public Connection getConnection() {
  Connection conn = null;
  try {
   conn = DriverManager.getConnection(poolUrl + driverName);
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
  return conn;
 }
}[/code]
이제 클래스 생성하고 getConnection() 을 호출하면 connection pool 에 의해 얻어진 connection 을 쓸 수 있다.

'알짜정보 > Java' 카테고리의 다른 글

JNLP 테스트  (36) 2010.02.14
JAVA 리눅스 IP 주소 알아내기  (38) 2008.12.02
java 에서 xmlrpc 사용하기  (38) 2008.07.13
annotation 주석?  (43) 2006.12.16
JAVA5(1.5) 달라진점!  (19) 2006.12.16
by cranix 2008. 8. 15. 00:00