---
title: "解决MySQL 5数据库连接超时问题"
author: "daniel_tu"
date: "2011-02-14T13:40:08Z"
tags: ["Linux", "MySQL", "Tomcat", "百度", "网络应用"]
categories: ["数据库"]
slug: "mysql-5"
draft: false
lastmod: "2011-02-14T13:40:08Z"
id: 905822
url: "https://daniel-tu.iteye.com/blog/905822"
---

最近碰到一个mysql5数据库的问题。就是一个标准的[servlet](http://whatis.ctocio.com.cn/searchwhatis/17/5949017.shtml) /tomcat网络应用，后台使用mysql数据库。问题是待机一晚上后，第二天早上第一次登录总是失败。察看日志发现如下错误：

 

   “[com](http://whatis.ctocio.com.cn/searchwhatis/307/5947307.shtml) .mysql.jdbc.exceptions.jdbc4.CommunicationsException:

        Communications [link](http://whatis.ctocio.com.cn/searchwhatis/206/5948706.shtml) failure

　　Last [packet](http://whatis.ctocio.com.cn/searchwhatis/385/6025885.shtml) sent to the [server](http://whatis.ctocio.com.cn/searchwhatis/497/5948997.shtml) was 0 ms ago.”

 　　经过一番调研，发现很多人都碰到过类似问题，但网上令人满意的回答并不多。mysql网站上的提问也很多，但并没有正确答案;百度知道上倒是有一个近似正确的回答。现将本人的解决办法总结一下：

　　上述问题是由mysql5数据库的配置引起的。mysql5将其连接的等待时间(wait\_timeout)缺省为8小时。在其客户程序中可以这样来查看其值：

 

      mysql﹥

　　mysql﹥ show global variables like 'wait\_timeout';

　　+---------------+---------+

　　| Variable\_name | Value |

　　+---------------+---------+

　　| wait\_timeout | 28800 |

　　+---------------+---------+

　　1 [row](http://whatis.ctocio.com.cn/searchwhatis/243/6093743.shtml) in [set](http://whatis.ctocio.com.cn/searchwhatis/23/5949023.shtml) (0.00 sec)

　　28800 seconds，也就是8小时。

　　如果在wait\_timeout秒期间内，数据库连接(java.sql.[Connection](http://whatis.ctocio.com.cn/searchwhatis/393/5947393.shtml) )一直处于等待状态，mysql5就将该连接关闭。这时，你的Java应用的连接池仍然合法地持有该连接的引用。当用该连接来进行数据库操作时，就碰到上述错误。这解释了为什么我的程序第二天不能登录 的问题。

　　你可能会想到在tomcat的数据源配置中有没有办法解决?的确，在jdbc连接url的配置中，你可以附上“autoReconnect=true”，但这仅对mysql5以前的版本起作用。增加“validation query”似乎也无济于事。

　　本人觉得最简单的办法，就是对症下药：既然问题是由mysql5的全局变量wait\_timeout的缺省值太小引起的，我们将其改大就好了。

　　查看mysql5的手册，发现对wait\_timeout的最大值分别是24天/365天(windows/linux)。以windows为 例，假设我们要将其设为21天，我们只要修改mysql5的配置文件“my.ini”(mysql5 installation dir)，增加一行：wait\_timeout=1814400

　　需要重新启动mysql5。

　　linux系统配置文件：/etc/my.cnf

　　测试显示问题解决了。