← 返回学习路线

SYSTEM

连接池

Java基础连接池system
src/content/notes/system/连接池.md

连接池

概念

数据库连接背景:数据库连接是一种关键的、有限的、昂贵的资源,这一点在多用户的网页应用程序中体现得尤为突出。对数据库连接的管理能显著影响到整个应用程序的伸缩性和健壮性,影响到程序的性能指标。

数据库连接池:数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个,这项技术能明显提高对数据库操作的性能。

数据库连接池原理


归还连接

使用动态代理的方式来改进

自定义数据库连接池类:

public class MyDataSource implements DataSource {
    //1.准备一个容器。用于保存多个数据库连接对象
    private static List<Connection> pool = Collections.synchronizedList(new ArrayList<>());

    //2.定义静态代码块,获取多个连接对象保存到容器中
    static{
        for(int i = 1; i <= 10; i++) {
            Connection con = JDBCUtils.getConnection();
            pool.add(con);
        }
    }
    //3.提供一个获取连接池大小的方法
    public int getSize() {
        return pool.size();
    }

   	//动态代理方式
    @Override
    public Connection getConnection() throws SQLException {
        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 连接池:

  • 配置文件名称:c3p0-config.xml,必须放在 src 目录下

    <c3p0-config>
      <!-- 使用默认的配置读取连接池对象 -->
      <default-config>
      	<!--  连接参数 -->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://192.168.2.184:3306/db14</property>
        <property name="user">root</property>
        <property name="password">123456</property>
        
        <!-- 连接池参数 -->
        <!--初始化数量-->
        <property name="initialPoolSize">5</property>
        <!--最大连接数量-->
        <property name="maxPoolSize">10</property>
        <!--超时时间 3000ms-->
        <property name="checkoutTimeout">3000</property>
      </default-config>
    
      <named-config name="otherc3p0"> 
        <!--  连接参数 -->
        <!-- 连接池参数 -->
      </named-config>
    </c3p0-config>
  • 代码演示

    public class C3P0Test1 {
        public static void main(String[] args) throws Exception{
            //1.创建c3p0的数据库连接池对象
            DataSource dataSource = new ComboPooledDataSource();
    
            //2.通过连接池对象获取数据库连接
            Connection con = dataSource.getConnection();
    
            //3.执行操作
            String sql = "SELECT * FROM student";
            PreparedStatement pst = con.prepareStatement(sql);
    
            //4.执行sql语句,接收结果集
            ResultSet rs = pst.executeQuery();
    
            //5.处理结果集
            while(rs.next()) {
                System.out.println(rs.getInt("sid") + "\t" + rs.getString("name") + "\t" + rs.getInt("age") + "\t" + rs.getDate("birthday"));
            }
    
            //6.释放资源
            rs.close();   pst.close();   con.close();
        }
    }

Druid

Druid 连接池:

  • 配置文件:druid.properties,必须放在 src 目录下

    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://192.168.2.184:3306/db14
    username=root
    password:[已隐藏]
    initialSize=5
    maxActive=10
    maxWait=3000
  • 代码演示

    public class DruidTest1 {
        public static void main(String[] args) throws Exception{
            //获取配置文件的流对象
            InputStream is = DruidTest1.class.getClassLoader().getResourceAsStream("druid.properties");
    
            //1.通过Properties集合,加载配置文件
            Properties prop = new Properties();
            prop.load(is);
    
            //2.通过Druid连接池工厂类获取数据库连接池对象
            DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
    
            //3.通过连接池对象获取数据库连接进行使用
            Connection con = dataSource.getConnection();
            
    		//4.执行sql语句,接收结果集
            String sql = "SELECT * FROM student";
            PreparedStatement pst = con.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();
    
            //5.处理结果集
            while(rs.next()) {
                System.out.println(rs.getInt("sid") + "\t" + rs.getString("name") + "\t" + rs.getInt("age") + "\t" + rs.getDate("birthday"));
            }
    
            //6.释放资源
            rs.close();   pst.close();   con.close();
        }
    }