apache-DBCP基本配置介绍
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 一般优化的配置示例:
<bean id="dbcpDataSource"/><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><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" />
jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost/iecmsjdbc.username=rootjdbc.password=
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 sjsky007@gmail.com */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(); }}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 sjsky007@gmail.com */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) { } } }}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 sjsky007@gmail.com */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(); } } }}