pom.xml添加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.13</version>
</dependency>
dbconfig.properties,连接池配置信息
#我用的是mysql数据库
url=jdbc:mysql://127.0.0.1:3306/poreader
username=root
password=123123
filters=stat
#最大连接数量
maxActive=20
#初始化连接数量
initialSize=1
#超时等待时间以毫秒为单位
maxWait=60000
#最小空闲连接
minIdle=1
#校验连接池中限制时间超过minEvictableIdleTimeMillis的连接对象
timeBetweenEvictionRunsMillis=3000
#连接在池中保持空闲而不被空闲连接回收器线程(如果有)回收的最小时间值,单位毫秒
minEvictableIdleTimeMillis=300000
#SQL查询,用来验证从连接池取出的连接,在将连接返回给调用者之前
validationQuery=SELECT now();
#指明连接是否被空闲连接回收器(如果有)进行检验.
#如果检测失败,则连接将被从池中去除.
testWhileIdle=true
#指明是否在从池中取出连接前进行检验,如果检验失败,
#则从池中去除连接并尝试取出另一个.
testOnBorrow=false
#指明是否在归还到池中前进行检验
testOnReturn=false
#poolPreparedStatements=true
maxPoolPreparedStatementPerConnectionSize=20
DBConfig.java,读取连接池的配置文件信息。
package com.poreader.dao.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class DBConfig {
public static Properties getProperties(){
String path = Class.class.getClass().getResource("/").getPath() +
"dbconfig.properties";
System.out.println("Begin load database dbconfig.properties");
try {
System.out.println(path);
FileInputStream fileInputStream = new FileInputStream(path);
Properties p = new Properties();
p.load(fileInputStream);
System.out.println("Done!");
return p;
} catch (FileNotFoundException e) {
System.err.println("该 \"" + path + " \" 路径下的文件没有找到!");
e.printStackTrace();
} catch (IOException e) {
System.err.println("该 \"" + path + " \" 路径中的文件读取失败!");
e.printStackTrace();
}
return null;
}
}
Conn.java提供获取sqlConnection方法
package com.poreader.dao.util;
import java.sql.Connection;
import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
public class Conn {
private static final Logger logger = LoggerFactory.getLogger(Conn.class);
private static DruidDataSource druidDataSource = null;
public static DruidDataSource getDruidDataSource() {
if (druidDataSource == null) {
try {
druidDataSource = (DruidDataSource) DruidDataSourceFactory
.createDataSource(DBConfig.getProperties());
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
return druidDataSource;
}
public static Connection getConnection() {
try {
return getDruidDataSource().getConnection();
} catch (SQLException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
return null;
}
}