常见的数据库连接池有c3p0、dbcp、druid(阿里巴巴开源,结合前面两者优点,加入日志监控,目前最好用的数据库连接池)
自定义数据库连接池
ConnectionPool.java
package test.testCoonPool;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Properties;
public class ConnectionPool {
private static ConnectionPool pool;
private static String driverClass;
private static String url;
private static String username;
private static String password;
//初始连接数
private static int initCount = 5;
//最小连接数
private static int minCount = 5;
//最大连接数
private static int maxCount;
//当前连接数
private static int currentCount;
//使用集合存储连接
LinkedList<Connection> conns = new LinkedList<>();
//成员属性初始化
static {
Properties properties = new Properties();
try {
properties.load(ConnectionPool.class.getClassLoader().getResourceAsStream("db.properties"));
url = properties.getProperty("jdbc.url");
username = properties.getProperty("jdbc.username");
password = properties.getProperty("jdbc.password");
driverClass = properties.getProperty("jdbc.driverClass");
try{
initCount = new Integer(properties.getProperty("jdbc.initCount"));
}catch (NumberFormatException e){
System.out.println("initCount使用默认值");
}
try{
minCount = new Integer(properties.getProperty("jdbc.minCount"));
}catch (NumberFormatException e){
System.out.println("minCount使用默认值");
}
try{
maxCount = new Integer(properties.getProperty("jdbc.maxCount"));
}catch (NumberFormatException e){
System.out.println("maxCount使用默认值");
}
} catch (IOException e) {
e.printStackTrace();
}
}
private ConnectionPool(){}
public static ConnectionPool getPool(){
if(pool==null){
pool = new ConnectionPool();
}
return pool;
}
/**
* 初始化数据库连接池
*/
private void init(){
for (int i = 0; i <initCount ; i++) {
boolean flag = conns.add(createConn());
if(flag){
currentCount++;
}
}
System.out.println("数据库连接池初始化完成");
getCurrentCount();
}
private Connection createConn(){
try{
Class.forName(driverClass);
return DriverManager.getConnection(url,username,password);
}catch (Exception e){
throw new RuntimeException("数据库连接创建失败,"+e.getMessage());
}
}
/**
* 从池中获取一个可用连接
*/
public Connection getConn(){
if(conns.size()>0){
return conns.removeFirst();
}else if(currentCount <maxCount){
autoAdd();
//递归调用返回连接
return getConn();
}else {
//如果池中连接数已经达到上限,就不能扩充连接数了,就等一会(等有空闲连接)再获取
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return getConn();
}
}
/**
* 数据库连接池连接数量自增长2 ,池中没有空闲连接时调用
*/
private void autoAdd(){
if(currentCount == maxCount){
throw new RuntimeException("数据库连接池连接数量已经达到最大值!");
}
for (int i = 0; i <2 ; i++) {
if(currentCount == maxCount){
break;
}
conns.add(createConn());
currentCount++;
}
}
public int getCurrentCount(){
System.out.println("当前数据库连接池数量:"+currentCount);
return currentCount;
}
/**
* 连接池自动缩减
*/
private synchronized void reduce(){
//当连接数量大于最小连接数量,并且池中有空闲连接
if(currentCount > minCount && conns.size()>0){
try{
//从池中获取连接并关闭
Connection con = conns.removeFirst();
con.close();
con = null;
currentCount--;
}catch (SQLException e){
}
}
}
public void returnCon(Connection conn){
conns.add(conn);
reduce();
}
public static void main(String[] args) {
ConnectionPool.getPool().init();
}
}
配置文件db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
jdbc.username=xxx
jdbc.password=xxxxxx
jdbc.initCount=8
jdbc.minCount=8
jdbc.maxCount=20
自定义数据库连接池的使用
JDBCTool.java
package test.testCoonPool;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCTool {
/**
* 从数据库连接池中获取连接
* @return
*/
public static Connection getConn(){
return ConnectionPool.getPool().getConn();
}
public static void closeAll(Statement st, ResultSet rs,Connection conn){
try {
if(st!=null)st.close();
if(rs!=null)rs.close();
if(conn!=null)ConnectionPool.getPool().returnCon(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
druid的使用
- maven项目引入依赖
<!-- 阿里巴巴druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.18</version>
</dependency>
介绍一个概念,数据源对象——jva.sql.DataSource接口对象,表示数据源对象,可以直接理解为数据库连接池,所有的连接池都会有一个数据源实现这个接口。
Druid实现这个数据源的类是:DruidDataSource
druid.properties
jdbcUrl=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username=xxx
password=xxxxxx
initialSize=5
maxActive=15
minIdle=5
maxWait=3000
JDBCTool2
package test.testCoonPool;
import com.alibaba.druid.pool.DruidDataSource;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCTool2 {
private static DataSource dataSource;
static {
//需要加载配置
try {
Properties properties = new Properties();
properties.load(JDBCTool2.class.getClassLoader().getResourceAsStream("druid.properties"));
dataSource = new DruidDataSource();
DruidDataSource druidDataSource = (DruidDataSource)dataSource;
druidDataSource.setUrl(properties.getProperty("jdbcUrl"));
druidDataSource.setUsername(properties.getProperty("username"));
druidDataSource.setPassword(properties.getProperty("password"));
druidDataSource.setInitialSize(new Integer(properties.getProperty("initialSize")));
druidDataSource.setMaxActive(new Integer(properties.getProperty("maxActive")));
druidDataSource.setMaxActive(new Integer(properties.getProperty("maxActive")));
druidDataSource.setMinIdle(new Integer(properties.getProperty("minIdle")));
druidDataSource.setMaxWait(new Long(properties.getProperty("maxWait")));
dataSource = druidDataSource;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("创建druid连接池失败:"+e.getMessage());
}
}
public static Connection getCoon() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("获取连接失败:" + e.getMessage());
}
}
public static void closeAll(Statement st, ResultSet rs, Connection conn){
try {
if(st!=null)st.close();
if(rs!=null)rs.close();
//使用Druid获取的连接直接关闭即可,它会自己还回池中
if(conn!=null)conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
谈谈通过druidDataSource获取的Connection对象为什么用完后可以直接关闭,其实这是一个Connection代理对象,代理对象修改了原生对象的一些方法,特别是close方法。
代理Connection的close方法实际操作是:首先判断池中是否有过多的空闲连接,如果超过了最大空闲连接数,close会直接关闭,并且将这个连接从池中移除。如果池中的空闲连接数并不大于最大空闲连接数量,就不会关闭连接,而是标记为空闲状态。
462




被折叠的 条评论
为什么被折叠?



