trssc 发表于 2017-1-2 09:47:07

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代码  




[*]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("创建连接池失败!请检查设置!!!");   
[*]}  



      PropertiesdbProps=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代码  




[*]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;   
[*]    }   
[*]}  



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() throwsSQLException {
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

 
页: [1]
查看完整版本: apache连接池使用