日期:2014-05-16  浏览次数:20478 次

数据库连接池和事务

背景

在高并发情况下,最近项目中出现了锁定量问题,可能原因是出库没有加上锁定量,入库没有减去锁定量,这样会导致不能正常的出库和入库。需要从几个方面来考虑

1、  业务过程中加锁存在问题

2、  事务没有正确提交

3、  提交了之前不合理的事务

4、  存在没有使用事务的业务

于是在数据库理论基础上,做了一些测试来推断问题所在。首先需要铺垫两方面内容:修改数据库my.ini文件,指定其连接最大等待时间。

默认设置如下:

需要修改wait_timeoutinteractive_timeout。在my.ini中,找到mysqld在其下增加

Wait_timeout=10

Interactive_timeout=10

修改数据库连接池,指定其回收连接最大等待时间。

removeAbandoned="true"

removeAbandonedTimeout="60"

logAbandoned="true"

这样只要两者不相等就可以分别模拟数据库连接关闭和连接池连接关闭情况下事务的执行情况。如下:

数据库连接关闭

用例1

插入test1,插入test2,插入test3,使数据库连接断开在插入test2处并捕获异常,

结论:

异常之后的所有操作都会报错,所有的操作都不能提交到数据库。错误信息如下:

1com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

 

The last packet successfullyreceived from the server was 37,281 milliseconds ago.  The last packet sent successfully to theserver was 0 milliseconds ago.

    atsun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

Caused by: java.net.SocketException: Software caused connection abort: recv failed

    atjava.net.SocketInputStream.socketRead0(Native Method)

2、构造preparedStatement

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.