连接池是一个对数据库连接进行管理的东西,当一个线程需要用 JDBC 对 数据库操作时,它从池中请求一个连接。当这个线程使用完了这个连接,将它返回到连接池中,这样这就可以被其它想使用它的线程使用,而不是每次都重新建立一个数据库连接。
1.下载好Druid的jar包,并在项目中引入
2.在项目resource文件夹下面新建文件db_server.properties(druid配置文件),复制如下内容:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8
username=root
password=123456
filters=stat
initialSize=2
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200
3.写连接池管理工具类DBPoolConnection.java(配置文件db_server.properties所在路径自己根据实际情况填写)
package com.cqgs.kit;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
/**
* 要实现单例模式,保证全局只有一个数据库连接池
*/
public class DBPoolConnection {
static Logger log = Logger.getLogger(DBPoolConnection.class);
private static DBPoolConnection dbPoolConnection = null;
private static DruidDataSource druidDataSource = null;
static {
Properties properties = loadPropertiesFile("resource/db_server.properties");
try {
druidDataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties); //DruidDataSrouce工厂模式
} catch (Exception e) {
log.error("获取配置失败");
}
}
/**
* 数据库连接池单例
* @return
*/
public static synchronized DBPoolConnection getInstance(){
if (null == dbPoolConnection){
dbPoolConnection = new DBPoolConnection();
}
return dbPoolConnection;
}
/**
* 返回druid数据库连接
* @return
* @throws SQLException
*/
public DruidPooledConnection getConnection() throws SQLException{
return druidDataSource.getConnection();
}
/**
* @param string 配置文件名
* @return Properties对象
*/
private static Properties loadPropertiesFile(String fullFile) {
String webRootPath = null;
if (null == fullFile || fullFile.equals("")){
throw new IllegalArgumentException("Properties file path can not be null" + fullFile);
}
webRootPath = DBPoolConnection.class.getClassLoader().getResource("").getPath();
webRootPath = new File(webRootPath).getParent();
InputStream inputStream = null;
Properties p =null;
try {
inputStream = new FileInputStream(new File(webRootPath + File.separator + fullFile));
p = new Properties();
p.load(inputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != inputStream){
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return p;
}
}
4.如何使用连接池获得连接,回收连接
最后记得把连接放回连接池