万字详解数据库连接池

数据库连接池的概念
  • 数据库连接是一种关键的、有限的、昂贵的资源,这一点在多用户的网页应用程序中体现得尤为突出。对数据库连接的管理能显著影响到整个应用程序的伸缩性和健壮性,影响到程序的性能指标。数据库连接池正是针对这个问题提出来的。
  • 数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个。这项技术能明显提高对数据库操作的性能。
自定义连接池
  • java.sql.DataSource接口:数据源(数据库连接池)。java官方提供的数据库连接池规范(接口)
    • 获取数据库连接对象:Connection getConnection();

工具类:

package com.dataSource;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class JDBCUtils {
    /**
     * 1.私有构造方法
     */
    private JDBCUtils() {
    }

    // 2.声明配置信息变量
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
    private static Connection con;

    // 3.静态代码块中实现加载配置文件和注册驱动
    static {
        try {
            // 通过类加载器返回配置文件的字节流
            // getClassLoader().getResourceAsStream:通过给定名称查找资源,查询资源的规则由给定的类的class load来实现,这个方法由类的loader来执行;如果这个类由bootstrap加载,那么方法由ClassLoader.getSystemResourceAsStream代理执行。
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties");

            // 创建Properties集合,加载流对象的信息
            Properties prop = new Properties();
            prop.load(is);

            // 获取信息为变量赋值
            driverClass = prop.getProperty("driverClass");
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");

            // 注册驱动
            Class.forName(driverClass);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //4.获取数据库连接的方法
    public static Connection getConnection() {
        try {
            con = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return con;
    }

    //5.释放资源的方法
    public static void close(Connection con, Statement stat, ResultSet rs) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection con, Statement stat) {
        close(con, stat, null);
    }
}

自定义连接池:

package com.dataSource;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

public class MyDataSource implements DataSource {
    // 定义集合容器,用于保存多个数据库连接对象

    private static final List<Connection> POOP = Collections.synchronizedList(new ArrayList<>());


    // 静态代码块,生成10个数据库连接保存到集合中
    static {
        for (int i = 0; i < 10; i++) {
            Connection coon = JDBCUtils.getConnection();
            POOP.add(coon);
        }
    }

    @Override
    public Connection getConnection() throws SQLException {
        if (POOP.size() > 0) {
            Connection remove = POOP.remove(0);
            return remove;
        } else {
            throw new RuntimeException("连接数量耗尽");
        }
    }

    /**定义getSize方法,获取连接池容器的大小*/
    public int getSize() {
        return POOP.size();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }


    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }
}

测试类:

package com.dataSource;

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

public class DataSourceTest {
    public static void main(String[] args) throws SQLException {
        // 创建连接池对象
        MyDataSource dataSource = new MyDataSource();
        System.out.println("使用之前连接池数量:" + dataSource.getSize());
        // 通过连接池对象获取连接对象
        Connection conn = dataSource.getConnection();
        // 查看DriverManager连接的实现类,发现是JDBC4Connection
        System.out.println(conn.getClass());
        // 查询学生表的全部信息
        String sql = "SELECT * FROM student";
        PreparedStatement ps = conn.prepareStatement(sql);

        // 执行sql语句,接收结果集
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getInt("sid") + "\t" + rs.getString("name") + "\t" + rs.getInt("age") + "\t" + rs.getDate("birthday"));
        }

        // 释放资源
        conn.close();
        ps.close();
        rs.close();
        System.out.println("使用之后连接池数量:" + dataSource.getSize());
    }
}

上面的代码是有问题的,因为最后释放了资源以后,通过查看使用后的连接池的数量发现没有归还操作,那连接池存在就没有意义了,连接池存在就是为了重复使用的。

连接池归还连接:
归还连接_继承:

通过打印连接对象,发现DriverManager获取的连接实现类是JDBC4Connection。

自定义一个类,继承JDBC4Connection这个类,定义连接对象和连接池容器对象的成员变量,通过有参构造对成员变量赋值,重写close()方法,将连接对象添加到池中
定义了子类完成了归还,但是DriverManager获取的还是JDBC4Connection这个对象,不是定义的子类,所以继承搞不了

归还连接_装饰设计模式:

自定义一个类,实现Connection接口,这样就和JDBC4Connection有相同的方法,重写close方法,剩余方法,只需要调用mysql驱动包的连接对象完成即可,但是这个设计模式需要重写很多的方法,比较麻烦

自定义类连接池:

package com.dataSource;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;


public class MyDataSource implements DataSource {
    // 定义集合容器,用于保存多个数据库连接对象

    private static final List<Connection> pool = Collections.synchronizedList(new ArrayList<>());


    // 静态代码块,生成10个数据库连接保存到集合中
    static {
        for (int i = 0; i < 10; i++) {
            Connection coon = JDBCUtils.getConnection();
            pool.add(coon);
        }
    }

    // 从连接池返回一个数据库连接
    @Override
    public Connection getConnection() {
        if (pool.size() > 0) {
            // 从池中获取数据库连接
            Connection con = pool.remove(0);
            // 通过自定义连接对象进行包装
            MyConnection mycon = new MyConnection(con, pool);
            // 返回包装后的连接对象
        return mycon;
        } else {
            throw new RuntimeException("连接数量耗尽");
        }
    }

    /**定义getSize方法,获取连接池容器的大小*/
    public int getSize() {
        return pool.size();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }


    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }
}

自定义连接类:

package com.dataSource;

import java.sql.*;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

/*
    自定义Connection类。通过装饰设计模式,实现和mysql驱动包中的Connection实现类相同的功能!
    实现步骤:
        1.定义一个类,实现Connection接口
        2.定义Connection连接对象和连接池容器对象的变量
        3.提供有参构造方法,接收连接对象和连接池对象,对变量赋值
        4.在close()方法中,完成连接的归还
        5.剩余方法,还是只需要调用mysql驱动包的连接对象完成即可
 */

public class MyConnection implements Connection {
    private Connection con;
    private List<Connection> pool;

    public MyConnection(Connection con, List<Connection> pool) {
        this.con = con;
        this.pool = pool;
    }

    @Override
    public void close() throws SQLException {
        pool.add(con);
    }

    @Override
    public Statement createStatement() throws SQLException {
        return con.createStatement();
    }

    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return con.prepareStatement(sql);
    }

    @Override
    public CallableStatement prepareCall(String sql) throws SQLException {
        return con.prepareCall(sql);
    }

    @Override
    public String nativeSQL(String sql) throws SQLException {
        return con.nativeSQL(sql);
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        con.setAutoCommit(autoCommit);
    }

    @Override
    public boolean getAutoCommit() throws SQLException {
        return con.getAutoCommit();
    }

    @Override
    public void commit() throws SQLException {
        con.commit();
    }

    @Override
    public void rollback() throws SQLException {
        con.rollback();
    }

    @Override
    public boolean isClosed() throws SQLException {
        return con.isClosed();
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return con.getMetaData();
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException {
        con.setReadOnly(readOnly);
    }

    @Override
    public boolean isReadOnly() throws SQLException {
        return con.isReadOnly();
    }

    @Override
    public void setCatalog(String catalog) throws SQLException {
        con.setCatalog(catalog);
    }

    @Override
    public String getCatalog() throws SQLException {
        return con.getCatalog();
    }

    @Override
    public void setTransactionIsolation(int level) throws SQLException {
        con.setTransactionIsolation(level);
    }

    @Override
    public int getTransactionIsolation() throws SQLException {
        return con.getTransactionIsolation();
    }

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return con.getWarnings();
    }

    @Override
    public void clearWarnings() throws SQLException {
        con.clearWarnings();
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
        return con.createStatement(resultSetType,resultSetConcurrency);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return con.prepareStatement(sql,resultSetType,resultSetConcurrency);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return con.prepareCall(sql,resultSetType,resultSetConcurrency);
    }

    @Override
    public Map<String, Class<?>> getTypeMap() throws SQLException {
        return con.getTypeMap();
    }

    @Override
    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
        con.setTypeMap(map);
    }

    @Override
    public void setHoldability(int holdability) throws SQLException {
        con.setHoldability(holdability);
    }

    @Override
    public int getHoldability() throws SQLException {
        return con.getHoldability();
    }

    @Override
    public Savepoint setSavepoint() throws SQLException {
        return con.setSavepoint();
    }

    @Override
    public Savepoint setSavepoint(String name) throws SQLException {
        return con.setSavepoint(name);
    }

    @Override
    public void rollback(Savepoint savepoint) throws SQLException {
        con.rollback(savepoint);
    }

    @Override
    public void releaseSavepoint(Savepoint savepoint) throws SQLException {
        con.releaseSavepoint(savepoint);
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return con.createStatement(resultSetType,resultSetConcurrency,resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return con.prepareStatement(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return con.prepareCall(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        return con.prepareStatement(sql,autoGeneratedKeys);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        return con.prepareStatement(sql,columnIndexes);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
        return con.prepareStatement(sql,columnNames);
    }

    @Override
    public Clob createClob() throws SQLException {
        return con.createClob();
    }

    @Override
    public Blob createBlob() throws SQLException {
        return con.createBlob();
    }

    @Override
    public NClob createNClob() throws SQLException {
        return con.createNClob();
    }

    @Override
    public SQLXML createSQLXML() throws SQLException {
        return con.createSQLXML();
    }

    @Override
    public boolean isValid(int timeout) throws SQLException {
        return con.isValid(timeout);
    }

    @Override
    public void setClientInfo(String name, String value) throws SQLClientInfoException {
        con.setClientInfo(name,value);
    }

    @Override
    public void setClientInfo(Properties properties) throws SQLClientInfoException {
        con.setClientInfo(properties);
    }

    @Override
    public String getClientInfo(String name) throws SQLException {
        return con.getClientInfo(name);
    }

    @Override
    public Properties getClientInfo() throws SQLException {
        return con.getClientInfo();
    }

    @Override
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
        return con.createArrayOf(typeName,elements);
    }

    @Override
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
        return con.createStruct(typeName,attributes);
    }

    @Override
    public void setSchema(String schema) throws SQLException {
        con.setSchema(schema);
    }

    @Override
    public String getSchema() throws SQLException {
        return con.getSchema();
    }

    @Override
    public void abort(Executor executor) throws SQLException {
        con.abort(executor);
    }

    @Override
    public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
        con.setNetworkTimeout(executor,milliseconds);
    }

    @Override
    public int getNetworkTimeout() throws SQLException {
        return con.getNetworkTimeout();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return con.unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return con.isWrapperFor(iface);
    }
}
归还连接_适配器设计模式:

通过装饰设计模式有很多个需要实现的方法。这个时候就可以使用适配器设计模式了。提供一个适配器类,实现Connection接口,将所有功能进行实现(除了close方法)。自定义连接类只需要继承这个适配器类,重写需要改进的close()方法即可!

实现步骤:

  1. 定义一个适配器类,实现Connection接口
  2. 定义Connection连接对象的成员变量
  3. 通过有参构造方法完成对成员变量的赋值
  4. 重写所有方法(除close),调用mysql驱动包的连接对象完成
  5. 定义一个类,继承适配器父类
  6. 定义Connection连接对象和连接池容器对象的变量,通过有参构造进行赋值
  7. 重写close()方法中,完成归还连接
  8. 在自定义连接池中,将获取的连接对象通过自定义连接对象进行包装

适配器类:

package com.dataSource;

import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;


/* 定义一个适配器类,实现Connection接口
   定义Connection连接对象的成员变量
   通过有参构造方法完成对成员变量的赋值
   重写所有方法(除close),调用mysql驱动包的连接对象完成
*/

public abstract class MyAdapter implements Connection {
    // 因为所有的方法还是要调用要有的连接对象所以需要有参把原有的对象接收进来
    // 一般适配器类都是抽象类,可以有抽象方法也可以有普通方法和构造
    private Connection con;

    public MyAdapter(Connection con) {
        this.con = con;
    }

    @Override
    public Statement createStatement() throws SQLException {
        return con.createStatement();
    }

    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return con.prepareStatement(sql);
    }

    @Override
    public CallableStatement prepareCall(String sql) throws SQLException {
        return con.prepareCall(sql);
    }

    @Override
    public String nativeSQL(String sql) throws SQLException {
        return con.nativeSQL(sql);
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        con.setAutoCommit(autoCommit);
    }

    @Override
    public boolean getAutoCommit() throws SQLException {
        return con.getAutoCommit();
    }

    @Override
    public void commit() throws SQLException {
        con.commit();
    }

    @Override
    public void rollback() throws SQLException {
        con.rollback();
    }

    @Override
    public boolean isClosed() throws SQLException {
        return con.isClosed();
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return con.getMetaData();
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException {
        con.setReadOnly(readOnly);
    }

    @Override
    public boolean isReadOnly() throws SQLException {
        return con.isReadOnly();
    }

    @Override
    public void setCatalog(String catalog) throws SQLException {
        con.setCatalog(catalog);
    }

    @Override
    public String getCatalog() throws SQLException {
        return con.getCatalog();
    }

    @Override
    public void setTransactionIsolation(int level) throws SQLException {
        con.setTransactionIsolation(level);
    }

    @Override
    public int getTransactionIsolation() throws SQLException {
        return con.getTransactionIsolation();
    }

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return con.getWarnings();
    }

    @Override
    public void clearWarnings() throws SQLException {
        con.clearWarnings();
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
        return con.createStatement(resultSetType, resultSetConcurrency);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return con.prepareStatement(sql, resultSetType, resultSetConcurrency);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return con.prepareCall(sql, resultSetType, resultSetConcurrency);
    }

    @Override
    public Map<String, Class<?>> getTypeMap() throws SQLException {
        return con.getTypeMap();
    }

    @Override
    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
        con.setTypeMap(map);
    }

    @Override
    public void setHoldability(int holdability) throws SQLException {
        con.setHoldability(holdability);
    }

    @Override
    public int getHoldability() throws SQLException {
        return con.getHoldability();
    }

    @Override
    public Savepoint setSavepoint() throws SQLException {
        return con.setSavepoint();
    }

    @Override
    public Savepoint setSavepoint(String name) throws SQLException {
        return con.setSavepoint(name);
    }

    @Override
    public void rollback(Savepoint savepoint) throws SQLException {
        con.rollback(savepoint);
    }

    @Override
    public void releaseSavepoint(Savepoint savepoint) throws SQLException {
        con.releaseSavepoint(savepoint);
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return con.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return con.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return con.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        return con.prepareStatement(sql, autoGeneratedKeys);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        return con.prepareStatement(sql, columnIndexes);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
        return con.prepareStatement(sql, columnNames);
    }

    @Override
    public Clob createClob() throws SQLException {
        return con.createClob();
    }

    @Override
    public Blob createBlob() throws SQLException {
        return con.createBlob();
    }

    @Override
    public NClob createNClob() throws SQLException {
        return con.createNClob();
    }

    @Override
    public SQLXML createSQLXML() throws SQLException {
        return con.createSQLXML();
    }

    @Override
    public boolean isValid(int timeout) throws SQLException {
        return con.isValid(timeout);
    }

    @Override
    public void setClientInfo(String name, String value) throws SQLClientInfoException {
        con.setClientInfo(name, value);
    }

    @Override
    public void setClientInfo(Properties properties) throws SQLClientInfoException {
        con.setClientInfo(properties);
    }

    @Override
    public String getClientInfo(String name) throws SQLException {
        return con.getClientInfo(name);
    }

    @Override
    public Properties getClientInfo() throws SQLException {
        return con.getClientInfo();
    }

    @Override
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
        return con.createArrayOf(typeName, elements);
    }

    @Override
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
        return con.createStruct(typeName, attributes);
    }

    @Override
    public void setSchema(String schema) throws SQLException {
        con.setSchema(schema);
    }

    @Override
    public String getSchema() throws SQLException {
        return con.getSchema();
    }

    @Override
    public void abort(Executor executor) throws SQLException {
        con.abort(executor);
    }

    @Override
    public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
        con.setNetworkTimeout(executor, milliseconds);
    }

    @Override
    public int getNetworkTimeout() throws SQLException {
        return con.getNetworkTimeout();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return con.unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return con.isWrapperFor(iface);
    }
}

继承适配器类:

public class MyConnection2 extends MyAdapter {
    private Connection con;
    private List<Connection> pool;

    public MyConnection2(Connection con, List<Connection> pool) {
        super(con);
        this.con = con;
        this.pool = pool;
    }

    @Override
    public void close() throws SQLException {
        pool.add(con);
    }
}

自定义连接池类:

public class MyDataSource implements DataSource {
    // 定义集合容器,用于保存多个数据库连接对象

    private static final List<Connection> pool = Collections.synchronizedList(new ArrayList<>());


    // 静态代码块,生成10个数据库连接保存到集合中
    static {
        for (int i = 0; i < 10; i++) {
            Connection coon = JDBCUtils.getConnection();
            pool.add(coon);
        }
    }

    // 从连接池返回一个数据库连接
    @Override
    public Connection getConnection() {
        if (pool.size() > 0) {
            // 从池中获取数据库连接
            Connection con = pool.remove(0);
            // 通过自定义连接对象进行包装
            MyConnection mycon = new MyConnection(con, pool);
            // 返回包装后的连接对象
        return mycon;
        } else {
            throw new RuntimeException("连接数量耗尽");
        }
    }

    /**定义getSize方法,获取连接池容器的大小*/
    public int getSize() {
        return pool.size();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

测试类:

public class DataSourceTest {
    public static void main(String[] args) throws SQLException {
        // 创建连接池对象
        MyDataSource dataSource = new MyDataSource();
        System.out.println("使用之前连接池数量:" + dataSource.getSize());
        // 通过连接池对象获取连接对象
        Connection conn = dataSource.getConnection();
        // 查看DriverManager连接的实现类
        System.out.println(conn.getClass());
        // 查询学生表的全部信息
        String sql = "SELECT * FROM student";
        PreparedStatement ps = conn.prepareStatement(sql);

        // 执行sql语句,接收结果集
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getInt("sid") + "\t" + rs.getString("name") + "\t" + rs.getInt("age") + "\t" + rs.getDate("birthday"));
        }

        // 释放资源
        conn.close();
        ps.close();
        rs.close();
        System.out.println("使用之后连接池数量:" + dataSource.getSize());
    }
}

适配器模式也可以实现,但是也很麻烦,说白了就是把装饰设计模式拆分了而已

连接池归还_动态代理:

经过适配器模式的改进,自定义连接类中的方法已经很简洁了。剩余所有的方法已经抽取到了适配器类中。但是适配器这个类还是我们自己编写的,也比较麻烦!所以可以使用动态代理的方式来改进。

自定义数据库连接池类:

public class MyDataSource implements DataSource{
    //定义集合容器,用于保存多个数据库连接对象
    private static List<Connection> pool = Collections.synchronizedList(new ArrayList<Connection>());

    //静态代码块,生成10个数据库连接保存到集合中
    static {
        for (int i = 0; i < 10; i++) {
            Connection con = JDBCUtils.getConnection();
            pool.add(con);
        }
    }

    //返回连接池的大小
    public int getSize() {
        return pool.size();
    }

    //动态代理方式
    @Override
    public Connection getConnection() {
        if(pool.size() > 0) {
            //从池中获取数据库连接
            Connection con = pool.remove(0);

            Connection proxyCon = (Connection)Proxy.newProxyInstance(con.getClass().getClassLoader(), new Class[]{Connection.class}, new InvocationHandler() {
                /*
                    执行Connection实现类所有方法都会经过invoke
                    如果是close方法,则将连接还回池中
                    如果不是,直接执行实现类的原有方法
                 */
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if(method.getName().equals("close")) {
                        pool.add(con);
                        return null;
                    }else {
                        return method.invoke(con,args);
                    }
                }
            });

            return proxyCon;
        }else {
            throw new RuntimeException("连接数量已用尽");
        }
    }
}
C3P0:

C3P0是一个开源的JDBC连接池,简化了很多步骤

使用步骤:

  1. 导入jar包
  2. 导入配置文件到src目录下
  3. 创建c3p0连接池对象
  4. 获取数据库连接进行使用 注意:C3p0的配置文件会自动加载,但是必须叫c3p0-config.xmlc3p0-config.properties

在这里插入图片描述
C3p0测试类:

public class C3p0Test {
    public static void main(String[] args) throws Exception {
        // 这里是空参的话,加载的就是默认的C3p0,如果指定名称就可以用自定义的
        DataSource dataSource = new ComboPooledDataSource();

        // 通过连接池对象获取数据库连接
        Connection con = dataSource.getConnection();

        // 查询学生表的全部信息
        String sql = "SELECT * FROM student";
        PreparedStatement ps = con.prepareStatement(sql);

        // 执行sql语句,接收结果集
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getInt("sid") + "\t" + rs.getString("name") + "\t" + rs.getInt("age") + "\t" + rs.getDate("birthday"));
        }

        // 释放资源
        con.close();
        ps.close();
        rs.close();
    }
}

测试连接池归还情况:

public class C3P0Test02 {
    public static void main(String[] args) throws Exception {
        DataSource dataSource = new ComboPooledDataSource();

        // 定的是10个连接池,如果是11=5个应该会在3秒以后去申请新的,然后报错
        for (int i = 0; i < 15; i++) {
            Connection con = dataSource.getConnection();
            System.out.println(i + "   " + con);
            // 执行到第六次的时候关闭,如果处理了close 地址值肯定是有两个重复的
            if (i == 6) {
                con.close();
            }
        }
        // 第6个的连接执行到的时候就关闭掉,可以看到打印结果第6、7次的地址值是一样的,有十一个地址值,说明是做了归还处理
    }
}

配置类:c3p0-config.xml

<c3p0-config>
  <!-- 使用默认的配置读取连接池对象 -->
  <default-config>
  	<!--  连接参数 -->
    <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost/db2</property>
    <property name="user">root</property>
    <property name="password">itzhuzhu</property>
    
    <!-- 连接池参数 -->
    <!--初始化的连接数量-->
    <property name="initialPoolSize">5</property>
    <!--最大连接数量  初始化为5,最大10,意思就是默认给5个,不够再要,但是最多10个-->
    <property name="maxPoolSize">10</property>
    <!--超时时间 毫秒-->
    <property name="checkoutTimeout">3000</property>
  </default-config>

  <!--这里是和上面一样的配置,但是c3p0默认的是上面这个,也可以自己加name,不指定的时候默认使用上面的-->
  <named-config name="otherc3p0"> 
    <!--  连接参数 -->
    <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/db2</property>
    <property name="user">root</property>
    <property name="password">itzhuzhu</property>
    
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">8</property>
    <property name="checkoutTimeout">1000</property>
  </named-config>
</c3p0-config>
Druid:

阿里开发的数据库连接池工具,不会自动加载配置文件,需要手动去读取,文件名称可以随意取,连接池也不会释放。

使用步骤:

  1. 导入jar包
  2. 编写配置文件,放在src目录下
  3. 通过Properties集合加载配置文件
  4. 通过Druid连接池工厂类获取数据库连接池对象
  5. 获取数据库连接,进行使用

工具类:

public class DataSourceUtils {
    //1.私有构造方法
    private DataSourceUtils() {
    }

    //2.定义DataSource数据源变量
    private static DataSource dataSource;

    //3.提供静态代码块,完成配置文件的加载和获取连接池对象
    static {
        try {
            //加载配置文件
            InputStream is = DataSourceUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            Properties prop = new Properties();
            prop.load(is);

            //获取数据库连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(prop);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //4.提供获取数据库连接的方法
    public static Connection getConnection() {
        Connection con = null;
        try {
            con = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    //5.提供获取数据库连接池的方法
    public static DataSource getDataSource() {
        return dataSource;
    }

    //6.提供释放资源的方法
    public static void close(Connection con, Statement stat, ResultSet rs) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection con, Statement stat) {
        close(con, stat, null);
    }
}

配置文件:

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost/db2
username=root
password=itzhuzhu

#初始化连接数量
initialSize=5

#最大连接数量
maxActive=10

#超时时间
maxWait=3000

测试类:

public class DruidTest {
    public static void main(String[] args) throws Exception {
        Connection con = DataSourceUtils.getConnection();
        // 查询学生表的全部信息
        String sql = "SELECT * FROM student";
        PreparedStatement ps = con.prepareStatement(sql);

        // 执行sql语句,接收结果集
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getInt("sid") + "\t" + rs.getString("name") + "\t" + rs.getInt("age") + "\t" + rs.getDate("birthday"));
        }

        // 释放资源
        DataSourceUtils.close(con, ps, rs);
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

itzhuzhu.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值