C3P0连接池+MySQL的配置及wait_timeout问题的解决方法_MySQL

 一、配置环境

spring4.2.4+mybatis3.2.8+c3p0-0.9.1.2+Mysql5.6.24

二、c3p0的配置详解及spring+c3p0配置

1.配置详解

官方文档 : http://www.mchange.com/projects/c3p0/index.html

3 30 1000 falseTestfalse100nullfalse6036015100 3rootpassword select id from test where id=1300falsetruerootfalse

2.spring+mybatis+c3p0的基本配置

     

初始化基本配置信息如下:

Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge26l9jv0ov961czeg8w|a2f51c, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge26l9jv0ov961czeg8w|a2f51c, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://192.168.6.24:3306/ETeam, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]

三、遇到的问题:

1.问题log:

严重: Servlet.service() for servlet [ETeam] in context with path [/ETeam] threw exception [Request processing failed; nested exception is org.springframework.dao.RecoverableDataAccessException: ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 55,518,630 milliseconds ago. The last packet sent successfully to the server was 55,518,631 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. ### The error may exist in com/mango/mapper/ProductMapper.java (best guess) ### The error may involve defaultParameterMap ### The error occurred while setting parameters ### SQL: SELECT * FROM product ### Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 55,518,630 milliseconds ago. The last packet sent successfully to the server was 55,518,631 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. ; SQL []; The last packet successfully received from the server was 55,518,630 milliseconds ago. The last packet sent successfully to the server was 55,518,631 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.; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 55,518,630 milliseconds ago. The last packet sent successfully to the server was 55,518,631 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.] with root cause java.net.SocketException: Connection reset by peer: socket write error at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113) at java.net.SocketOutputStream.write(SocketOutputStream.java:159) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140) at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3634) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2460) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2551) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861) at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1192) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.execute(NewProxyPreparedStatement.java:989) at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:62) at com.sun.proxy.$Proxy138.execute(Unknown Source) at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:59) at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:73) at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:60) at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:267) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:137) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:96) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:77) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:108) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:102) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:358) at com.sun.proxy.$Proxy357.selectList(Unknown Source) at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:198) at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:119) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:63) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52) at com.sun.proxy.$Proxy376.getProductIndex(Unknown Source) at com.mango.service.impl.ProductServiceImpl.getProductIndex(ProductServiceImpl.java:25) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:280) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) at com.sun.proxy.$Proxy377.getProductIndex(Unknown Source) at com.mango.controller.PageController.index(PageController.java:57) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860) at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at com.mango.filter.BaseFilter.doFilter(BaseFilter.java:34) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:134) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.sitemesh.webapp.contentfilter.ContentBufferingFilter.bufferAndPostProcess(ContentBufferingFilter.java:169) at org.sitemesh.webapp.contentfilter.ContentBufferingFilter.doFilter(ContentBufferingFilter.java:126) at org.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:120) at org.sitemesh.config.ConfigurableSiteMeshFilter.doFilter(ConfigurableSiteMeshFilter.java:163) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1813) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745)

从问题log中

The last packet successfully received from the server was 55,518,630 milliseconds ago. The last packet sent successfully to the server was 55,518,631 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.; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 55,518,630 milliseconds ago. The last packet sent successfully to the server was 55,518,631 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.] with root cause

很容易看出是由于wait_timeout(服务器关闭非交互连接之前等待活动的秒数)造成的。MySQL会根据wait_timeout设置每个空闲连接的超时时间,时间到了就会断开。

2.查看mysql的wait_timeout

mysql> show global variables like 'wait_timeout';+---------------+-------+| Variable_name | Value |+---------------+-------+| wait_timeout | 28800 |+---------------+-------+1 row in set

默认设置28800秒,即8小时,明显连接时间55,518,630 milliseconds超过了mysql数据库设置的wait_timeout

修改命令:mysql>set global wait_timeout=28800;

3.问题解决

1)log中也给了解决方案:

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.

AI建筑知识问答 AI建筑知识问答

用人工智能ChatGPT帮你解答所有建筑问题

AI建筑知识问答 22 查看详情 AI建筑知识问答

你应该考虑到期和/或有效性测试连接在应用程序中使用之前,增加服务器为客户机超时配置值,或使用连接器/ J连接属性“autoReconnect = true”来避免这个问题。

2)后两种方法显然不太实用

增加mysql数据库的超时时间,由于最大超时时间是2147483一年,不可无限制增加,再说也不应该随便增加。’autoReconnect=true’如果使用的时候reconnect会影响效率,而且据说mysql5以上无效(本人没试),而且官方也不建议http://bugs.mysql.com/bug.php?id=5020

3)采用c3p0提供的方案

可参考:http://www.mchange.com/projects/c3p0/index.html#configuring_connection_testing

The most reliable time to test Connections is on check-out. But this is also the most costly choice from a client-performance perspective. Most applications should work quite reliably using a combination of idleConnectionTestPeriod and testConnectionOnCheckin. Both the idle test and the check-in test are performed asynchronously, which can lead to better performance, both perceived and actual.
For some applications, high performance is more important than the risk of an occasional database exception. In its default configuration, c3p0 does no Connection testing at all. Setting a fairly long idleConnectionTestPeriod, and not testing on checkout and check-in at all is an excellent, high-performance approach.

 最可靠的是退出时间测试连接。但这也是最昂贵的从客户端性能的角度选择。大多数应用程序应该使用idleConnectionTestPeriod和testConnectionOnCheckin相当可靠。闲置的测试和登记测试是异步执行的,这可能导致更好的性能,感知和实际。

对于某些应用程序,高性能比偶尔的风险更重要数据库异常。在默认配置中,c3p0没有连接测试。设置一个相当长的idleConnectionTestPeriod,而不是测试是一个很好的检验和登记,高性能的方法。

考虑再三可以如下设置

设置c3p0中连接池内连接的生存周期(idleConnectionTestPeriod)小于数据库中的wait_timeout的值

 

四、c3p0中用到的定时任务是Java中的Timer实现的,实际上是TimerThread的定时执行

checkidle源码

BasicResourcePool.java

// this is run by a single-threaded timer, so we don't have // to worry about multiple threads executing the task at the same // time class CheckIdleResourcesTask extends TimerTask { public void run() { try { //System.err.println("c3p0-JENNIFER: refurbishing idle resources - " + new Date() + " [" + BasicResourcePool.this + "]"); if (Debug.DEBUG && Debug.TRACE >= Debug.TRACE_MED && logger.isLoggable(MLevel.FINER)) logger.log(MLevel.FINER, "Refurbishing idle resources - " + new Date() + " [" + BasicResourcePool.this + "]"); synchronized ( BasicResourcePool.this ) { checkIdleResources(); } } catch ( ResourceClosedException e ) // one of our async threads died { //e.printStackTrace(); if ( Debug.DEBUG ) { if ( logger.isLoggable( MLevel.FINE ) ) logger.log( MLevel.FINE, "a resource pool async thread died.", e ); } unexpectedBreak(); } } }

最终测试:

C3P0PooledConnectionPool.java

private void testPooledConnection(Object resc) throws Exception { PooledConnection pc = (PooledConnection) resc; Throwable[] throwableHolder = EMPTY_THROWABLE_HOLDER; int status; Connection conn = null; Throwable rootCause = null; try { //we don't want any callbacks while we're testing the resource pc.removeConnectionEventListener( cl ); conn = pc.getConnection(); //checkout proxy connection // if this is a c3p0 pooled-connection, let's get underneath the // proxy wrapper, and test the physical connection sometimes. // this is faster, when the testQuery would not otherwise be cached, // and it avoids a potential statusOnException() double-check by the // PooledConnection implementation should the test query provoke an // Exception Connection testConn; if (scache != null) //when there is a statement cache... { // if it's the slow, default query, faster to test the raw Connection if (testQuery == null && connectionTesterIsDefault && c3p0PooledConnections) testConn = ((AbstractC3P0PooledConnection) pc).getPhysicalConnection(); else //test will likely be faster on the proxied Connection, because the test query is probably cached testConn = conn; } else //where there's no statement cache, better to use the physical connection, if we can get it { if (c3p0PooledConnections) testConn = ((AbstractC3P0PooledConnection) pc).getPhysicalConnection(); else testConn = conn; } if ( testQuery == null ) status = connectionTester.activeCheckConnection( testConn ); else { if (connectionTester instanceof UnifiedConnectionTester) { throwableHolder = thp.getThrowableHolder(); status = ((UnifiedConnectionTester) connectionTester).activeCheckConnection( testConn, testQuery, throwableHolder ); } else if (connectionTester instanceof QueryConnectionTester) status = ((QueryConnectionTester) connectionTester).activeCheckConnection( testConn, testQuery ); else { // System.err.println("[c3p0] WARNING: testQuery '" + testQuery + // "' ignored. Please set a ConnectionTester that implements " + // "com.mchange.v2.c3p0.advanced.QueryConnectionTester, or use the " + // "DefaultConnectionTester, to test with the testQuery."); logger.warning("[c3p0] testQuery '" + testQuery + "' ignored. Please set a ConnectionTester that implements " + "com.mchange.v2.c3p0.QueryConnectionTester, or use the " + "DefaultConnectionTester, to test with the testQuery."); status = connectionTester.activeCheckConnection( testConn ); } } } catch (Exception e) { if (Debug.DEBUG) logger.log(MLevel.FINE, "A Connection test failed with an Exception.", e); //e.printStackTrace(); status = ConnectionTester.CONNECTION_IS_INVALID; // System.err.println("rootCause -->"); // e.printStackTrace(); rootCause = e; } finally { if (rootCause == null) rootCause = throwableHolder[0]; else if (throwableHolder[0] != null && logger.isLoggable(MLevel.FINE)) logger.log(MLevel.FINE, "Internal Connection Test Exception", throwableHolder[0]); if (throwableHolder != EMPTY_THROWABLE_HOLDER) thp.returnThrowableHolder( throwableHolder ); ConnectionUtils.attemptClose( conn ); //invalidate proxy connection pc.addConnectionEventListener( cl ); //should we move this to CONNECTION_IS_OKAY case? (it should work either way) } switch (status) { case ConnectionTester.CONNECTION_IS_OKAY: break; //no problem, babe case ConnectionTester.DATABASE_IS_INVALID: rp.resetPool(); //intentional cascade... case ConnectionTester.CONNECTION_IS_INVALID: Exception throwMe; if (rootCause == null) throwMe = new SQLException("Connection is invalid"); else throwMe = SqlUtils.toSQLException("Connection is invalid", rootCause); throw throwMe; default: throw new Error("Bad Connection Tester (" + connectionTester + ") " + "returned invalid status (" + status + ")."); } }

以上所述是小编给大家介绍的C3P0连接池+MySQL的配置及wait_timeout问题的解决方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/424797.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月7日 11:00:23
下一篇 2025年11月7日 11:03:13

相关推荐

  • PHP怎样防止SQL注入 PHP防SQL注入的5个关键措施

    防止sql注入的核心方法是使用预处理语句和参数化查询,结合输入验证、输出编码、最小权限原则等措施。1. 使用预处理语句(如pdo或mysqli)将sql结构与数据分离,防止恶意数据被当作sql执行;2. 对所有用户输入进行严格验证,确保其格式、类型和长度符合预期,例如使用intval()或filte…

    2025年12月10日 好文分享
    000
  • PHP中的索引优化:如何提高数据库查询性能

    索引是提升数据库查询速度的关键。它像书的目录一样,帮助数据库快速定位数据,避免全表扫描。常见类型包括主键索引、唯一索引、普通索引和复合索引。选择合适字段建立索引应优先考虑频繁查询条件、连接字段和排序分组字段;不适合加索引的情况包括重复率高、很少查询或小数据量表的字段。使用复合索引时需遵循最左匹配原则…

    2025年12月10日
    000
  • PHP中的身份验证:如何在PHP中实现用户身份验证

    用户身份验证在php开发中至关重要,其核心流程分为四步:用户提交信息、系统查询数据库、密码比对、创建session;密码必须用password_hash()加密存储,并用password_verify()验证;使用session维护登录状态时应设置$_session标识,并在登出时清除;安全方面需防…

    2025年12月10日
    000
  • PHP中的安全防护:如何在PHP中防止常见安全漏洞

    要保障php应用安全,需重点防范sql注入、xss攻击、csrf攻击及文件上传风险。1. 防止sql注入:使用pdo或mysqli扩展的预处理语句,通过参数绑定方式传入用户输入,避免拼接sql字符串;2. 过滤和转义输出:使用htmlspecialchars()函数防止xss攻击,针对不同上下文采用…

    2025年12月10日
    000
  • CentOS 8编译安装PHP8.0全流程解析

    在centos 8上编译安装php8.0需要以下步骤:1.安装必要的工具和依赖库;2.下载并解压php8.0源码;3.配置编译选项;4.编译和安装。通过这些步骤,你可以在centos 8上成功编译安装php8.0,并根据需求定制编译选项以优化性能。 引言 在当今的Web开发世界中,PHP仍然是一个不…

    2025年12月10日
    000
  • PHP中的Docker部署:如何使用容器化运行PHP应用

    部署php应用时使用docker能简化环境配置并提升一致性。1.安装docker及docker compose并确认版本;2.选择合适的php基础镜像如php:8.2-fpm或php:8.2-apache,或基于alpine的轻量镜像;3.编写dockerfile定制环境,包括安装扩展、引入comp…

    2025年12月10日
    000
  • PHP中的服务监控:如何监控PHP应用的运行状态

    要对php应用进行有效监控,首先应建立健康检查接口以确认服务可用性,其次关注性能指标如执行时间和资源消耗,同时监控错误日志以捕捉致命错误和警告,并对第三方依赖进行健康检查。1. 建议创建轻量的健康检查接口,返回状态码或json结构,并通过外部工具定期访问,触发异常报警;2. 通过记录请求耗时和内存使…

    2025年12月10日
    000
  • PHP中的数据库连接:如何使用PHP连接和操作MySQL数据库

    php开发中连接mysql数据库需使用mysqli或pdo扩展,步骤为:1.通过mysqli创建连接并检测错误;2.执行sql查询或操作并处理结果;3.使用预处理语句防止sql注入;4.操作完成后关闭连接释放资源。此外应将配置信息独立管理、避免暴露数据库错误、验证用户输入以确保安全性。 在PHP开发…

    2025年12月10日
    000
  • PHP中的PDO扩展:如何安全地使用PDO操作数据库

    使用pdo安全操作数据库需遵循四个步骤:一、连接数据库时关闭错误提示,使用环境变量存储敏感信息,并设置字符集为utf8mb4;二、通过预处理语句防止sql注入,使用绑定参数而非拼接字符串;三、合理处理查询结果并使用事务确保数据一致性,异常时回滚事务;四、避免拼接sql、验证动态表名字段名合法性,统一…

    2025年12月10日
    000
  • PHP中的表单验证:如何在PHP中验证用户输入的表单数据

    表单验证在php网站开发中至关重要,因为用户输入不可靠,可能引发错误或安全漏洞。1. 使用filter_var函数可实现基础验证,如邮箱、url判断及数字过滤,简洁且无需手动编写正则;2. 通过empty()或!isset()检查必填字段,确保关键信息完整,同时可批量验证多个字段;3. 对特殊字段设…

    2025年12月10日
    000
  • PHP中的并发控制:如何在PHP中处理并发请求

    在php开发中处理高并发请求需采取多种策略。1. 使用文件锁(flock)控制并发写入,适用于低并发场景,通过lock_ex和lock_sh实现排他或共享锁定;2. 利用数据库事务和行锁确保数据一致性,通过select … for update锁定数据行,避免冲突;3. 使用redis实…

    2025年12月10日
    000
  • PHP中的事务处理:如何在MySQL中实现原子性操作

    在php中操作mysql事务需使用pdo或mysqli并遵循acid特性。事务是一组sql语句的执行单元,满足原子性、一致性、隔离性和持久性。开启事务需关闭自动提交并调用begintransaction()。成功则commit()提交,失败则rollback()回滚。示例代码通过try-catch结…

    2025年12月10日
    000
  • PHP中的预处理语句:如何防止SQL注入攻击

    sql注入是攻击者通过输入恶意sql代码操纵数据库,而预处理语句通过分离sql结构与数据参数有效防止此类攻击。1. 预处理先发送sql模板供数据库解析,后传参数并作为纯文本处理,不参与语法解析,从而避免注入;2. php中使用pdo或mysqli扩展实现预处理,推荐用pdo因其支持多数据库;3. 可…

    2025年12月10日
    000
  • php7怎样进行数据库事务处理?php7的PDO事务方法有哪些?

    在 php7 中推荐使用 pdo 进行数据库事务处理,其核心方法包括:1. 调用 begintransaction() 关闭自动提交以开启事务;2. 使用 commit() 提交事务使更改生效;3. 通过 rollback() 回滚事务撤销错误操作;4. 注意选择支持事务的数据库引擎如 innodb…

    2025年12月10日
    000
  • php如何实现数据过滤?php安全输入处理的方法

    在php开发中保障网站安全需遵循数据过滤与输入处理的四大要点:一、始终不信任用户输入,利用filter_input()和filter_var()验证格式;二、防止sql注入应使用预处理语句如pdo或mysqli;三、防御xss攻击需用htmlspecialchars()对输出内容转义;四、严格控制富…

    2025年12月10日 好文分享
    000
  • php开发是做什么的 php开发的主要工作内容和应用场景

    php开发是利用php语言进行网站和网络应用的开发工作。具体包括:1) 编写和维护php代码,2) 设计数据库结构,3) 优化网站性能,4) 与前端开发人员和设计师合作,确保产品质量和用户体验。 PHP开发是做什么的?简单来说,PHP开发就是利用PHP语言进行网站和网络应用的开发工作。PHP是一种广…

    2025年12月10日
    000
  • PHP7安全编程指南:防范常见漏洞与攻击

    php7应用安全性需开发者主动防范。1.防止sql注入:使用参数化查询(如pdo或mysqli)避免恶意输入篡改sql逻辑;2.过滤与转义输出:根据上下文使用htmlspecialchars、rawurlencode等函数防止xss攻击;3.文件上传安全:白名单限制扩展名、检测真实mime类型、重命…

    2025年12月10日
    000
  • php全文检索的实现方法

    实现 php 全文检索的关键在于根据项目规模与需求选择合适方案,1. 对于中小型项目可使用 mysql 的 fulltext 索引,通过创建全文索引并使用 match … against 语句进行搜索,优势是集成简单但功能有限;2. 大型项目或需高性能复杂检索时推荐 elasticsea…

    2025年12月10日
    000
  • 如何检查PHP变量是否为生成器?

    要检查php变量是否为生成器,使用instanceof操作符是最佳方法:return $var instanceof generator;生成器在处理大数据集时非常有用,如逐条处理数据库记录或逐行读取大文件,但需注意其单向状态和性能权衡。 检查PHP变量是否为生成器,这个问题看似简单,实则隐藏着许多…

    2025年12月10日
    000
  • php如何实现数据导出?php导出csv文件的步骤是什么?

    php导出数据到csv需注意4个关键点。1.准备好数据源,如数据库查询结果或数组;2.设置响应头触发浏览器下载,如header(‘content-type:text/csv;charset=utf-8’)和header(‘content-disposition:a…

    2025年12月10日
    000

发表回复

登录后才能评论
关注微信