Sri*_*a N 3 java mysql spring hibernate connection-pooling
如果我在空闲一段时间后启动我的应用程序,我曾经得到以下错误.(我使用Spring + Hibernate + MySQL作为DB)
ERROR [org.hibernate.util.JDBCExceptionReporter]The last packet successfully received from the server was 74,188,684 milliseconds ago.
The last packet sent successfully to the server was 74,188,685 milliseconds ago. 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.
org.hibernate.exception.JDBCConnectionException: could not execute query
Run Code Online (Sandbox Code Playgroud)
我在下面添加了我的servlet-context.xml解决了这个问题.
<beans:property name="validationQuery" value="SELECT 1"/>
Run Code Online (Sandbox Code Playgroud)
我在这里问了这个问题,这个问题对解决方案更具体.我需要知道为什么我会收到这个错误.
我在上面的链接中尝试了第1个(使用autoReconnect = true配置连接字符串)和第3个选项(配置连接池以测试连接的有效性)并且都工作了.我仍然不明白为什么在第一时间我得到了错误.
这是我更新的servlet-context.xml文件,我使用ApacheDBCP进行连接池.
<beans:bean id="MyID" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<beans:property name="url" value="jdbc:mysql://localhost:17761/myDB"/>
<beans:property name="username" value="myname"/>
<beans:property name="password" value="mypwd"/>
<beans:property name="maxIdle" value="5"/>
<beans:property name="maxActive" value="20"/>
<beans:property name="minIdle" value="5"/>
<beans:property name="validationQuery" value="SELECT 1"/>
</beans:bean>
Run Code Online (Sandbox Code Playgroud)
这是一些连接到期问题吗?请帮我理解.
以下是用于说明正在发生的事件的事件流程:
autoReconnect = true的原因是什么,以及测试连接有效性的池是否有效,是指示调用系统测试此情况的连接,如果发生这种情况则再次尝试.
至于验证查询是否会影响性能:理论上它是使用连接来做某事.在实践中,某些东西是如此微不足道,以至于它在整个系统环境中的影响可以忽略不计.
[编辑]
在这种情况下,Apache DBCP是挂在连接上的连接池,但是您不希望DBCP在每次调用后关闭连接.连接池的目的是为下次调用保持连接,因为创建连接很昂贵.池维护的连接对象由实际数据库连接支持,数据库是在空闲超时期限后关闭该实际连接的数据库.请注意,关闭空闲连接的超时是在数据库上配置的,而不是在连接池上配置的.因此,DBCP无法知道连接是否已关闭,除非它实际上尝试连接它.这就是您需要验证查询的原因.