设为首页 收藏本站
查看: 589|回复: 0

[经验分享] apache连接池使用

[复制链接]

尚未签到

发表于 2017-1-2 09:47:07 | 显示全部楼层 |阅读模式
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代码 DSC0000.gif   DSC0001.png DSC0002.gif




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



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




  • 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() 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

 

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-322711-1-1.html 上篇帖子: Apache内存池内幕(2) 下篇帖子: apache日志分析简介
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表