Java使用commons-dbcp2.0



Java使用commons-dbcp2.0

dbcp 是 apache 上的一个 java 连接池项目,也是 tomcat 使用的连接池组件。单独使用dbcp需要3个包:common-dbcp.jar,common-pool.jar,common-collections.jar。

1.关于commons-pool及commons-dbcp版本区别
之前项目一直用的是commons-dbcp1.4,因为项目中原来用的是jedis-2.1.0.jar,升级到jedis-2.5.1.jar之后,jedis内部所用的池依赖由原来的commons-pool-1.6.jar改为了commons-pool2-2.2.jar,其中原有的一些参数都改名或删掉了。由于jedis和commons-dbcp内部都是用的commons-pool中的池,所以参数可以也需要按照commons-pool的实现类来进行配置。
commons-pool1.6和commons-pool2.2分属commons-pool中两个不同的大版本,按照commons-pool官网上的介绍,Apache Commons Pool 2.2 (Java 6.0+),Apache Commons Pool 1.6 (Java 5.0+),即不同版本要求的JDK最低版本不同。

而commons-dbcp现在分成了3个大版本,不同的版本要求的JDK不同:
DBCP now comes in three different versions to support different versions of JDBC. Here is how it works:
DBCP 2 compiles and runs under Java 7 only (JDBC 4.1)
DBCP 1.4 compiles and runs under Java 6 only (JDBC 4)
DBCP 1.3 compiles and runs under Java 1.4-5 only (JDBC 3)

2.关于commons-dbcp2参数配置
由于commons-dbcp所用的连接池出现版本升级,因此commons-dbcp2中的数据库池连接配置也发生了变化,具体的参数配置说明如下:
Parameter Description
username The connection username to be passed to our JDBC driver to establish a connection.
password The connection password to be passed to our JDBC driver to establish a connection.
url The connection URL to be passed to our JDBC driver to establish a connection.
driverClassName The fully qualified Java class name of the JDBC driver to be used.
connectionProperties The connection properties that will be sent to our JDBC driver when establishing new connections.
Format of the string must be [propertyName=property;]*
NOTE – The “user” and “password” properties will be passed explicitly, so they do not need to be included here.
Parameter Default Description
defaultAutoCommit driver default The default auto-commit state of connections created by this pool. If not set then the setAutoCommit method will not be called.
defaultReadOnly driver default The default read-only state of connections created by this pool. If not set then the setReadOnly method will not be called. (Some drivers don’t support read only mode, ex: Informix)
defaultTransactionIsolation driver default The default TransactionIsolation state of connections created by this pool. One of the following: (see javadoc)
NONE
READ_COMMITTED
READ_UNCOMMITTED
REPEATABLE_READ
SERIALIZABLE
defaultCatalog The default catalog of connections created by this pool.
cacheState true If true, the pooled connection will cache the current readOnly and autoCommit settings when first read or written and on all subsequent writes. This removes the need for additional database queries for any further calls to the getter. If the underlying connection is accessed directly and the readOnly and/or autoCommit settings changed the cached values will not reflect the current state. In this case, caching should be disabled by setting this attribute to false.
[java] view plaincopy在CODE上查看代码片派生到我的代码片
package dbcp;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;

/**
* @author
* @date
*
* dbcp 实用类,提供了dbcp连接,不允许继承;
*
* 该类需要有个地方来初始化 DS ,通过调用initDS 方法来完成, 可以在通过调用带参数的构造函数完成调用,
* 可以在其它类中调用,也可以在本类中加一个static{}来完成;
*/
public final class DbcpBean {
/** 数据源,static */
private static DataSource DS;

/** 从数据源获得一个连接 */
public Connection getConn() {
Connection con = null;
if (DS != null) {
try {
con = DS.getConnection();
} catch (Exception e) {
e.printStackTrace(System.err);
}

try {
con.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
return con;
}


/** 默认的构造函数 */
public DbcpBean() {
}

/** 构造函数,初始化了 DS ,指定 数据库 */
public DbcpBean(String connectURI) {
initDS(connectURI);
}

/** 构造函数,初始化了 DS ,指定 所有参数 */
public DbcpBean(String connectURI, String username, String pswd,
String driverClass, int initialSize, int maxActive, int maxIdle,
int maxWait, int minIdle) {
initDS(connectURI, username, pswd, driverClass, initialSize, maxActive,
maxIdle, maxWait, minIdle);
}

/**
* 创建数据源,除了数据库外,都使用硬编码默认参数;
*
* @param connectURI
* 数据库
* @return
*/
public static void initDS(String connectURI) {
initDS(connectURI, “root”, “password”, “com.mysql.jdbc.Driver”, 5, 100,
30, 10000, 1);
}

/**
* 指定所有参数连接数据源
*
* @param connectURI
* 数据库
* @param username
* 用户名
* @param pswd
* 密码
* @param driverClass
* 数据库连接驱动名
* @param initialSize
* 初始连接池连接个数
* @param maxtotal
* 最大活动连接数
* @param maxIdle
* 最大连接数
* @param maxWaitMillis
* 获得连接的最大等待毫秒数
* @param minIdle
* 最小连接数
* @return
*/
public static void initDS(String connectURI, String username, String pswd,
String driverClass, int initialSize, int maxtotal, int maxIdle,
int maxWaitMillis , int minIdle) {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(driverClass);
ds.setUsername(username);
ds.setPassword(pswd);
ds.setUrl(connectURI);
ds.setInitialSize(initialSize); // 初始的连接数;
ds.setMaxTotal(maxtotal);
ds.setMaxIdle(maxIdle);
ds.setMaxWaitMillis(maxWaitMillis);
ds.setMinIdle(minIdle);
DS = ds;
}

/** 获得数据源连接状态 */
public static Map<String, Integer> getDataSourceStats() throws SQLException {
BasicDataSource bds = (BasicDataSource) DS;
Map<String, Integer> map = new HashMap<String, Integer>(2);
map.put(“active_number”, bds.getNumActive());
map.put(“idle_number”, bds.getNumIdle());
return map;
}

/** 关闭数据源 */
protected static void shutdownDataSource() throws SQLException {
BasicDataSource bds = (BasicDataSource) DS;
bds.close();
}

public static void main(String[] args) {
DbcpBean db = new DbcpBean(“jdbc:mysql://localhost:3306/testit”);
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = db.getConn();
stmt = conn.createStatement();
rs = stmt.executeQuery(“select * from test limit 1 “);
System.out.println(“Results:”);
int numcols = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 1; i <= numcols; i++) {
System.out.print(“\t” + rs.getString(i) + “\t”);
}
System.out.println(“”);
}
System.out.println(getDataSourceStats());
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
if (db != null)
shutdownDataSource();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}