当前位置:Gxlcms > mysql > jdbc4.CommunicationsException:Communicationslinkfailure

jdbc4.CommunicationsException:Communicationslinkfailure

时间:2021-07-01 10:21:17 帮助过:40人阅读

mysql 查看空闲连接时间: mysql﹥ mysql﹥ show global variables like 'wait_timeout'; ------------------------ | Variable_name | Value | ------------------------ | wait_timeout | 28800 | //----默认空闲连接时间8个小时,超时将关闭该连接 --------



mysql 查看空闲连接时间:

mysql﹥

mysql﹥ show global variables like 'wait_timeout';

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

| Variable_name | Value |

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

| wait_timeout | 28800 | //---->默认空闲连接时间8个小时,超时将关闭该连接

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

1 row in set (0.00 sec)

此时如果,程序中的Connection一直保存着的话,(如使用连接池),超过8个小时后,再次使用Connection时会抛出

“com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure Last packet sent to the server was ****** ms ago.”

A:连接时加上属性autoReconnect=true,后面新版本,但在mysql5及以后,此方法无效

B:修改my.cnf(linux系统) 或者 my.ini(windows系统).wait_timeout的最大值分别是24天/365天(windows/linux)

修改方法:

假设我们要将其设为21天,我们只要修改mysql5的配置文件“my.ini”(mysql5 installation dir),

在[mysqld]后增加一行:wait_timeout=1814400

* 然后重启mysql服务.

但是:此方法有时个仍然不能满足需求.

C:此时建议使用C3P0连接池

JDBC eg:

public synchronized static DataSource createDataSource(String driver,String url,String username,String password) throws SQLException, ClassNotFoundException {

Class.forName(driver);

DataSource ds_unpooled = DataSources.unpooledDataSource(url,username,password);

Map overrides = new HashMap();
//当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3
overrides.put("acquireIncrement", 5);
overrides.put("minPoolSize", 5);
overrides.put("maxPoolSize", 10);
//overrides.put("initialPoolSize",cfg.getMaxPoolSize());
overrides.put("maxStatements", 10000);
//最大空闲时间,3600秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0
overrides.put("maxIdleTime", 3600 );
overrides.put("automaticTestTable", "C3P0TestTable");
overrides.put("testConnectionOnCheckin", true);
// 每60秒检查所有连接池中的空闲连接。Default: 0
overrides.put("idleConnectionTestPeriod",18000);
overrides.put("testConnectionOnCheckout", true);
//获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效
//保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试
//获取连接失败后该数据源将申明已断开并永久关闭。Default: false
overrides.put("breakAfterAcquireFailure", true);

//c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能
//通过多线程实现多个操作同时被执行。Default: 3
overrides.put("numHelperThreads", 10);

// create the PooledDataSource using the default configuration and our overrides
DataSource ds_pooled = DataSources.pooledDataSource( ds_unpooled, overrides );
return ds_pooled;
}

Hibernate eg:

hibernate.cfg.xml



jdbc:mysql://192.168.10.189:3306/gameforsky?useUnicode=true&characterEncoding=UTF-8
********
*************
com.mysql.jdbc.Driver
true
update
org.hibernate.connection.C3P0ConnectionProvider

5

30

1800

100

121

1
true


注:

A:直接用Code的方式未试过

B:Hibernate的方式试过,调通过.

C:Hibernate方式,出现过找不到org.hibernate.connection.C3P0ConnectionProvider类,这主要是由于Hibernate.jar里面没有该类,需完善包.

D:网上有的地说,需要c3p0的jar,经测试不需要.

人气教程排行