c3p0的介绍可参见:http://www.micmiu.com/j2ee/jdbc-tech/c3p0-simple
dbcp的介绍可参见:http://www.micmiu.com/j2ee/jdbc-tech/apache-dbcp-simple
本文的章节目录:
- 一、参数详细说明
- 二、多种实现方式的演示
- 三、结合spring的实例演示
一、参数详细说明
- alias:连接的别名
- driver-url: 数据库连接URL
- driver-class:数据库驱动
- fatal-sql-exception: 它是一个逗号分割的信息片段.当一个SQL异常发生时,他的异常信息将与这个信息片段进行比较.如果在片段中存在,那么这个异常将被认为是个致命错误 (Fatal SQL Exception ).这种情况下,数据库连接将要被放弃.无论发生什么,这个异常将会被重掷以提供给消费者.用户最好自己配置一个不同的异常来抛出.
- fatal-sql-exception-wrapper-class:正如上面所说,你最好配置一个不同的异常来重掷.利用这个属性,用户可以包装SQLException,使他变成另外一个异常.这个异常或者继承SQLException或者继承RuntimeException。proxool自带了2个实现类:’org.logicalcobwebs.proxool.FatalSQLException’ 和’org.logicalcobwebs.proxool.FatalRuntimeException’.后者更合适.
- house-keeping-sleep-time: house keeper 保留线程处于睡眠状态的最长时间,house keeper 的职责就是检查各个连接的状态,并判断是否需要销毁或者创建.
- house-keeping-test-sql: 如果发现了空闲的数据库连接.house keeper 将会用这个语句来测试.这个语句最好非常快的被执行.如果没有定义,测试过程将会被忽略。
- injectable-connection-interface: 允许proxool实现被代理的connection对象的方法.
- injectable-statement-interface: 允许proxool实现被代理的Statement 对象方法.
- injectable-prepared-statement-interface: 允许proxool实现被代理的PreparedStatement 对象方法.
- injectable-callable-statement-interface: 允许proxool实现被代理的CallableStatement 对象方法.
- jmx: 如果属性为true,就会注册一个消息Bean到jms服务,消息Bean对象名: “Proxool:type=Pool, name=<alias>”. 默认值为false.
- jmx-agent-id: 一个逗号分隔的JMX代理列表(如使用MBeanServerFactory.findMBeanServer(String agentId)注册的连接池。)这个属性是仅当”jmx”属性设置为”true”才有效。所有注册jmx服务器使用这个属性是不确定的
- jndi-name: 数据源的名称
- maximum-active-time: 如果housekeeper 检测到某个线程的活动时间大于这个数值.它将会杀掉这个线程.所以确认一下你的服务器的带宽.然后定一个合适的值.默认是5分钟.
- maximum-connection-count: 最大的数据库连接数.
- maximum-connection-lifetime: 一个线程的最大寿命.
- minimum-connection-count: 最小的数据库连接数
- overload-without-refusal-lifetime: 这可以帮助我们确定连接池的状态。如果我们已经拒绝了一个连接在这个设定值(毫秒),然后被认为是超载。默认为60秒。
- prototype-count: 连接池中可用的连接数量.如果当前的连接池中的连接少于这个数值.新的连接将被建立(假设没有超过最大可用数).例如.我们有3个活动连接2个可用连接,而我们的prototype-count是4,那么数据库连接池将试图建立另外2个连接.这和 minimum-connection-count不同. minimum-connection-count把活动的连接也计算在内.prototype-count 是spare connections 的数量.
- recently-started-threshold: 这可以帮助我们确定连接池的状态,连接数少还是多或超载。只要至少有一个连接已开始在此值(毫秒)内,或者有一些多余的可用连接,那么我们假设连接池是开启的。默认为60秒
- simultaneous-build-throttle: 这是我们可一次建立的最大连接数。那就是新增的连接请求,但还没有可供使用的连接。由于连接可以使用多线程,在有限的时间之间建立联系从而带来可用连接,但是我们需要通过一些方式确认一些线程并不是立即响应连接请求的,默认是10。
- statistics: 连接池使用状况统计。 参数“10s,1m,1d”
- statistics-log-level: 日志统计跟踪类型。 参数“ERROR”或 “INFO”
- test-before-use: 如果为true,在每个连接被测试前都会服务这个连接,如果一个连接失败,那么将被丢弃,另一个连接将会被处理,如果所有连接都失败,一个新的连接将会被建立。否则将会抛出一个SQLException异常。
- test-after-use: 如果为true,在每个连接被测试后都会服务这个连接,使其回到连接池中,如果连接失败,那么将被废弃。
- trace: 如果为true,那么每个被执行的SQL语句将会在执行期被log记录(DEBUG LEVEL).你也可以注册一个ConnectionListener (参看ProxoolFacade)得到这些信息.
二、多种实现方式的演示(以mysql为例)
[ 1 ]、最基础的实现
TestProxool.java:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class TestProxool { public static void main(String[] args) { Connection connection = null; Properties info = new Properties(); info.setProperty("proxool.maximum-connection-count", "10"); info.setProperty("proxool.minimum-connection-count", "3"); info.setProperty("proxool.house-keeping-test-sql", "select now()"); info.setProperty("user", "root"); info.setProperty("password", ""); String alias = "test"; String driverClass = "com.mysql.jdbc.Driver"; String driverUrl = "jdbc:mysql://localhost/michaeldemo"; String url = "proxool." + alias + ":" + driverClass + ":" + driverUrl; try { try { // 这步不能缺少 Class.forName("org.logicalcobwebs.proxool.ProxoolDriver"); } catch (ClassNotFoundException e) { System.out.println("Couldn't find driver" + e.getMessage()); e.printStackTrace(); } try { connection = DriverManager.getConnection(url, info); } catch (SQLException e) { System.out.println("Problem getting connection " + e.getMessage()); e.printStackTrace(); } if (connection != null) { System.out.println("Got connection successful : )"); } else { System.out.println("Didn't get connection, which probably means that no Driver accepted the URL"); } } catch (Exception e) { e.printStackTrace(); } finally { try { // Check to see we actually got a connection before we attempt to close it. if (connection != null) { connection.close(); } } catch (SQLException e) { System.out.println("Problem closing connection" + e.getMessage()); e.printStackTrace(); } } } }
运行结果:
Got connection successful : )
[ 2 ]、通过properties配置文件实现
proxool-demo.properties:
#The first word (up to the first dot) must start with "jdbc", but it can be anything you like. #Use unique names to identify each pool. Any property not starting with "jdbc" will be ignored. #The properties prefixed with "proxool." will be used by Proxool #while the properties that are not prefixed will be passed on to the delegate JDBC driver. jdbc-0.proxool.alias=property-test jdbc-0.proxool.driver-url=jdbc:mysql://localhost/michaeldemo jdbc-0.proxool.driver-class=com.mysql.jdbc.Driver jdbc-0.user=root jdbc-0.password= jdbc-0.proxool.house-keeping-sleep-time=40000 jdbc-0.proxool.house-keeping-test-sql=select now() jdbc-0.proxool.maximum-connection-count=10 jdbc-0.proxool.minimum-connection-count=3 jdbc-0.proxool.maximum-connection-lifetime=18000000 jdbc-0.proxool.simultaneous-build-throttle=5 jdbc-0.proxool.recently-started-threshold=40000 jdbc-0.proxool.overload-without-refusal-lifetime=50000 jdbc-0.proxool.maximum-active-time=60000 jdbc-0.proxool.verbose=true
TestProxoolCfgPp.java:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.logicalcobwebs.proxool.ProxoolException; import org.logicalcobwebs.proxool.configuration.PropertyConfigurator; public class TestProxoolCfgPp { /** * * @param args */ public static void main(String[] args) { Connection connection = null; try { try { PropertyConfigurator.configure("src/main/java/michael/jdbc/proxool/proxool-demo.properties"); } catch (ProxoolException e) { System.out.println("JAXPConfigurator configure error:" + e.getMessage()); e.printStackTrace(); } try { connection = DriverManager.getConnection("proxool.property-test"); } catch (SQLException e) { System.out.println("Problem getting connection " + e.getMessage()); e.printStackTrace(); } if (connection != null) { System.out.println("Got connection successful : )"); } else { System.out.println("Didn't get connection, which probably means that no Driver accepted the URL"); } } catch (Exception e) { e.printStackTrace(); } finally { try { // Check to see we actually got a connection before we attempt to close it. if (connection != null) { connection.close(); } } catch (SQLException e) { System.out.println("Problem closing connection" + e.getMessage()); e.printStackTrace(); } } } }
运行结果:
Got connection successful : )
ps:代码中DriverManager.getConnection(“proxool.property-test”)的“property-test“需要和配置文件中jdbc-0.proxool.alias=property-test的值一致
[ 3 ]、通过XML配置文件实现
proxool-demo.xml:
<?xml version="1.0" encoding="utf-8"?> <something-else-entirely> <proxool> <alias>xml-test</alias> <driver-url>jdbc:mysql://localhost/michaeldemo</driver-url> <driver-class>com.mysql.jdbc.Driver</driver-class> <driver-properties> <property name="user" value="root" /> <property name="password" value="" /> </driver-properties> <maximum-connection-count>10</maximum-connection-count> <minimum-connection-count>3</minimum-connection-count> <house-keeping-test-sql>select now()</house-keeping-test-sql> </proxool> </something-else-entirely>
TestProxoolCfgXml.java :
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.logicalcobwebs.proxool.ProxoolException; import org.logicalcobwebs.proxool.configuration.PropertyConfigurator; public class TestProxoolCfgPp { public static void main(String[] args) { Connection connection = null; try { try { Class.forName("org.logicalcobwebs.proxool.ProxoolDriver"); } catch (ClassNotFoundException e) { System.out.println("Couldn't find driver" + e.getMessage()); e.printStackTrace(); } try { PropertyConfigurator.configure("src/main/java/michael/jdbc/proxool/proxool-demo.properties"); } catch (ProxoolException e) { System.out.println("JAXPConfigurator configure error:" + e.getMessage()); e.printStackTrace(); } try { connection = DriverManager.getConnection("proxool.property-test"); } catch (SQLException e) { System.out.println("Problem getting connection " + e.getMessage()); e.printStackTrace(); } if (connection != null) { System.out.println("Got connection successful : )"); } else { System.out.println("Didn't get connection, which probably means that no Driver accepted the URL"); } } catch (Exception e) { e.printStackTrace(); } finally { try { // Check to see we actually got a connection before we attempt to close it. if (connection != null) { connection.close(); } } catch (SQLException e) { System.out.println("Problem closing connection" + e.getMessage()); e.printStackTrace(); } } } }
运行结果:
ps:代码中DriverManager.getConnection(“proxool.property-test”)的"property-test"需要和配置文件中jdbc-0.proxool.alias=property-test的值一致
[ 4 ]、通过注册的方式实现
TestProxoolRegister.java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import org.logicalcobwebs.proxool.ProxoolException; import org.logicalcobwebs.proxool.ProxoolFacade; public class TestProxoolRegister { public static void main(String[] args) { Connection connection = null; Properties info = new Properties(); info.setProperty("proxool.maximum-connection-count", "10"); info.setProperty("proxool.minimum-connection-count", "3"); info.setProperty("proxool.house-keeping-test-sql", "select now()"); info.setProperty("user", "root"); info.setProperty("password", ""); String alias = "test"; String driverClass = "com.mysql.jdbc.Driver"; String driverUrl = "jdbc:mysql://localhost/iecms"; String url = "proxool." + alias + ":" + driverClass + ":" + driverUrl; try { try { Class.forName("org.logicalcobwebs.proxool.ProxoolDriver"); } catch (ClassNotFoundException e) { System.out.println("Couldn't find driver" + e.getMessage()); e.printStackTrace(); } try { ProxoolFacade.registerConnectionPool(url, info); } catch (ProxoolException e) { System.out.println("Problem getting connection " + e.getMessage()); e.printStackTrace(); } connection = DriverManager.getConnection("proxool.test"); if (connection != null) { System.out.println("Got connection successful : )"); } else { System.out.println("Didn't get connection, which probably means that no Driver accepted the URL"); } Thread.sleep(10 * 1000L); } catch (Exception e) { System.out.println("error:" + e.getMessage()); e.printStackTrace(); } finally { try { // Check to see we actually got a connection before we attempt // to close it. if (connection != null) { connection.close(); } } catch (SQLException e) { System.out.println("Problem closing connection" + e.getMessage()); e.printStackTrace(); } } } }
运行结果:
三、结合spring的实例演示
配置文件michael/jdbc/proxool/proxool.ds.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/proxool/proxool.jdbc.properties </value> </list> </property> </bean> <bean id="proxoolDataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource" destroy-method="close"> <property name="alias" value="${jdbc.alias}" /> <property name="driver" value="${jdbc.driverClassName}" /> <property name="driverUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="minimumConnectionCount" value="3" /> <property name="maximumConnectionCount" value="10" /> <property name="delegateProperties" value="autoCommit=true, foo=5" /> </bean> </beans>
ProxoolInSpringExample.java:
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.logicalcobwebs.proxool.ProxoolDataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ProxoolInSpringExample { public static void main(String[] args) { System.out.println("c3p0.ds.spring.xml init start "); ApplicationContext appCt = new ClassPathXmlApplicationContext("michael/jdbc/proxool/proxool.ds.spring.xml"); System.out.println("spring bean create proxool.ProxoolDataSource"); ProxoolDataSource dataSource = (ProxoolDataSource) appCt.getBean("proxoolDataSource"); 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) { e.printStackTrace(); } try { if (stmt != null){ stmt.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (conn != null){ conn.close(); } } catch (Exception e) { e.printStackTrace(); } } } }
运行结果:
c3p0.ds.spring.xml init start spring bean create proxool.ProxoolDataSource 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.
转载自micmiu – 软件开发+生活点滴[ http://www.micmiu.com/ ]