java数据库连接池

一、数据库连接池是什么

①数据库连接池的基本思想就是为数据库连接建立一个“缓冲池”。
数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个。
②数据库连接池在初始化时将创建一定数量的数据库连接放到连接池中,这些数据库连接的数量是由最小数据库连接数来设定的。无论这些数据库连接是否被使用,连接池都将一直保证至少拥有这么多的连接数量。连接池的最大数据库连接数量限定了这个连接池能占有的最大连接数,当应用程序向连接池请求的连接数超过最大连接数量时,这些请求将被加入到等待队列中。
③数据库连接池技术的优点:资源重用、更快的系统反应速度、新的资源分配手段和统一的连接管理,避免数据库连接泄露
④JDBC 的数据库连接池使用 javax.sql.DataSource 来表示,DataSource 只是一个接口,该接口通常由服务器(Weblogic, WebSphere, Tomcat)提供实现,也有一些开源组织提供实现。
DataSource 通常被称为数据源,它包含连接池和连接池管理两个部分,习惯上也经常把 DataSource 称为连接池
⑤数据库连接池的 Connection 对象进行 close 时,并不是真的进行关闭, 而是把该数据库连接会归还到数据库连接池中。
当连接池连接减少甚至没有时,连接池自动关闭一些连接,保持最小数目。

二、DBCP 数据库连接池

Tomcat 的连接池正是采用该连接池来实现的。

使用步骤:

①方式一:
1. 加入jar包(commons-dbcp-x.jar和commons-pool-x.jar)

2. 创建数据库连接池实例
BasicDataSource dataSource = new BasicDataSource();

3. 为数据源实例指定必须的属性
dataSource.setUsername("root");
dataSource.setPassword("1230");
dataSource.setUrl("jdbc:mysql:///atguigu");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");

4. 指定数据源的一些可选的属性.
1). 指定数据库连接池中初始化连接数的个数
dataSource.setInitialSize(5);        
2). 指定最大的连接数: 同一时刻可以同时向数据库申请的连接数
dataSource.setMaxActive(5);    
3). 指定最小连接数: 在数据库连接池中保存的最少的空闲连接的数量
dataSource.setMinIdle(2);
4).等待数据库连接池分配连接的最长时间. 单位为毫秒. 超出该时间将抛出异常.
dataSource.setMaxWait(1000);

5. 从数据源中获取数据库连接
Connection connection = dataSource.getConnection();

②方式二:

1. 加入jar包(commons-dbcp-x.jar和commons-pool-x.jar)

2. 加载 dbcp 的 properties 配置文件: 配置文件中的键需要来自 BasicDataSource的属性.
Properties properties = new Properties();
InputStream in = this.getClass().getClassLoader().getResourceAsStream("dbcp.properties");
properties.load(in);

3. 调用 BasicDataSourceFactory 的 createDataSource 方法创建 DataSource实例
DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);

4. 从 DataSource 实例中获取数据库连接.
dataSource.getConnection()        

三、c3p0数据库连接池

导入c3p0-0.9.2-pre1.jar

使用方式一:

ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "com.mysql.jdbc.Driver" );          
cpds.setJdbcUrl( "jdbc:mysql:///atguigu" );
cpds.setUser("root");                                  
cpds.setPassword("1230");   
cpds.getConnection();

使用方式二:
1. 创建 c3p0-config.xml 文件, 参考帮助文档中 Appendix B: Configuation Files 的内容
2. 创建 ComboPooledDataSource 实例(数据库连接池应只被初始化一次)
DataSource dataSource = new ComboPooledDataSource("helloc3p0");  
3. 从 DataSource 实例中获取数据库连接.
dataSource.getConnection();
4. c3p0-config.xml 文件:


  
   
root
1230
com.mysql.jdbc.Driver
jdbc:mysql:///atguigu

5

5

5

10

20

5

	

四、自定义的一个线程池

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.Properties;

public class JdbcPool {

    /**
    * @Field: unusedlst
    *         使用LinkedList集合来存放数据库链接,
    *        由于要频繁读写List集合,所以这里使用LinkedList存储数据库连接比较合适
    */ 
    private static LinkedList unusedlst = new LinkedList();
    
    static{
        //在静态代码块中加载db.properties数据库配置文件
        InputStream in = JdbcPool.class.getClassLoader().getResourceAsStream("db.properties");
        Properties prop = new Properties();
        try {
            prop.load(in);
            String driver = prop.getProperty("driver");
            String url = prop.getProperty("url");
            String username = prop.getProperty("username");
            String password = prop.getProperty("password");
            //数据库连接池的初始化连接数大小
            int jdbcPoolInitSize =Integer.parseInt(prop.getProperty("jdbcPoolInitSize"));
            //加载数据库驱动
            Class.forName(driver);
            for (int i = 0; i < jdbcPoolInitSize; i++) {
                Connection conn = DriverManager.getConnection(url, username, password);
                //将获取到的数据库连接加入到unusedlst集合中,unusedlst集合此时就是一个存放了数据库连接的连接池
                unusedlst.add(conn);
            }
            
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }
  
    public static synchronized  Connection getConnection() throws SQLException {
        //如果数据库连接池中的连接对象的个数大于0
        if(unusedlst.size() <= 0)
            return null;
        Connection connection = unusedlst.poll();    
        return connection;        
    }
    
    public synchronized static void  releaseConnection(Connection con)
    {
        unusedlst.add(con);
    }

    public static void releaseConnection(Connection con, Statement st,ResultSet rs)
    {
        if(rs!=null){
            try{
                //关闭存储查询结果的ResultSet对象
                rs.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
            rs = null;
        }
        if(st!=null){
            try{
                //关闭负责执行SQL命令的Statement对象
                st.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        releaseConnection(con);
    }
}

 

你可能感兴趣的:(Java)