您的位置:首页 > 其它

c3p0连接池使用

2015-08-13 11:28 393 查看

      在实际开发中,使用JDBC连接数据库的情况时有出现,在多层结构的应用中,使用DriverManager获取连接时,一个需要连接的操作对应一个数据库物理连接,每一次操作都会重新打开一个连接,在使用完毕后立即关闭。而频繁打开、关闭连接会造成系统及其不稳定,并发操作时经常会出现连接不足甚至是根本无法获取连接的情况。

      c3p0连接池很好地解决了这个问题,解决思路是:在应用程序启动时,即建立足够的数据库连接用于待命,并将这些连接存放在池中等待使用。每次其它服务请求数据库连接时,不需要重新打开数据库连接,而是从池中取出已有的连接,使用完毕后,这个连接也不会被关闭,而是重新放入连接池。JDBC2.0引入了数据库连接池技术以解决共享连接问题,使用java.sql.DataSource接口实现,而c3p0是一个开源的实现,商用服务器也提供连接池实现(如WebLogic、WebSphere)。

      本文使用一个工具类来读取配置文件,具体代码如下:

package com.any.util;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;

/**
* @ClassName: ConfigUtil
* @author Helen
* @date 2015年8月13日 上午10:46:39
*/

public class ConfigUtil {
private String resourcePath = "com.any.config";
private ResourceBundle bundle;
private ArrayList<String> keyList;

private ConfigUtil(){
loadFile();
}
public static ConfigUtil getInstanceConfig(){
return new ConfigUtil();
}
protected void loadFile(){
bundle = ResourceBundle.getBundle(resourcePath, Locale.CHINA);
if(bundle!=null){
Enumeration<String> eumObj = bundle.getKeys();
keyList = new ArrayList<String>();
while (eumObj.hasMoreElements()) {
keyList.add(eumObj.nextElement());
}
} else {
System.out.println("Config file not exists!");
System.exit(2);
}
}
private boolean isKeyExists(String key){
return keyList.contains(key);
}
public String getString(String key){
if(isKeyExists(key)){
return bundle.getString(key);
}
return null;
}
public int getInt(String key){
if(isKeyExists(key)){
return Integer.valueOf(bundle.getString(key));
}
return 0;
}
}

     该工具类仅用于从properties文件中读取数据,该文件中通常会存放应用系统的常用配置参数:如数据库信息、资源路径信息、国际化资源等。使用C3P0获取连接池的关键代码如下:

package com.any.util;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
* @ClassName: DBPool
* @author Helen
* @date 2015年8月13日 上午10:19:44
*/

public class DBPool {
public static Connection getConnection(){
ComboPooledDataSource ds = new ComboPooledDataSource();
ConfigUtil config = ConfigUtil.getInstanceConfig();
try {
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl(config.getString("url"));
ds.setUser(config.getString("user"));
ds.setPassword(config.getString("password"));
ds.setMaxPoolSize(60);
ds.setMinPoolSize(3);
ds.setInitialPoolSize(10);
ds.setMaxStatements(200);
return ds.getConnection();
} catch (PropertyVetoException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}

      注意,需要引入C3P0对应版本的jar包,通过设置最大连接数、最小连接数等,即可创建一个连接池,C3P0还能很好地管理连接池,也能自动清理不再使用的Statement和ResultSet。

      使用以下代码测试:

package com.any;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.any.util.DBPool;

/**
* @ClassName: TestPool
* @Description: (这里用一句话描述这个类的作用)
* @author Helen
* @date 2015年8月13日 上午10:30:43
*/

public class TestPool {
public static void main(String[] args) {
Connection conn = DBPool.getConnection();
try {
PreparedStatement psmt=conn.prepareStatement("select * from emp");
ResultSet rs = psmt.executeQuery();
while(rs.next()){
System.out.println("result:"+rs.getString("ename"));
}
} catch (SQLException e) {
e.printStackTrace();
}

}
}

     由于引入了日志组件,因此运行时可以看到控制台打印出的如下日志信息:

八月 13, 2015 11:05:48 上午 com.mchange.v2.log.MLog <clinit>
INFO: MLog clients using java 1.4+ standard logging.
八月 13, 2015 11:05:48 上午 com.mchange.v2.c3p0.C3P0Registry banner
INFO: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
八月 13, 2015 11:05:48 上午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
INFO: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge48x9ba9sf7i1qnzmj8|4544c134, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge48x9ba9sf7i1qnzmj8|4544c134, idleConnectionTestPeriod -> 0, initialPoolSize -> 10, jdbcUrl -> jdbc:mysql://127.0.0.1:3306/test, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 60, maxStatements -> 200, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
result:abc

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: