阅读更多
dbcp连接池实现commons DBCP 配置参数简要说明
前段时间因为项目原因,要在修改数据库连接池到DBCP上,折腾了半天,有一点收获,不敢藏私,特在这里与朋友们共享。
在配置时,主要难以理解的主要有:removeAbandoned 、logAbandoned、removeAbandonedTimeout、maxWait这四个参数,设置了rmoveAbandoned=true那么在getNumActive()快要到getMaxActive()的时候,系统会进行无效的Connection的回收,回收的Connection为removeAbandonedTimeout(默认300秒)中设置的秒数后没有使用的Connection,激活回收机制好像是getNumActive()=getMaxActive()-2。
有点忘了。
logAbandoned=true的话,将会在回收事件后,在log中打印出回收Connection的错误信息,包括在哪个地方用了Connection却忘记关闭了,在调试的时候很有用。
在这里私人建议maxWait的时间不要设得太长,maxWait如果设置太长那么客户端会等待很久才激发回收事件。
以下是我的配置的properties文件:
#连接设置
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:DBSERVER
jdbc.username=user
jdbc.password=pass
#
dataSource.initialSize=10
#
dataSource.maxIdle=20
#
dataSource.minIdle=5
#最大连接数量
dataSource.maxActive=50
#是否在自动回收超时连接的时候打印连接的超时错误
dataSource.logAbandoned=true
#是否自动回收超时连接
dataSource.removeAbandoned=true
#超时时间(以秒数为单位)
dataSource.removeAbandonedTimeout=180
#
dataSource.maxWait=1000
以下是我在连接控制中调用的方法:
Properties dbProps=null;
//下面的读取配置文件可以根据实际的不同修改
dbProps = ConfigProperties.getInstance().getProperties("jdbc.properties");
try {
String driveClassName = dbProps.getProperty("jdbc.driverClassName");
String url = dbProps.getProperty("jdbc.url");
String username = dbProps.getProperty("jdbc.username");
String password = dbProps.getProperty("jdbc.password");
String initialSize = dbProps.getProperty("dataSource.initialSize");
String minIdle = dbProps.getProperty("dataSource.minIdle");
String maxIdle = dbProps.getProperty("dataSource.maxIdle");
String maxWait = dbProps.getProperty("dataSource.maxWait");
String maxActive = dbProps.getProperty("dataSource.maxActive");
//是否在自动回收超时连接的时候打印连接的超时错误
boolean logAbandoned = (Boolean.valueOf(dbProps.getProperty("dataSource.logAbandoned","false"))).booleanValue();
//是否自动回收超时连接
boolean removeAbandoned = (Boolean.valueOf(dbProps.getProperty("dataSource.removeAbandoned","false"))).booleanValue();
//超时时间(以秒数为单位)
int removeAbandonedTimeout = Integer.parseInt(dbProps.getProperty("dataSource.removeAbandonedTimeout","300"));
dataSource = new BasicDataSource();
dataSource.setDriverClassName(driveClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
//初始化连接数
if(initialSize!=null)
dataSource.setInitialSize(Integer.parseInt(initialSize));
//最小空闲连接
if(minIdle!=null)
dataSource.setMinIdle(Integer.parseInt(minIdle));
//最大空闲连接
if(maxIdle!=null)
dataSource.setMaxIdle(Integer.parseInt(maxIdle));
//超时回收时间(以毫秒为单位)
if(maxWait!=null)
dataSource.setMaxWait(Long.parseLong(maxWait));
//最大连接数
if(maxActive!=null){
if(!maxActive.trim().equals("0"))
dataSource.setMaxActive(Integer.parseInt(maxActive));
}
System.out.println("logAbandoned="+logAbandoned);
dataSource.setLogAbandoned(logAbandoned);
dataSource.setRemoveAbandoned(removeAbandoned);
dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
Connection conn = dataSource.getConnection();
if(conn==null){
log("创建连接池时,无法取得连接!检查设置!!!");
}else{
conn.close();
}
System.out.println("连接池创建成功!!!");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("创建连接池失败!请检查设置!!!");
}
有使用问题或建议可与我联系:
2006-04-20 By: 小土
用apache的dbcp来建立独立的数据库连接池(db connection pool)
数据库连接池的好处是不言而喻的,现在大部分的application server都提供自己的数据库连接池方案,此时,只要按照application server的文档说明,正确配置,即可在应用中享受到数据库连接池的好处。
但是,有些时候,我们的应用是个独立的java application,并不是普通的WEB/J2EE应用,而且是单独运行的,不要什么application server的配合,这种情况下,我们就需要建立自己的数据库连接池方案了。这里,介绍如何利用apache的dbcp来建立为民自己的数据库连接池。
1。首先,下载必须的jar包
dbcp包,目前版本是1.2.1:http://jakarta.apache.org/commons/dbcp/
pool包,目前版本是1.3:http://jakarta.apache.org/commons/pool/,
如果下载的pool包是1.2的版本,还要下载common-collections包:http://jakarta.apache.org/commons/collections/
在建立我们自己的数据库连接池时,可以使用xml文件来传入需要的参数,这里只使用hard code的方式来简单介绍,所有需要我们自己写的代码很少,只要建立一个文件如下:
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import java.sql.SQLException;
import java.sql.Connection;
import java.util.Properties;
public class ConnectionSource {
private static BasicDataSource dataSource = null;
public ConnectionSource() {
}
public static void init() {
if (dataSource != null) {
try {
dataSource.close();
} catch (Exception e) {
//
}
dataSource = null;
}
try {
Properties p = new Properties();
p.setProperty("driverClassName", "oracle.jdbc.driver.OracleDriver");
p.setProperty("url", "jdbc:oracle:thin:@192.168.0.1:1521:testDB");
p.setProperty("password", "scott");
p.setProperty("username", "tiger");
p.setProperty("maxActive", "30");
p.setProperty("maxIdle", "10");
p.setProperty("maxWait", "1000");
p.setProperty("removeAbandoned", "false");
p.setProperty("removeAbandonedTimeout", "120");
p.setProperty("testOnBorrow", "true");
p.setProperty("logAbandoned", "true");
dataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(p);
} catch (Exception e) {
//
}
}
public static synchronized Connection getConnection() throws SQLException {
if (dataSource == null) {
init();
}
Connection conn = null;
if (dataSource != null) {
conn = dataSource.getConnection();
}
return conn;
}
}
接下来,在我们的应用中,只要简单地使用ConnectionSource.getConnection()就可以取得连接池中的数据库连接,享受数据库连接带给我们的好处了。当我们使用完取得的数据库连接后,只要简单地使用connection.close()就可把此连接返回到连接池中,至于为什么不是直接关闭此连接,而是返回给连接池,这是因为dbcp使用委派模型来实现Connection接口了。
在使用Properties来创建BasicDataSource时,有很多参数可以设置,比较重要的还有:
testOnBorrow、testOnReturn、testWhileIdle,他们的意思是当是取得连接、返回连接或连接空闲时是否进行有效性验证(即是否还和数据库连通的),默认都为false。所以当数据库连接因为某种原因断掉后,再从连接池中取得的连接,实际上可能是无效的连接了,所以,为了确保取得的连接是有效的, 可以把把这些属性设为true。当进行校验时,需要另一个参数:validationQuery,对oracle来说,可以是:SELECT COUNT(*) FROM DUAL,实际上就是个简单的SQL语句,验证时,就是把这个SQL语句在数据库上跑一下而已,如果连接正常的,当然就有结果返回了。
还有2个参数:timeBetweenEvictionRunsMillis 和 minEvictableIdleTimeMillis, 他们两个配合,可以持续更新连接池中的连接对象,当timeBetweenEvictionRunsMillis 大于0时,每过timeBetweenEvictionRunsMillis 时间,就会启动一个线程,校验连接池中闲置时间超过minEvictableIdleTimeMillis的连接对象。
还有其他的一些参数,可以参考源代码。
出处:http://blog.csdn.net/zllsdn/archive/2006/11/20/1398577.aspx
官方网站的例子:
/* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 import javax.sql.DataSource; 19 import java.sql.Connection; 20 import java.sql.Statement; 21 import java.sql.ResultSet; 22 import java.sql.SQLException; 23 24 // 25 // Here are the dbcp-specific classes. 26 // Note that they are only used in the setupDataSource 27 // method. In normal use, your classes interact 28 // only with the standard JDBC API 29 // 30 import org.apache.commons.dbcp.BasicDataSource; 31 32 // 33 // Here's a simple example of how to use the BasicDataSource. 34 // In this example, we'll construct the BasicDataSource manually, 35 // but you could also configure it using an external conifguration file. 36 // 37 38 // 39 // Note that this example is very similiar to the PoolingDriver 40 // example. 41 42 // 43 // To compile this example, you'll want: 44 // * commons-pool-1.5.4.jar 45 // * commons-dbcp-1.2.2.jar 46 // * j2ee.jar (for the javax.sql classes) 47 // in your classpath. 48 // 49 // To run this example, you'll want: 50 // * commons-pool-1.5.4.jar 51 // * commons-dbcp-1.2.2.jar 52 // * j2ee.jar (for the javax.sql classes) 53 // * the classes for your (underlying) JDBC driver 54 // in your classpath. 55 // 56 // Invoke the class using two arguments: 57 // * the connect string for your underlying JDBC driver 58 // * the query you'd like to execute 59 // You'll also want to ensure your underlying JDBC driver 60 // is registered. You can use the "jdbc.drivers" 61 // property to do this. 62 // 63 // For example: 64 // java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver \ 65 // -classpath commons-pool-1.5.3.jar:commons-dbcp-1.2.2.jar:j2ee.jar:oracle-jdbc.jar:. \ 66 // ManualPoolingDataSourceExample 67 // "jdbc:oracle:thin:scott/tiger@myhost:1521:mysid" 68 // "SELECT * FROM DUAL" 69 // 70 public class BasicDataSourceExample { 71 72 public static void main(String[] args) { 73 // First we set up the BasicDataSource. 74 // Normally this would be handled auto-magically by 75 // an external configuration, but in this example we'll 76 // do it manually. 77 // 78 System.out.println("Setting up data source."); 79 DataSource dataSource = setupDataSource(args[0]); 80 System.out.println("Done."); 81 82 // 83 // Now, we can use JDBC DataSource as we normally would. 84 // 85 Connection conn = null; 86 Statement stmt = null; 87 ResultSet rset = null; 88 89 try { 90 System.out.println("Creating connection."); 91 conn = dataSource.getConnection(); 92 System.out.println("Creating statement."); 93 stmt = conn.createStatement(); 94 System.out.println("Executing statement."); 95 rset = stmt.executeQuery(args[1]); 96 System.out.println("Results:"); 97 int numcols = rset.getMetaData().getColumnCount(); 98 while(rset.next()) { 99 for(int i=1;i<=numcols;i++) { 100 System.out.print("\t" + rset.getString(i)); 101 } 102 System.out.println(""); 103 } 104 } catch(SQLException e) { 105 e.printStackTrace(); 106 } finally { 107 try { rset.close(); } catch(Exception e) { } 108 try { stmt.close(); } catch(Exception e) { } 109 try { conn.close(); } catch(Exception e) { } 110 } 111 } 112 113 public static DataSource setupDataSource(String connectURI) { 114 BasicDataSource ds = new BasicDataSource(); 115 ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); 116 ds.setUsername("scott"); 117 ds.setPassword("tiger"); 118 ds.setUrl(connectURI); 119 return ds; 120 } 121 122 public static void printDataSourceStats(DataSource ds) { 123 BasicDataSource bds = (BasicDataSource) ds; 124 System.out.println("NumActive: " + bds.getNumActive()); 125 System.out.println("NumIdle: " + bds.getNumIdle()); 126 } 127 128 public static void shutdownDataSource(DataSource ds) throws SQLException { 129 BasicDataSource bds = (BasicDataSource) ds; 130 bds.close(); 131 } 132 }
来源:http://svn.apache.org/viewvc/commons/proper/dbcp/trunk/doc/BasicDataSourceExample.java?revision=884350&view=markup
来源:http://hi.baidu.com/iloverobot/item/e71038a6e9cf50268819d36e