链接数据库超时设置autoReconnect=true

1,问题现象:php

com.mysql.jdbc.CommunicationsException: The last packet successfully received from the server was58129 seconds ago.The last packet sent successfully to the server was 58129 seconds ago, which is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem. mysql

解决办法: 
若是链接闲置8小时 (8小时内没有进行数据库操做), mysql就会自动断开链接, 要重启tomcat. 
    不用hibernate的话, connection url加参数: autoReconnect=true 
    用hibernate的话, 加以下属性: 
        <property name="connection.autoReconnect">true</property> 
        <property name="connection.autoReconnectForPools">true</property> 
        <property name="connection.is-connection-validation-required">true</property>
 
    要是还用c3p0链接池: 
        <property name="hibernate.c3p0.acquire_increment">1</property> 
        <property name="hibernate.c3p0.idle_test_period">0</property> 
        <property name="hibernate.c3p0.timeout">0</property> 
        <property name="hibernate.c3p0.validate">true</property>

sql

 以上转载连接地址:http://blog.aqsc.cn/article.php?type=blog&itemid=1016数据库

2,另外:关于Mysql连接参数的说明以下:tomcat

mysql JDBC Driver服务器

经常使用的有两个,一个是gjt(Giant Java Tree)组织提供的mysql驱动,其JDBC Driver名称(JAVA类名)为:org.gjt.mm.mysql.Driverapp

详情请参见网站:http://www.gjt.org/socket

或在本网站下载mysql JDBC Driver(mm.jar)ide

另外一个是mysql官方提供的JDBC Driver,其JAVA类名为:com.mysql.jdbc.Driver网站

驱动下载网址:http://dev.mysql.com/downloads/,进入其中的MySQL Connector/J区域下载。

mysql JDBC URL格式以下:

jdbc:mysql://[host:port],[host:port].../[database][?参数名1][=参数值1][&参数名2][=参数值2]...

现只列举几个重要的参数,以下表所示:

参数名称 参数说明 缺省值 最低版本要求
user 数据库用户名(用于链接数据库)   全部版本
password 用户密码(用于链接数据库)   全部版本
useUnicode 是否使用Unicode字符集,若是参数characterEncoding设置为gb2312或gbk,本参数值必须设置为true false 1.1g
characterEncoding 当useUnicode设置为true时,指定字符编码。好比可设置为gb2312或gbk false 1.1g
autoReconnect 当数据库链接异常中断时,是否自动从新链接? false 1.1
autoReconnectForPools 是否使用针对数据库链接池的重连策略 false 3.1.3
failOverReadOnly 自动重连成功后,链接是否设置为只读? true 3.0.12
maxReconnects autoReconnect设置为true时,重试链接的次数 3 1.1
initialTimeout autoReconnect设置为true时,两次重连之间的时间间隔,单位:秒 2 1.1
connectTimeout 和数据库服务器创建socket链接时的超时,单位:毫秒。 0表示永不超时,适用于JDK 1.4及更高版本 0 3.0.1
socketTimeout socket操做(读写)超时,单位:毫秒。 0表示永不超时 0 3.0.1

对应中文环境,一般mysql链接URL能够设置为:

jdbc:mysql://localhost:3306/test?user=root&password=&useUnicode=true&characterEncoding=gbk&autoReconnect=true&failOverReadOnly=false

在使用数据库链接池的状况下,最好设置以下两个参数:

autoReconnect=true&failOverReadOnly=false

须要注意的是,在xml配置文件中,url中的&符号须要转义成&。好比在tomcat的server.xml中配置数据库链接池时,mysql jdbc url样例以下:

jdbc:mysql://localhost:3306/test?user=root&amp;password=&amp;useUnicode=true&amp;characterEncoding=gbk

&amp;autoReconnect=true&amp;failOverReadOnly=false

其余参数请参见mysql jdbc官方文档: MySQL Connector/J Documentation

相关文章
相关标签/搜索