mysql automatically disconnects the connection solution after the idle time of the mysql connection exceeds 8 hours

  • 2020-05-15 02:16:44
  • OfStack

There are three ways to solve this problem:

1. Increase the value of wait_timeout property of MySQL.

Modify/etc/mysql/my cnf file, in [mysqld] section Settings:

# Set a connection to wait 8hours in idle status.
wait_timeout =86400
Related parameters, in red
mysql > show variables like '%timeout%';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| wait_timeout | 28800 |
+--------------------------+-------+
At the same time, only one of these two parameters is in effect. Which parameter is in effect depends on the connection parameter specified by the user when connecting, and wait_timeout is used by default. My suggestion is to modify both parameters so as not to cause unnecessary trouble.

The default value for these two parameters is 8 hours (60*60*8=28800). I tested changing these two parameters to 0, and the result was unexpected. The system automatically set the value to 0. In other words, the value cannot be set to permanent.
Set these two parameters to 24 hours (60*60*24=604800).
set interactive_timeout=604800;
set wait_timeout=604800;

2. Reduce the lifetime of connections in the connection pool to less than the value of wait_timeout set in item 1 above.
Modify the configuration file of c3p0, set:

# How long to keep unused connections around(in seconds)
# Note: MySQL times out idle connections after 8hours(28,800seconds)
# so ensure this value is below MySQL idle timeout
cpool.maxIdleTime=25200
In the Spring configuration file:
 
<bean id="dataSource" 
class="com.mchange.v2.c3p0.ComboPooledDataSource"> 
<property name="maxIdleTime"value="${cpool.maxIdleTime}"/> 
<!--other properties --> 
</bean> 


3. Regularly use connections in the connection pool so that they are not disconnected by MySQL due to idle timeout.
Modify the configuration file of c3p0, set:

# Prevent MySQL raise exception after a long idle timecpool.preferredTestQuery='SELECT 1'cpool.idleConnectionTestPeriod=18000cpool.testConnectionOnCheckout=true
Modify the configuration file of 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> 

Related articles: