Home > Database > Mysql Tutorial > apache的BasicDataSource数据库连接问题

apache的BasicDataSource数据库连接问题

WBOY
Release: 2016-06-07 15:42:21
Original
1323 people have browsed it

调用创建连接时报错: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet successfully received from the server was 141,979 milliseconds ago. The last packet sent successfully to the server w

调用创建连接时报错:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet successfully received from the server was 141,979 milliseconds ago.  The last packet sent successfully to the server was 1 milliseconds ago.

这个问题找了好久,因为源码不是自己写的,对这个东西也不是太了解,因为催得急,因此也是很努力地找原因。apachecommons.dbcp这个包里的BasicDataSource的数据库连接使用的是连接池,在执行关闭连接操作的时候不是真正关闭连接,而只是把连接回收到连接池中,待再有需求时直接调用,但是默认的是不检查数据连接的有效性,可能有些连接因为超时等原因已经失效,所以有时候调用时可能得到的是个无效的连接,因此造成上述情况,修改方法:在初始化basicdatasource的时候,

BasicDataSource ds = new BasicDataSource();

……//其它初始化

ds.setTestOnBorrow(true);//调取连接时检查有效性

ds.setTestOnReturn(true);

ds.setTestWhileIdle(true);

ds.setValidationQuery("select 1 from dual");//验证连接有效性的方式,这步不能省

ps:不过在windows下一直没出现这种错,还有什么原因不甚明白。在windows下远程访问linux服务器上的数据库也会报错,可能错还是跟数据库有关的,不过linux上的数据库版本还有高点的嘛,难道是连接的jar文件?但是网上说5.0以上通用的嘛,不知道原因了。

 

此外还有两个参数,timeBetweenEvictionRunsMillis  minEvictableIdleTimeMillis 他们两个配合,可以持续更新连接池中的连接对象,当timeBetweenEvictionRunsMillis 大于0时,每过timeBetweenEvictionRunsMillis 时间,就会启动一个线程,校验连接池中闲置时间超过minEvictableIdleTimeMillis的连接对象。

 

具体设置与操作原理见:Configuring jdbc-pool for high-concurrency

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template