apache-DBCP基本配置介绍

apache-DBCP基本配置介绍

博客分类: Java
ApacheJava连接池JDBCdbcp
    blog迁移至:http://www.micmiu.com

本文主要介绍apache-dbcp基本参数配置和应用示例,dbcp目前最新版是1.4需要在jdk1.6的环境下运行,如果要在jdk1.4、1.5环境下运行,需要下载前一版本1.3,具体详细可以查看它的官网。
本文结构目录分两大部分:
一、基础参数说明
二、dbcp在spring、hibernate等应用中的配置示例
以后会陆续给出有关c3p0、proxool等相关参数介绍和应用配置实例。

c3p0的配置介绍已经发表参见:http://sjsky.iteye.com/blog/1107197

proxool的配置介绍已经发表参见:http://sjsky.iteye.com/blog/1108808

[ 一 ]、参数介绍
[ 1 ]、基础参数说明
defaultAutoCommit: 对于事务是否 autoCommit, 默认值为 true
defaultReadOnly:对于数据库是否只能读取, 默认值为 false
initialSize:连接池启动时创建的初始化连接数量(默认值为0)
driverClassName:连接数据库所用的 JDBC Driver Class,
url: 连接数据库的 URL
username:登陆数据库所用的帐号
password: 登陆数据库所用的密码
maxActive: 连接池中可同时连接的最大的连接数,为0则表示没有限制,默认为8
maxIdle: 连接池中最大的空闲的连接数(默认为8,设 0 为没有限制),超过的空闲连接将被释放,如果设置为负数表示不限制(maxIdle不能设置太小,因为假如在高负载的情况下,连接的打开时间比关闭的时间快,会引起连接池中idle的个数 上升超过maxIdle,而造成频繁的连接销毁和创建)
minIdle:连接池中最小的空闲的连接数(默认为0,一般可调整5),低于这个数量会被创建新的连接(该参数越接近maxIdle,性能越好,因为连接的创建和销毁,都是需要消耗资源的;但是不能太大,因为在机器很空闲的时候,也会创建低于minidle个数的连接)
maxWait: 超过时间会丟出错误信息 最大等待时间(单位为 ms),当没有可用连接时,连接池等待连接释放的最大时间,超过该时间限制会抛出异常,如果设置-1表示无限等待(默认为-1,一般可调整为60000ms,避免因线程池不够用,而导致请求被无限制挂起)
validationQuery: 验证连接是否成功, SQL SELECT 指令至少要返回一行
removeAbandoned:超过removeAbandonedTimeout时间后,是否进行没用连接的回收(默认为false)
removeAbandonedTimeout: 超过时间限制,回收五用的连接(默认为 300秒),removeAbandoned 必须为 true
logAbandoned: 是否记录中断事件, 默认为 false
一般优化的配置示例:
Xml代码  收藏代码
<bean id="dbcpDataSource" 
        class="org.apache.commons.dbcp.BasicDataSource" 
        destroy-method="close"> 
        <property name="driverClassName" 
            value="${jdbc.driverClassName}" /> 
        <property name="url" value="${jdbc.url}" /> 
        <property name="username" value="${jdbc.username}" /> 
        <property name="password" value="${jdbc.password}" /> 
        <property name="maxActive" value="20" /> 
        <property name="initialSize" value="1" /> 
        <property name="maxWait" value="60000" /> 
        <property name="maxIdle" value="15" /> 
        <property name="minIdle" value="5" /> 
        <property name="removeAbandoned" value="true" /> 
        <property name="removeAbandonedTimeout" value="180" /> 
        <property name="connectionProperties"> 
            <value>clientEncoding=utf-8</value> 
        </property> 
    </bean> 


[ 2 ]、validate配置参数说明
minEvictableIdleTimeMillis:大于0 ,进行连接空闲时间判断,或为0,对空闲的连接不进行验证;默认30分钟
timeBetweenEvictionRunsMillis:失效检查线程运行时间间隔,如果小于等于0,不会启动检查线程,默认-1
testOnBorrow:在进行borrowObject进行处理时,对拿到的connection进行validateObject校验,默认为false
testOnReturn:就是在进行returnObject对返回的connection进行validateObject校验,默认为false
testWhileIdle:GenericObjectPool中针对pool管理,起了一个Evict的TimerTask定时线程进行控制(可通过设置参数timeBetweenEvictionRunsMillis>0),定时对线程池中的链接进行validateObject校验,对无效的链接进行关闭后,会调用ensureMinIdle,适当建立链接保证最小的minIdle连接数,默认为false
numTestsPerEvictionRun:每次检查链接的数量,建议设置和maxActive一样大,这样每次可以有效检查所有的链接.
validateQuery:验证检查执行的sql
validateQueryTimeout:在执行检查时超时设置,通过statement 设置,statement.setQueryTimeout(validationQueryTimeout)
配置示例:
Xml代码  收藏代码
<property name="testWhileIdle" value="true" /> 
<property name="testOnBorrow" value="false" /> 
<property name="testOnReturn" value="false" /> 
<property name="validationQuery"> 
    <value>select sysdate from dual</value> 
</property> 
<property name="validationQueryTimeout" value="1" /> 
<property name="timeBetweenEvictionRunsMillis" value="30000" /> 
<property name="numTestsPerEvictionRun" value="20" /> 

[ 二 ]、dbcp在spring、hibernate等应用中的配置示例
dbcp.jdbc.properties
Java代码  收藏代码
jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost/iecms 
jdbc.username=root 
jdbc.password= 

[ 1 ]、最基本的应用
Java代码  收藏代码
package michael.jdbc.dbcp; 
 
import javax.sql.DataSource; 
import java.sql.Connection; 
import java.sql.Statement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.util.Properties; 
 
import org.apache.commons.dbcp.BasicDataSource; 
 
/**
* @see http://sjsky.iteye.com
* @author michael [email protected]
*/ 
public class DbcpDataSourceExample { 
 
    /**
     * @param args
     */ 
    public static void main(String[] args) { 
 
        String testSql = "select * from TB_MYTEST"; 
        String cfgFileName = "dbcp.jdbc.properties"; 
 
        System.out.println("Setting up data source."); 
        DataSource dataSource = setupDataSource(cfgFileName); 
        System.out.println("dataSource Done."); 
 
        printDataSourceStats(dataSource); 
 
        Connection conn = null; 
        Statement stmt = null; 
        ResultSet rset = null; 
 
        try { 
            System.out.println("Creating connection start."); 
            conn = dataSource.getConnection(); 
 
            System.out.println("Creating statement start."); 
            stmt = conn.createStatement(); 
 
            System.out.println("Executing statement start."); 
            rset = stmt.executeQuery(testSql); 
 
            System.out.println("executeQuery Results:"); 
            int numcols = rset.getMetaData().getColumnCount(); 
 
            while (rset.next()) { 
                for (int i = 1; i <= numcols; i++) { 
                    System.out.print("\t" + rset.getString(i)); 
                } 
                System.out.println(""); 
            } 
            System.out.println("Results display done."); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } finally { 
            try { 
                if (rset != null) 
                    rset.close(); 
            } catch (Exception e) { 
            } 
            try { 
                if (stmt != null) 
                    stmt.close(); 
            } catch (Exception e) { 
            } 
            try { 
                if (conn != null) 
                    conn.close(); 
                shutdownDataSource(dataSource); 
            } catch (Exception e) { 
            } 
 
        } 
    } 
 
    /**
     * @param cfgFileName
     * @return DataSource
     */ 
    public static DataSource setupDataSource(String cfgFileName) { 
        BasicDataSource ds = new BasicDataSource(); 
        try { 
            Properties cfgpp = new Properties(); 
            cfgpp.load(DbcpDataSourceExample.class 
                    .getResourceAsStream(cfgFileName)); 
            ds.setDriverClassName(cfgpp.getProperty("jdbc.driverClassName")); 
            ds.setUrl(cfgpp.getProperty("jdbc.url")); 
            ds.setUsername(cfgpp.getProperty("jdbc.username")); 
            ds.setPassword(cfgpp.getProperty("jdbc.password")); 
        } catch (Exception e) { 
            e.printStackTrace(); 
            return null; 
        } 
 
        return ds; 
    } 
 
    /**
     * @param ds
     */ 
    public static void printDataSourceStats(DataSource ds) { 
        BasicDataSource bds = (BasicDataSource) ds; 
        System.out.println("NumActive: " + bds.getNumActive()); 
        System.out.println("NumIdle: " + bds.getNumIdle()); 
    } 
 
    /**
     * @param ds
     * @throws SQLException
     */ 
    public static void shutdownDataSource(DataSource ds) throws SQLException { 
        BasicDataSource bds = (BasicDataSource) ds; 
        bds.close(); 
    } 


运行结果:
引用
Setting up data source.
dataSource Done.
NumActive: 0
NumIdle: 0
Creating connection start.
Creating statement start.
Executing statement start.
executeQuery Results:
1 batch add 0 2011-06-16 14:29:08.0
2 batch add 1 2011-06-16 14:29:08.0
3 batch add 2 2011-06-16 14:29:08.0
4 batch add 3 2011-06-16 14:29:08.0
5 batch add 4 2011-06-16 14:29:08.0
Results display done.

[ 2 ]、结合spring的应用测试
Xml代码  收藏代码
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> 
<beans> 
    <bean id="propertyConfigurer" 
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
        <property name="locations"> 
            <list> 
                <value> 
                    classpath:michael/jdbc/dbcp/dbcp.jdbc.properties 
                </value> 
            </list> 
        </property> 
    </bean> 
 
    <bean id="dbcpDataSource" 
        class="org.apache.commons.dbcp.BasicDataSource" 
        destroy-method="close"> 
        <property name="driverClassName" 
            value="${jdbc.driverClassName}" /> 
        <property name="url" value="${jdbc.url}" /> 
        <property name="username" value="${jdbc.username}" /> 
        <property name="password" value="${jdbc.password}" /> 
        <property name="maxActive" value="20" /> 
        <property name="initialSize" value="1" /> 
        <property name="maxWait" value="60000" /> 
        <property name="maxIdle" value="15" /> 
        <property name="minIdle" value="5" /> 
        <property name="removeAbandoned" value="true" /> 
        <property name="removeAbandonedTimeout" value="180" /> 
        <property name="connectionProperties"> 
            <value>clientEncoding=utf-8</value> 
        </property> 
    </bean> 
 
</beans> 

Java代码  收藏代码
package michael.jdbc.dbcp; 
 
import java.sql.Connection; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
 
import javax.sql.DataSource; 
 
import org.apache.commons.dbcp.BasicDataSource; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
 
/**
* @see http://sjsky.iteye.com
* @author michael [email protected]
*/ 
public class DbcpSpringExample { 
 
    /**
     * @param args
     */ 
    public static void main(String[] args) { 
        System.out.println("spring xml init start "); 
        ApplicationContext appCt = new ClassPathXmlApplicationContext( 
                "michael/jdbc/dbcp/dbcp.ds.spring.xml"); 
 
        System.out.println("spring bean create DataSource"); 
        DataSource dataSource = (BasicDataSource) appCt 
                .getBean("dbcpDataSource"); 
 
        String testSql = "select * from TB_MYTEST"; 
 
        Connection conn = null; 
        Statement stmt = null; 
        ResultSet rset = null; 
 
        try { 
            System.out.println("Creating connection start."); 
            conn = dataSource.getConnection(); 
 
            System.out.println("Creating statement start."); 
            stmt = conn.createStatement(); 
 
            System.out.println("Executing statement start."); 
            rset = stmt.executeQuery(testSql); 
 
            System.out.println("executeQuery Results:"); 
            int numcols = rset.getMetaData().getColumnCount(); 
 
            while (rset.next()) { 
                for (int i = 1; i <= numcols; i++) { 
                    System.out.print("\t" + rset.getString(i)); 
                } 
                System.out.println(""); 
            } 
            System.out.println("Results display done."); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } finally { 
            try { 
                if (rset != null) 
                    rset.close(); 
            } catch (Exception e) { 
            } 
            try { 
                if (stmt != null) 
                    stmt.close(); 
            } catch (Exception e) { 
            } 
            try { 
                if (conn != null) 
                    conn.close(); 
            } catch (Exception e) { 
            } 
 
        } 
 
    } 
 


运行结果:
引用
spring xml init start
spring bean create DataSource
Creating connection start.
Creating statement start.
Executing statement start.
executeQuery Results:
1 batch add 0 2011-06-16 14:29:08.0
2 batch add 1 2011-06-16 14:29:08.0
3 batch add 2 2011-06-16 14:29:08.0
4 batch add 3 2011-06-16 14:29:08.0
5 batch add 4 2011-06-16 14:29:08.0
Results display done.


[ 3 ]、结合hibernate的应用测试
DBCP在Hibernate2中受支持,目前在hibernate3.0,已经不再支持dbcp了,hibernate的作者在hibernate.org中,明确指出在实践中发现dbcp有 BUG,在某些种情会产生很多空连接不能释放,所以推荐使用c3p0连接,本文重点只是描述其基本使用配置,不是比较两者的优劣,故不过多展开描述。
Xml代码  收藏代码
<!DOCTYPE hibernate-configuration 
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" 
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 
 
<hibernate-configuration> 
 
    <session-factory> 
        <!--database connection settings --> 
        <property name="connection.driver_class"> 
            com.mysql.jdbc.Driver 
        </property> 
        <property name="connection.url"> 
            jdbc:mysql://localhost/iecms 
        </property> 
        <property name="connection.username">root</property> 
        <property name="connection.password"></property> 
 
        <!-- dbcp --> 
        <!-- 连接池的最大活动个数 --> 
        <property name="dbcp.maxActive">100</property> 
        <!-- 当连接池中的连接已经被耗尽的时候,DBCP将怎样处理( 0 = 失败, 1 = 等待, 2= 增长) --> 
        <property name="dbcp.whenExhaustedAction">1</property> 
        <!-- 最大等待时间(ms)  --> 
        <property name="dbcp.maxWait">60000</property> 
        <!-- 最大闲置的连接个数 --> 
        <property name="dbcp.maxIdle">10</property> 
        <!-- 下面是对 prepared statement --> 
        <property name="dbcp.ps.maxActive">100</property> 
        <property name="dbcp.ps.whenExhaustedAction">1</property> 
        <property name="dbcp.ps.maxWait">60000</property> 
        <property name="dbcp.ps.maxIdle">10</property> 
 
        <property name="current_session_context_class">thread</property> 
        <property name="show_sql">false</property> 
        <property name="dialect"> 
            org.hibernate.dialect.MySQL5Dialect 
        </property> 
 
        <property name="hbm2ddl.auto">update</property> 
    </session-factory> 
</hibernate-configuration> 

Java代码  收藏代码
package michael.jdbc.dbcp; 
 
import java.util.List; 
 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.hibernate.cfg.AnnotationConfiguration; 
import org.hibernate.cfg.Configuration; 
 
/**
* @see http://sjsky.iteye.com
* @author michael [email protected]
*/ 
public class DbcpHibernateExample { 
 
    /**
     * @param args
     */ 
    public static void main(String[] args) { 
        SessionFactory sessionFactory = null; 
        try { 
            System.out.println(" hibernate config start"); 
            Configuration config = new AnnotationConfiguration() 
                    .configure("michael/jdbc/dbcp/hibernate.cfg.xml"); 
 
            System.out.println(" create sessionFactory "); 
            sessionFactory = config.buildSessionFactory(); 
 
            System.out.println(" create session "); 
            Session session = sessionFactory.getCurrentSession(); 
            String testSql = "select * from TB_MYTEST"; 
 
            System.out.println(" beginTransaction "); 
            Transaction ta = session.beginTransaction(); 
            org.hibernate.Query query = session.createSQLQuery(testSql); 
            List<Object[]> list = query.list(); 
            System.out.println(" createSQLQuery list: "); 
            for (Object[] objArr : list) { 
                for (Object obj : objArr) { 
                    System.out.print("\t" + obj); 
                } 
                System.out.println(""); 
            } 
            System.out.println(" beginTransaction commit "); 
            ta.commit(); 
 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } finally { 
            if (null != sessionFactory) { 
                sessionFactory.close(); 
            } 
 
        } 
 
    } 


运行结果:
引用
hibernate config start
create sessionFactory
create session
beginTransaction
createSQLQuery list:
1 batch add 0 2011-06-16 14:29:08.0
2 batch add 1 2011-06-16 14:29:08.0
3 batch add 2 2011-06-16 14:29:08.0
4 batch add 3 2011-06-16 14:29:08.0
5 batch add 4 2011-06-16 14:29:08.0
beginTransaction commit


转载请注明来自:Michael's blog @ http://sjsky.iteye.com

你可能感兴趣的:(java,jdbc)