查看资料,得知dbcp和c3p0都是单线程的,在高并发的环境下性能会非常低下,
决定换用tomcat自带的jdbc-pool,关于jdbc-pool的项目介绍。
区别参考链接:http://www.open-open.com/lib/view/open1329182303124.html
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" parent="c3p0DataSource">
Tomcat 在 7.0 以前的版本都是使用 commons-dbcp 做为连接池的实现,但是 dbcp 饱受诟病,原因有:
dbcp 是单线程的,为了保证线程安全会锁整个连接池
dbcp 性能不佳
dbcp 太复杂,超过 60 个类
dbcp 使用静态接口,在 JDK 1.6 编译有问题
dbcp 发展滞后
因此很多人会选择一些第三方的连接池组件,例如 c3p0 , bonecp, druid (@wenshao ) 等。
为此,Tomcat 从 7.0 开始引入一个新的模块:Tomcat jdbc pool
tomcat jdbc pool 近乎兼容 dbcp ,性能更高
异步方式获取连接
tomcat jdbc pool 是 tomcat 的一个模块,基于 tomcat JULI,使用 Tomcat 的日志框架
使用 javax.sql.PooledConnection 接口获取连接
支持高并发应用环境
超简单,核心文件只有8个,比 c3p0 还
更好的空闲连接处理机制
支持 JMX
支持 XA Connection
tomcat jdbc pool 的优点远不止这些,详情请看这里。
tomcat jdbc pool 可在 Tomcat 中直接使用,也可以在独立的应用中使用。
推荐使用
[html] view plain copy print?
-- JDBC连接池 、数据源 -->
id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="false" />
<property name="validationQuery" value="SELECT 1" />
<property name="validationInterval" value="30000" />
<property name="timeBetweenEvictionRunsMillis" value="30000" />
<property name="maxActive" value="100" />
<property name="minIdle" value="2" />
<property name="maxWait" value="10000" />
<property name="initialSize" value="4" />
<property name="removeAbandonedTimeout" value="60" />
<property name="removeAbandoned" value="true" />
<property name="logAbandoned" value="true" />
<property name="minEvictableIdleTimeMillis" value="30000" />
<property name="jmxEnabled" value="true" />
引入Maven依赖:
[html] view plain copy print?在CODE上查看代码片派生到我的代码片
org.apache.tomcat
tomcat-jdbc
7.0.29
org.apache.tomcat
tomcat-juli
7.0.29
tomcat-dbcp与commons-dbcp有什么区别
The default database connection pool implementation in Apache Tomcat relies on the libraries from the Apache Commons project. The following libraries are used:
Commons DBCP
Commons Pool
These libraries are located in a single JAR at $CATALINA_HOME/lib/tomcat-dbcp.jar. However, only the classes needed for connection pooling have been included, and the packages have been renamed to avoid interfering with applications.
以上是tomcat7.x的帮助文档,大意是tomcat-dbcp.jar包含了commons-dbcp和Commons Pool的内容,当然也只仅仅包含了需要数据库连接的部分,而不是全部。
本文提供了对c3p0与DBCP连接池连接MySQL数据库时, 8小时内无请求自动断开连接的解决方案。首先介绍一下我在项目(c3p0连接池)中遇到的问题,后面还提供了使用DBCP连接池的解决方案。
基本问题解决
项目环境:
Java Web项目框架为spring MVC+JPA,使用c3p0连接池,发布环境为Tomcat 7
错误描述:
项目运行一段时间(大概几个小时)之后访问时会出现第一次访问报错,再次访问正常的现象,且多次出现此问题。
报错日志:
[plain] view plain copy 在CODE上查看代码片派生到我的代码片
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.TransactionException: JDBC begin transaction failed:
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:428)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:372)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:417)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:255)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
at com.appcarcare.cube.service.UserService
EnhancerByCGLIB
a4429cba.getUserDao()
at com.appcarcare.cube.servlet.DataCenterServlet$SqlTimer.connectSql(DataCenterServlet.java:76)
at com.appcarcare.cube.servlet.DataCenterServlet$SqlTimer.run(DataCenterServlet.java:70)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Caused by: javax.persistence.PersistenceException: org.hibernate.TransactionException: JDBC begin transaction failed:
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1397)
at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:62)
at org.springframework.orm.jpa.DefaultJpaDialect.beginTransaction(DefaultJpaDialect.java:71)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:60)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:378)
... 11 more
Caused by: org.hibernate.TransactionException: JDBC begin transaction failed:
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:76)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1426)
at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:59)
... 14 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 1,836,166 milliseconds ago. The last packet sent successfully to the server was 29,134 milliseconds ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1117)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3567)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3456)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3997)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2468)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2629)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2713)
at com.mysql.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:5060)
at com.mchange.v2.c3p0.impl.NewProxyConnection.setAutoCommit(NewProxyConnection.java:881)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:72)
... 17 more
Caused by: java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:150)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:114)
at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:161)
at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:189)
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3014)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3467)
... 25 more
原因分析:
MySQL服务器默认的“wait_timeout”是28800秒即8小时,意味着如果一个连接的空闲时间超过8个小时,MySQL将自动断开该连接,而连接池却认为该连接还是有效的(因为并未校验连接的有效性),当应用申请使用该连接时,就会导致上面的报错。
解决方案(解决这个问题的办法有三种,推荐第二种):
1. 增加 MySQL 的 wait_timeout 属性的值
修改mysql安装目录下的配置文件 my.ini文件(如果没有此文件,复制“my-default.ini”文件,生成“复件 my-default.ini”文件。将“复件 my-default.ini”文件重命名成“my.ini” ),在文件中设置:
[plain] view plain copy 在CODE上查看代码片派生到我的代码片
wait_timeout=31536000
interactive_timeout=31536000
这两个参数的默认值是8小时(60*60*8=28800)。
注意: 1.wait_timeout的最大值只允许2147483 (24天左右)
2.修改配置文件为网上大部分文章所提供的方式,也可以使用mysql命令对这两个属性进行修改
mysql命令
id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="preferredTestQuery" value="SELECT 1"/>
<property name="idleConnectionTestPeriod" value="18000"/>
<property name="testConnectionOnCheckout" value="true"/>
知识扩展
C3P0
C3P0是一个开放源代码的JDBC连接池,它在lib目录中与hibernate一起发布,包括了实现jdbc3和jdbc2扩展规范说明的Connection 和Statement 池的DataSources 对象。 c3p0配置文件
[html] view plain copy 在CODE上查看代码片派生到我的代码片
<default-config>
<property name="acquireIncrement">3property>
<property name="acquireRetryAttempts">30property>
<property name="acquireRetryDelay">1000property>
<property name="autoCommitOnClose">falseproperty>
<property name="automaticTestTable">Testproperty>
<property name="breakAfterAcquireFailure">falseproperty>
<property name="checkoutTimeout">100property>
<property name="connectionTesterClassName">property>
<property name="factoryClassLocation">nullproperty>
<property name="forceIgnoreUnresolvedTransactions">falseproperty>
<property name="idleConnectionTestPeriod">60property>
<property name="initialPoolSize">3property>
<property name="maxIdleTime">60property>
<property name="maxPoolSize">15property>
<property name="maxStatements">100property>
<property name="maxStatementsPerConnection">property>
<property name="numHelperThreads">3property>
<property name="overrideDefaultUser">rootproperty>
<property name="overrideDefaultPassword">passwordproperty>
<property name="password">property>
<property name="preferredTestQuery">select id from test where id=1property>
<property name="propertyCycle">300property>
<property name="testConnectionOnCheckout">falseproperty>
<property name="testConnectionOnCheckin">trueproperty>
<property name="user">rootproperty>
在Hibernate(spring管理)中的配置:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass"><value>oracle.jdbc.driver.OracleDrivervalue>property>
<property name="jdbcUrl"><value>jdbc:oracle:thin:@localhost:1521:Testvalue>property>
<property name="user"><value>Kayvalue>property>
<property name="password"><value>rootvalue>property>
<property name="minPoolSize" value="10" />
<property name="maxPoolSize" value="100" />
<property name="maxIdleTime" value="1800" />
<property name="acquireIncrement" value="3" />
<property name="maxStatements" value="1000" />
<property name="initialPoolSize" value="10" />
<property name="idleConnectionTestPeriod" value="60" />
<property name="acquireRetryAttempts" value="30" />
<property name="breakAfterAcquireFailure" value="true" />
<property name="testConnectionOnCheckout" value="false" />
bean>
###########################
### C3P0 Connection Pool###
###########################
#hibernate.c3p0.max_size 2
#hibernate.c3p0.min_size 2
#hibernate.c3p0.timeout 5000
#hibernate.c3p0.max_statements 100
#hibernate.c3p0.idle_test_period 3000
#hibernate.c3p0.acquire_increment 2
#hibernate.c3p0.validate false
在hibernate.cfg.xml文件里面加入如下的配置:
<property name="hibernate.c3p0.max_size">20property>
<property name="hibernate.c3p0.min_size">5property>
<property name="hibernate.c3p0.timeout">120property>
<property name="hibernate.c3p0.max_statements">100property>
<property name="hibernate.c3p0.idle_test_period">120property>
<property name="hibernate.c3p0.acquire_increment">2property>
<property name="hibernate.c3p0.validate">trueproperty>
使用DBCP连接池时出现MySql 8小时断开连接的解决方法
修改l配置文件:
修改如下:
[html] view plain copy 在CODE上查看代码片派生到我的代码片
key="org.apache.struts.action.DATA_SOURCE" type="org.apache.commons.dbcp.BasicDataSource">
<set-property property="driverClassName" value="com.mysql.jdbc.Driver" />
<set-property property="description" value="wjjg" />
<set-property property="url" value="jdbc:mysql://localhost/wjjg?useUnicode=true&characterEncoding=GB2312" />
<set-property property="password" value="12345678" />
<set-property property="username" value="wjjg" />
<set-property property="maxActive" value="10" />
<set-property property="maxIdle" value="60000" />
<set-property property="maxWait" value="60000" />
<set-property property="defaultAutoCommit" value="true" />
<set-property property="defaultReadOnly" value="false" />
<set-property property="testOnBorrow" value="true"/>
<set-property property="validationQuery" value="select 1"/>
其中testOnBorrow 和 validationQuery 很重要。
testOnBorrow的意思是从数据库连接池中取得连接时,对其的有效性进行检查。
validationQuery 是用来检查的SQL语句,“select 1”执行较快,是一个不错的检测语句。
回顾
当测试人员反映到这个问题的时候,很快就锁定了Mysql八小时的问题,但是解决方案却费了我不小功夫,先是考虑到修改mysql配置文件肯定是不太合理的,弃之。
然后想了一下在一个servlet中写了个定时器,让它每两小时查一下数据库,运行了几天发现问题仍然存在,将定时器间隔时间修改为30分钟、3分钟仍然无济于事,异常照常出现,弃之。
在网上搜了一下解决方案也挺多,把
[java] view plain copy 在CODE上查看代码片派生到我的代码片
<set-property property="testOnBorrow" value="true"/>
<set-property property="validationQuery" value="select 1"/>
写入到配置文件中,运行报错,说bean中没有这两个属性,查看了一下原来是我用的c3p0连接池,而这个解决方案是针对DBCP连接池的。
最后在配置文件中,添加了
[java] view plain copy 在CODE上查看代码片派生到我的代码片
<property name="maxIdleTime"value="1800"/>
成功解决了问题。
相关问题解决
用数据库连接池解决org.hibernate.exception.JDBCConnectionException:could not execute query
数据库连接池解决
最近的一个项目在Hibernate使用C3P0的连接池,数据库为Mysql。开发测试没有问题,在运行中每个一段长的空闲时间就出现异常:
C3P0的连接池
自己的项目超时与数据库失去连接,线上是120s超时就没有连接采用的是这个配置
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="${COLLECTION_JDBC_URL}" />
<property name="username" value="${COLLECTION_JDBC_USERNAME}" />
<property name="password" value="${COLLECTION_JDBC_PASSWORD}" />
<property name="maxActive" value="#{env['jdbcMaxActive'] ?: 20}" />
<property name="maxIdle" value="#{env['jdbcMaxIdle'] ?: 10 }" />
<property name="minIdle" value="#{env['jdbcMinIdle'] ?: 2 }" />
<property name="initialSize" value="#{env['jdbcInitialSize'] ?: 20}" />
<property name="maxWait" value="#{env['jdbcMaxWait'] ?: 10000 }" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="#{env['jdbcTestOnReturn']?: false}" />
<property name="validationQuery" value="select 1" />
<property name="validationQueryTimeout" value="#{env['jdbcValidationQueryTimeout'] ?: 1}" />
<property name="testWhileIdle" value="#{env['jdbcTestWhileIdle']?: true}" />
<property name="timeBetweenEvictionRunsMillis" value="#{env['jdbcTimeBetweenEvictionRunsMillis']?: 600000}" />
<property name="minEvictableIdleTimeMillis" value="#{env['jdbcMinEvictableIdleTimeMillis'] ?: 600000}" />
<property name="numTestsPerEvictionRun" value="#{env['jdbcMaxActive'] ?: 20}" />
<property name="removeAbandoned" value="#{env['jdbcRemoveAbandoned']?: true}" />
<property name="removeAbandonedTimeout" value="#{env['jdbcRemoveAbandonedTimeout']?: 300}" />
<property name="logAbandoned" value="#{env['jdbcLogAbandoned']?: true}" />
bean>
dbcp类型,由于不让修改
wait_timeout=31536000
interactive_timeout=31536000
也无法定位问题,最后
<bean id="batchDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="${COLLECTION_JDBC_URL}" />
<property name="username" value="${COLLECTION_JDBC_USERNAME}" />
<property name="password" value="${COLLECTION_JDBC_PASSWORD}" />
<property name="initialSize" value="3" />
<property name="minIdle" value="3" />
<property name="maxActive" value="20" />
<property name="maxWait" value="5000" />
<property name="timeBetweenEvictionRunsMillis" value="90000" />
<property name="minEvictableIdleTimeMillis" value="1800000" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
最后更换连接池类型并且配置后再也没有出现断开不能重连的情况