现在的位置: 首页 > 综合 > 正文

mysql 8小时连接池异常

2016年11月26日 ⁄ 综合 ⁄ 共 1936字 ⁄ 字号 评论关闭
MySQL
的默认设置下,当一个连接的空闲时间超过8小时后,MySQL 就会断开该连接,而 c3p0
连接池则以为该被断开的连接依然有效。在这种情况下,如果客户端代码向 c3p0
连接池请求连接的话,连接池就会把已经失效的连接返回给客户端,客户端在使用该失效连接的时候即抛出异常。
解决这个问题的办法有三种:
1. 增加 MySQL 的 wait_timeout 属性的值。
修改 /etc/mysql/my.cnf
文件,在 [mysqld] 节中设置:
# Set a connection to wait
8
hours in idle status.

wait_timeout

=

86400

2. 减少连接池内连接的生存周期,使之小于上一项中所设置的 wait_timeout 的值。
修改 c3p0 的配置文件,设置:

# How long to keep unused connections around(in seconds)

# Note: MySQL times out idle connections after

8
hours(
28
,
800
seconds)

# so ensure this value is below MySQL idle timeout

cpool.maxIdleTime

=
25200

在 Spring 的配置文件中:

<
bean
id
="dataSource"


     class

="com.mchange.v2.c3p0.ComboPooledDataSource"
>


    

<
property
name
="maxIdleTime"
value
="${cpool.maxIdleTime}"

/>


    

<!--
other properties
-->


</
bean
>

3. 定期使用连接池内的连接,使得它们不会因为闲置超时而被 MySQL 断开。
修改 c3p0 的配置文件,设置:

# Prevent MySQL raise exception after a long idle time
cpool.preferredTestQuery
= 'SELECT 1 '
cpool.idleConnectionTestPeriod
= 18000
cpool.testConnectionOnCheckout
= true

修改 Spring 的配置文件:

<
bean 
id
="dataSource"

     class
="com.mchange.v2.c3p0.ComboPooledDataSource" >
    
< property name ="preferredTestQuery"
         value
="${cpool.preferredTestQuery}" />
    
< property name ="idleConnectionTestPeriod"
         value
="${cpool.idleConnectionTestPeriod}" />
    
< property name ="testConnectionOnCheckout"
         value
="${cpool.testConnectionOnCheckout}" />
    
<!-- other properties -->
</ bean >

附:以下 awk 脚本可以用以将 c3p0.properties 文件中的属性设置转换成为 applicationContext.xml 中 数据库连接池 DataSource 所需的 XML 元素形式。

#
!
/
bin
/
awk


BEGIN {

     FS

=
"
=
"
;


}

{

    

if

(
NF
==

2
)
{

        

if

((
x
=
index
($
1
,

"
.
"
))

>

0
)
{

             property_name

=
substr
($
1
,
x
+
1
,
length
($
1
));


         }

else
{

             property_name

=

$
1
;


         }

         printf

(
"
<property name="%s" value="${%s}"/>
"
,
property_name
,

$
1
);


     }

}


对MySQL server has gone away错误最常见的原因是服务器超时了并且关闭了连接。缺省地,如果没有事情发生,服务器在 8个小时后关闭连接。可在启动mysqld时通过设置wait_timeout变量改变时间限制。
      具体操作如下:
      在
MS-DOC 中 MySql 5.0/bin 目录下运行 :mysqld --verbose --help  ,得到 MySql
的参数配置。从中看到 wait_timeout = 28800 ,也就是8小时。如果超过 8 小时,没有对数据库进行操作,数据连接就会自动断开。

     解决方法一:
     可以在 my.ini 文件中启动项中添加  wait_timeout = 86400 任意值来设置等待时间。

 

 

抱歉!评论已关闭.