今天在工作过程中,遇到MySQL的程序,在跑一段时间后,就自动断开连接。出现的代码提示如下:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
The last packet successfully received from the server was56588 milliseconds ago.
The last packet sent successfully to the server was 56588 milliseconds 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.
大概意思是让:设置 autoReconnect=true。但是我在网上查询到:如果是mysql4以下,则只需要在datasource的url后加上autoReconnect=true便可以解决。但是我的版本是5,所以无法使用该方法。
上网查阅资料
MySQL服务器所支持的最大连接数是有上限的,因为每个连接的建立都会消耗内存,因此我们希望客户端在连接到MySQL Server处理完相应的操作后,应该断开连接并释放占用的内存。如果你的MySQL Server有大量的闲置连接,他们不仅会白白消耗内存,而且如果连接一直在累加而不断开,最终肯定会达到MySQL Server的连接上限数,这会报'too many connections'的错误。所以mysql在一定时长后默认断开连接并且释放掉sleep的连接线程,已保证mysql server不会出现连接数过满的情况。mysql默认8小时数据库断开的设置参数如下:
————————————————
原文链接:https://blog.csdn.net/qq383264679/article/details/79003590
1)interactive_timeout:
参数含义:服务器关闭交互式连接前等待活动的秒数。交互式客户端定义为在mysql_real_connect()中使用CLIENT_INTERACTIVE选项的客户端。
参数默认值:28800秒(8小时)
(2)wait_timeout:
参数含义:服务器关闭非交互连接之前等待活动的秒数。
在线程启动时,根据全局wait_timeout值或全局interactive_timeout值初始化会话wait_timeout值,取决于客户端类型(由mysql_real_connect()的连接选项CLIENT_INTERACTIVE定义)。
参数默认值:28800秒(8小时)
ps:如果在配置文件my.cnf中只设置参数wait_timeout=100,则重启服务器后进入,执行:Mysql> show variables like “%timeout%”;会发现参数设置并未生效,仍然为28800(即默认的8个小时)。查询资料后,要同时设置interactive_timeout和wait_timeout才会生效。
查询自己的参数设置:
所以,可以设置这两个参数的时间,
set global interactive_timeout=31536000;
set global wait_timeout=31536000;
来解决8小时错误问题,但不推荐这个
另一种方式,通过配置文件,来检测连接。这里引用网上的讲解:
-
将testConnectionOnCheckout 设为 false
-
将testConnectionOnCheckin 设为 true
-
将idleConnectionTestPeriod 设为 30,这个数字要根据项目情况设定,比8小时小就好
spring中的配置:
<property name="idleConnectionTestPeriod" value="60" />
<property name="testConnectionOnCheckin" value="true" />
<property name="testConnectionOnCheckout" value="false"/>
properties文件中的配置
#Unreasonable values of initialPoolSize will be ignored, and minPoolSize will be used instead.
jdbc.c3p0.initialPoolSize=10
jdbc.c3p0.minPoolSize=10
jdbc.c3p0.maxPoolSize=100
#maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool.
jdbc.c3p0.maxIdleTime=3600
testConnectionOnCheckout
If true, an operation will be performed at every connection checkout to verify that the connection is valid.
设置为true,所有的连接都将检测其有效性,会影响性能,所以将其设置为false
testConnectionOnCheckin
If true, an operation will be performed asynchronously at every connection checkin to verify that the connection is valid.
设置为true,异步检测连接的有效性
idleConnectionTestPeriod(单位是秒,不是毫秒)
If this is a number greater than 0, c3p0 will test all idle, pooled but unchecked-out connections, every this number of seconds.
每隔多少秒c3p0检测连接的有效性