MySQLNonTransientConnectionException:连接太多

Posted

技术标签:

【中文标题】MySQLNonTransientConnectionException:连接太多【英文标题】:MySQLNonTransientConnectionException: Too many connections 【发布时间】:2011-07-13 13:44:14 【问题描述】:

我的 Spring-MVC 应用程序在浏览站点时有时会崩溃,我从日志中得到的错误消息如下所示。我完全不知道是什么原因造成的,并且非常感谢任何能引导我走向正确方向的提示。

    SEVERE: Servlet.service() for servlet HS threw exception
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection,  message from server: "Too many connections"
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
    at com.mysql.jdbc.Util.getInstance(Util.java:382)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1116)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2338)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2371)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2163)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:794)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.GeneratedConstructorAccessor56.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:378)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
    at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
    at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
    at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1556)
    at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1545)
    at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388)
    at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
    at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:81)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
    at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
    at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1577)
    at org.hibernate.loader.Loader.doQuery(Loader.java:696)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
    at org.hibernate.loader.Loader.doList(Loader.java:2232)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)
    at org.hibernate.loader.Loader.list(Loader.java:2124)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401)
    at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363)
    at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1149)
    at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
    at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:921)
    at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:1)
    at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
    at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
    at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:912)
    at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:904)
    at se.hs.daos.UserDAOImpl.findByName(UserDAOImpl.java:42)
    at se.hs.controllers.LoginController.checkPassword(LoginController.java:20)
    at se.hs.pagecontrollers.LoginPageController.submitForm(LoginPageController.java:26)
    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:616)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:636)

我的 UserDaoImpl 是什么样子的:

package se.hs.daos;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import se.hs.models.User;

public class UserDAOImpl extends HibernateDaoSupport implements UserDAO 

    private ApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath*:applicationContext.xml");
    private SessionFactory sessionFactory = (SessionFactory) context
            .getBean("mySessionFactory");
    private HibernateTemplate hibernateTemplate = new HibernateTemplate(
            sessionFactory, true);

    public void saveUser(User user) 
        hibernateTemplate.save(user);
    

    public User getUserById(Integer id) 

        User userFromDB = hibernateTemplate.get(User.class, id);
        return userFromDB;
    

    public void removeUser(User user) 
        hibernateTemplate.delete(user);
    

    public User findByName(String name) 

        String query = "SELECT u.userId FROM User u WHERE u.userName='" + name
                + "'";

        @SuppressWarnings("unchecked")
        List<Integer> list = hibernateTemplate.find(query);

        User userFromDB = null;

        if (list.size() > 0) 
            userFromDB = getUserById(list.get(0));
        

        return userFromDB;
    


更新:

    exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: Cannot release connection; uncategorized SQLException for SQL [???]; SQL state [null]; error code [0]; Already closed.; nested exception is java.sql.SQLException: Already closed.
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause

org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: Cannot release connection; uncategorized SQLException for SQL [???]; SQL state [null]; error code [0]; Already closed.; nested exception is java.sql.SQLException: Already closed.
    org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
    org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
    org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
    org.springframework.orm.hibernate3.HibernateAccessor.convertJdbcAccessException(HibernateAccessor.java:424)
    org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:410)
    org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
    org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
    org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:683)
    se.hsr.daos.InfoTextDAOImpl.saveInfoText(InfoTextDAOImpl.java:26)
    se.hsr.controllers.InfoTextController.saveInfoText(InfoTextController.java:31)
    se.hsr.pagecontrollers.InfoTextPageController.submitForm(InfoTextPageController.java:35)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:616)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause

java.sql.SQLException: Already closed.
    org.apache.commons.dbcp.PoolableConnection.close(PoolableConnection.java:114)
    org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.close(PoolingDataSource.java:191)
    org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.closeConnection(LocalDataSourceConnectionProvider.java:95)
    org.hibernate.jdbc.ConnectionManager.closeConnection(ConnectionManager.java:474)
    org.hibernate.jdbc.ConnectionManager.aggressiveRelease(ConnectionManager.java:429)
    org.hibernate.jdbc.ConnectionManager.afterStatement(ConnectionManager.java:304)
    org.hibernate.jdbc.AbstractBatcher.closePreparedStatement(AbstractBatcher.java:572)
    org.hibernate.jdbc.AbstractBatcher.closeStatement(AbstractBatcher.java:291)
    org.hibernate.id.insert.AbstractReturningDelegate.releaseStatement(AbstractReturningDelegate.java:82)
    org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:60)
    org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2176)
    org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2656)
    org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
    org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
    org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321)
    org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
    org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
    org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
    org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
    org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
    org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
    org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:563)
    org.hibernate.impl.SessionImpl.save(SessionImpl.java:551)
    org.hibernate.impl.SessionImpl.save(SessionImpl.java:547)
    org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:686)
    org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:1)
    org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
    org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
    org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:683)
    se.hsr.daos.InfoTextDAOImpl.saveInfoText(InfoTextDAOImpl.java:26)
    se.hsr.controllers.InfoTextController.saveInfoText(InfoTextController.java:31)
    se.hsr.pagecontrollers.InfoTextPageController.submitForm(InfoTextPageController.java:35)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:616)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

【问题讨论】:

【参考方案1】:

这意味着 DB SQL 服务器连接不足。服务器有一个配置参数,指定允许的最大连接数。

这通常表示连接没有被关闭。您是否在代码中从 Hibernate 请求 Connection 对象?

短期内,您可以增加最大连接数,直到这个问题得到解决。

【讨论】:

感谢您的回复。我按照您的建议进行了操作,并将最大连接数更改为 2000。现在发生另一个错误:UncategorizedSQLException:休眠操作:无法释放连接(如果完整的堆栈跟踪相关,请告诉我,我会上传它。)这导致我相信增加最大连接数不是问题所在,知道可能是什么吗? 是的,堆栈跟踪会有所帮助。您也可以尝试将其添加到休眠配置:hibernate.connection.release_mode=after_statement 这不是永久解决方案,但如果这有助于我们知道这是一个配置问题。【参考方案2】:

如果您增加连接数可能会修复它,但将来仍有可能发生同样的异常。

确保您已在数据库配置xml 文件中定义&lt;property name="maxIdle" value="1" /&gt;。当我定义&lt;property name="maxIdle" value="1" /&gt; 时,我也遇到了同样的问题,它解决了我的问题。

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/crm" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="initialSize" value="10" />
        <property name="maxActive" value="15" />
        <property name="maxWait" value="5000" />
        <property name="maxIdle" value="1" />

    </bean>

【讨论】:

【参考方案3】:

在MySql中,检查最大并发连接数

SHOW VARIABLES LIKE "max_connections";

默认为 151 (0 - 150)。然后通过

更改最大并发连接数
SET GLOBAL max_connections = 250;

这解决了我的问题。

【讨论】:

【参考方案4】:

在上面的标签中,这一行很重要

 <property name="maxIdle" value="1" />

会起作用,因为它只允许 AJAX 或 DB 请求的一个连接

【讨论】:

以上是关于MySQLNonTransientConnectionException:连接太多的主要内容,如果未能解决你的问题,请参考以下文章