日期:2014-05-17  浏览次数:20755 次

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. ??