`
hbkh2000
  • 浏览: 197471 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

apache连接池使用

 
阅读更多

1、什么时候使用?
连接池是用来建立一些和db的连接,使用户访问db时可以直接使用
这些现成的连接。
  如果不建立连接池,每个用户每一次访问db时都要和db建立一次连接,
这样db server 容易产生连接过多的错误,用户也会觉得速度很慢。
   web编程,如果使用的是:客户端---web server---db server.
这种架构的,建议使用连接池的方法处理web server与db server间的
通讯。

2、如何检测连接池,让连接池配置更合理?

apache连接池使用

commons DBCP 配置参数简要说明 
   
  在配置时,主要难以理解的主要有:removeAbandoned 、logAbandoned、removeAbandonedTimeout、maxWait这四个参数,设置了rmoveAbandoned=true那么在getNumActive()快要到getMaxActive()的时候,系统会进行无效的Connection的回收,回收的Connection为removeAbandonedTimeout(默认300秒)中设置的秒数后没有使用的Connection,激活回收机制好像是getNumActive()=getMaxActive()-2。  有点忘了。 
  logAbandoned=true的话,将会在回收事件后,在log中打印出回收Connection的错误信息,包括在哪个地方用了Connection却忘记关闭了,在调试的时候很有用。 
  在这里私人建议maxWait的时间不要设得太长,maxWait如果设置太长那么客户端会等待很久才激发回收事件。 
  以下是我的配置的properties文件: 
#连接设置 
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver 
jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:DBSERVER 
jdbc.username=user 
jdbc.password=pass 

#<!-- 初始化连接 --> 
dataSource.initialSize=10 

#<!-- 最大空闲连接 --> 
dataSource.maxIdle=20 

#<!-- 最小空闲连接 --> 
dataSource.minIdle=5 

#最大连接数量 
dataSource.maxActive=50 

#是否在自动回收超时连接的时候打印连接的超时错误 
dataSource.logAbandoned=true 

#是否自动回收超时连接 
dataSource.removeAbandoned=true 

#超时时间(以秒数为单位) 
dataSource.removeAbandonedTimeout=180 

#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 --> 
dataSource.maxWait=1000 

  以下是我在连接控制中调用的方法: 
Java代码 复制代码 收藏代码
  1. Properties  dbProps=null;   
  2. 取配置文件可以根据实际的不同修改   
  3. dbProps = ConfigProperties.getInstance().getProperties("jdbc.properties");   
  4. try {   
  5.  String driveClassName = dbProps.getProperty("jdbc.driverClassName");   
  6.  String url = dbProps.getProperty("jdbc.url");   
  7.  String username = dbProps.getProperty("jdbc.username");   
  8.  String password = dbProps.getProperty("jdbc.password");   
  9.     
  10.  String initialSize = dbProps.getProperty("dataSource.initialSize");   
  11.  String minIdle = dbProps.getProperty("dataSource.minIdle");   
  12.  String maxIdle = dbProps.getProperty("dataSource.maxIdle");   
  13.  String maxWait = dbProps.getProperty("dataSource.maxWait");   
  14.  String maxActive = dbProps.getProperty("dataSource.maxActive");   
  15.    //是否在自动回收超时连接的时候打印连接的超时错误   
  16.   boolean logAbandoned = (Boolean.valueOf(dbProps.getProperty("dataSource.logAbandoned","false"))).booleanValue();   
  17.   
  18.   //是否自动回收超时连接   
  19.   boolean removeAbandoned = (Boolean.valueOf(dbProps.getProperty("dataSource.removeAbandoned","false"))).booleanValue();   
  20.   
  21.   //超时时间(以秒数为单位)   
  22.   int removeAbandonedTimeout = Integer.parseInt(dbProps.getProperty("dataSource.removeAbandonedTimeout","300"));   
  23.   
  24.  dataSource = new BasicDataSource();   
  25.  dataSource.setDriverClassName(driveClassName);   
  26.  dataSource.setUrl(url);   
  27.  dataSource.setUsername(username);   
  28.  dataSource.setPassword(password);   
  29.   
  30.  //初始化连接数   
  31.  if(initialSize!=null)   
  32.   dataSource.setInitialSize(Integer.parseInt(initialSize));   
  33.     
  34.  //最小空闲连接   
  35.  if(minIdle!=null)   
  36.   dataSource.setMinIdle(Integer.parseInt(minIdle));   
  37.   
  38.  //最大空闲连接   
  39.  if(maxIdle!=null)   
  40.   dataSource.setMaxIdle(Integer.parseInt(maxIdle));   
  41.     
  42.  //超时回收时间(以毫秒为单位)   
  43.  if(maxWait!=null)   
  44.   dataSource.setMaxWait(Long.parseLong(maxWait));   
  45.     
  46.  //最大连接数   
  47.  if(maxActive!=null){   
  48.   if(!maxActive.trim().equals("0"))   
  49.    dataSource.setMaxActive(Integer.parseInt(maxActive));   
  50.  }   
  51.   
  52.  System.out.println("logAbandoned="+logAbandoned);   
  53.     dataSource.setLogAbandoned(logAbandoned);   
  54.  dataSource.setRemoveAbandoned(removeAbandoned);   
  55.  dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);   
  56.     
  57.  Connection conn = dataSource.getConnection();   
  58.  if(conn==null){   
  59.   log("创建连接池时,无法取得连接!检查设置!!!");   
  60.  }else{   
  61.   conn.close();   
  62.  }   
  63.  System.out.println("连接池创建成功!!!");   
  64. }   
  65. catch (Exception e) {   
  66.  e.printStackTrace();   
  67.     System.out.println("创建连接池失败!请检查设置!!!");   
  68. }  
        Properties  dbProps=null;
  //下面的读取配置文件可以根据实际的不同修改
        dbProps = ConfigProperties.getInstance().getProperties("jdbc.properties");
        try {
         String driveClassName = dbProps.getProperty("jdbc.driverClassName");
         String url = dbProps.getProperty("jdbc.url");
         String username = dbProps.getProperty("jdbc.username");
         String password = dbProps.getProperty("jdbc.password");
         
         String initialSize = dbProps.getProperty("dataSource.initialSize");
         String minIdle = dbProps.getProperty("dataSource.minIdle");
         String maxIdle = dbProps.getProperty("dataSource.maxIdle");
         String maxWait = dbProps.getProperty("dataSource.maxWait");
         String maxActive = dbProps.getProperty("dataSource.maxActive");
           //是否在自动回收超时连接的时候打印连接的超时错误
          boolean logAbandoned = (Boolean.valueOf(dbProps.getProperty("dataSource.logAbandoned","false"))).booleanValue();

          //是否自动回收超时连接
          boolean removeAbandoned = (Boolean.valueOf(dbProps.getProperty("dataSource.removeAbandoned","false"))).booleanValue();

          //超时时间(以秒数为单位)
          int removeAbandonedTimeout = Integer.parseInt(dbProps.getProperty("dataSource.removeAbandonedTimeout","300"));
        
         dataSource = new BasicDataSource();
         dataSource.setDriverClassName(driveClassName);
         dataSource.setUrl(url);
         dataSource.setUsername(username);
         dataSource.setPassword(password);

         //初始化连接数
         if(initialSize!=null)
          dataSource.setInitialSize(Integer.parseInt(initialSize));
         
         //最小空闲连接
         if(minIdle!=null)
          dataSource.setMinIdle(Integer.parseInt(minIdle));

         //最大空闲连接
         if(maxIdle!=null)
          dataSource.setMaxIdle(Integer.parseInt(maxIdle));
         
         //超时回收时间(以毫秒为单位)
         if(maxWait!=null)
          dataSource.setMaxWait(Long.parseLong(maxWait));
         
         //最大连接数
         if(maxActive!=null){
          if(!maxActive.trim().equals("0"))
           dataSource.setMaxActive(Integer.parseInt(maxActive));
         }

         System.out.println("logAbandoned="+logAbandoned);
            dataSource.setLogAbandoned(logAbandoned);
         dataSource.setRemoveAbandoned(removeAbandoned);
         dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
         
         Connection conn = dataSource.getConnection();
         if(conn==null){
          log("创建连接池时,无法取得连接!检查设置!!!");
         }else{
          conn.close();
         }
         System.out.println("连接池创建成功!!!");
        }
        catch (Exception e) {
         e.printStackTrace();
            System.out.println("创建连接池失败!请检查设置!!!");
        }


用apache的dbcp来建立独立的数据库连接池(db connection pool)
数据库连接池的好处是不言而喻的,现在大部分的application server都提供自己的数据库连接池方案,此时,只要按照application server的文档说明,正确配置,即可在应用中享受到数据库连接池的好处。
但是,有些时候,我们的应用是个独立的java application,并不是普通的WEB/J2EE应用,而且是单独运行的,不要什么application server的配合,这种情况下,我们就需要建立自己的数据库连接池方案了。这里,介绍如何利用apache的dbcp来建立为民自己的数据库连接池。
1。首先,下载必须的jar包
dbcp包,目前版本是1.2.1:http://jakarta.apache.org/commons/dbcp/
pool包,目前版本是1.3:http://jakarta.apache.org/commons/pool/,
如果下载的pool包是1.2的版本,还要下载common-collections包:http://jakarta.apache.org/commons/collections/
在建立我们自己的数据库连接池时,可以使用xml文件来传入需要的参数,这里只使用hard code的方式来简单介绍,所有需要我们自己写的代码很少,只要建立一个文件如下:

Java代码 复制代码 收藏代码
  1. import org.apache.commons.dbcp.BasicDataSource;   
  2. import org.apache.commons.dbcp.BasicDataSourceFactory;   
  3.   
  4. import java.sql.SQLException;   
  5. import java.sql.Connection;   
  6. import java.util.Properties;   
  7.   
  8. public class ConnectionSource {   
  9.     private static BasicDataSource dataSource = null;   
  10.   
  11.     public ConnectionSource() {   
  12.     }   
  13.   
  14.     public static void init() {   
  15.   
  16.         if (dataSource != null) {   
  17.             try {   
  18.                 dataSource.close();   
  19.             } catch (Exception e) {   
  20.                 //   
  21.             }   
  22.             dataSource = null;   
  23.         }   
  24.   
  25.         try {   
  26.             Properties p = new Properties();   
  27.             p.setProperty("driverClassName""oracle.jdbc.driver.OracleDriver");   
  28.             p.setProperty("url""jdbc:oracle:thin:@192.168.0.1:1521:testDB");   
  29.             p.setProperty("password""scott");   
  30.             p.setProperty("username""tiger");   
  31.             p.setProperty("maxActive""30");   
  32.             p.setProperty("maxIdle""10");   
  33.             p.setProperty("maxWait""1000");   
  34.             p.setProperty("removeAbandoned""false");   
  35.             p.setProperty("removeAbandonedTimeout""120");   
  36.             p.setProperty("testOnBorrow""true");   
  37.             p.setProperty("logAbandoned""true");   
  38.   
  39.             dataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(p);   
  40.   
  41.         } catch (Exception e) {   
  42.             //   
  43.         }   
  44.     }   
  45.   
  46.   
  47.     public static synchronized Connection getConnection() throws  SQLException {   
  48.         if (dataSource == null) {   
  49.             init();   
  50.         }   
  51.         Connection conn = null;   
  52.         if (dataSource != null) {   
  53.             conn = dataSource.getConnection();   
  54.         }   
  55.         return conn;   
  56.     }   
  57. }  
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import java.sql.SQLException;
import java.sql.Connection;
import java.util.Properties;

public class ConnectionSource {
    private static BasicDataSource dataSource = null;

    public ConnectionSource() {
    }

    public static void init() {

        if (dataSource != null) {
            try {
                dataSource.close();
            } catch (Exception e) {
                //
            }
            dataSource = null;
        }

        try {
            Properties p = new Properties();
            p.setProperty("driverClassName", "oracle.jdbc.driver.OracleDriver");
            p.setProperty("url", "jdbc:oracle:thin:@192.168.0.1:1521:testDB");
            p.setProperty("password", "scott");
            p.setProperty("username", "tiger");
            p.setProperty("maxActive", "30");
            p.setProperty("maxIdle", "10");
            p.setProperty("maxWait", "1000");
            p.setProperty("removeAbandoned", "false");
            p.setProperty("removeAbandonedTimeout", "120");
            p.setProperty("testOnBorrow", "true");
            p.setProperty("logAbandoned", "true");

            dataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(p);

        } catch (Exception e) {
            //
        }
    }


    public static synchronized Connection getConnection() throws  SQLException {
        if (dataSource == null) {
            init();
        }
        Connection conn = null;
        if (dataSource != null) {
            conn = dataSource.getConnection();
        }
        return conn;
    }
}


接下来,在我们的应用中,只要简单地使用ConnectionSource.getConnection()就可以取得连接池中的数据库连接,享受数据库连接带给我们的好处了。当我们使用完取得的数据库连接后,只要简单地使用connection.close()就可把此连接返回到连接池中,至于为什么不是直接关闭此连接,而是返回给连接池,这是因为dbcp使用委派模型来实现Connection接口了。

在使用Properties来创建BasicDataSource时,有很多参数可以设置,比较重要的还有:

testOnBorrow、testOnReturn、testWhileIdle,他们的意思是当是取得连接、返回连接或连接空闲时是否进行有效性验证(即是否还和数据库连通的),默认都为false。所以当数据库连接因为某种原因断掉后,再从连接池中取得的连接,实际上可能是无效的连接了,所以,为了确保取得的连接是有效的, 可以把把这些属性设为true。当进行校验时,需要另一个参数:validationQuery,对oracle来说,可以是:SELECT COUNT(*) FROM DUAL,实际上就是个简单的SQL语句,验证时,就是把这个SQL语句在数据库上跑一下而已,如果连接正常的,当然就有结果返回了。

还有2个参数:timeBetweenEvictionRunsMillis 和 minEvictableIdleTimeMillis, 他们两个配合,可以持续更新连接池中的连接对象,当timeBetweenEvictionRunsMillis 大于0时,每过timeBetweenEvictionRunsMillis 时间,就会启动一个线程,校验连接池中闲置时间超过minEvictableIdleTimeMillis的连接对象。

原文参考http://blog.csdn.net/zllsdn/archive/2006/11/20/1398577.aspx

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics