0

我正在为我当前的网站使用 Hibernate 4 和 mysql,在我尝试在 2 个 Web 浏览器的选项卡中多次刷新页面后,服务器关闭并显示错误日志:

ERROR: Data source rejected establishment of connection,  message from server: "Too many connections"
org.hibernate.exception.JDBCConnectionException: Could not open connection
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:68)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304)
    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
    at hibernate.dao.StockDao.getWarehouseInStock(StockDao.java:132)
    at Utils.Common.updateStockHistorical(Common.java:501)
    at Controller.StockServlet.processRequest(StockServlet.java:67)
    at Controller.StockServlet.doPost(StockServlet.java:116)
    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 Controller.ServletFilter.doFilter(ServletFilter.java:134)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    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:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879)
    at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:600)
    at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1703)
    at java.lang.Thread.run(Thread.java:722)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection,  message from server: "Too many connections"
    at sun.reflect.GeneratedConstructorAccessor70.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1014)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1104)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2412)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2445)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2230)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.GeneratedConstructorAccessor62.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
    at java.sql.DriverManager.getConnection(DriverManager.java:579)
    at java.sql.DriverManager.getConnection(DriverManager.java:190)
    at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:173)
    at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:279)
    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)
    ... 24 more

这是我的休眠配置:

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/wstrader2?characterEncoding=UTF-8</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.current_session_context_class">jta</property>
    <mapping resource="hibernate/dto/Warehouse.hbm.xml"/>
    <mapping resource="hibernate/dto/Exchange.hbm.xml"/>
    <mapping resource="hibernate/dto/Packing.hbm.xml"/>
    <mapping resource="hibernate/dto/GradeMaster.hbm.xml"/>
    <mapping resource="hibernate/dto/MarketFobDiff.hbm.xml"/>
    <mapping resource="hibernate/dto/Arbitration.hbm.xml"/>
    <mapping resource="hibernate/dto/Quality.hbm.xml"/>
    <mapping resource="hibernate/dto/Region.hbm.xml"/>
    <mapping resource="hibernate/dto/City.hbm.xml"/>
    <mapping resource="hibernate/dto/Contract.hbm.xml"/>
    <mapping resource="hibernate/dto/HistoricalBasis.hbm.xml"/>
    <mapping resource="hibernate/dto/Country.hbm.xml"/>
    <mapping resource="hibernate/dto/Origin.hbm.xml"/>
    <mapping resource="hibernate/dto/WarehouseReceipt.hbm.xml"/>
    <mapping resource="hibernate/dto/DailyBasis.hbm.xml"/>
    <mapping resource="hibernate/dto/User.hbm.xml"/>
    <mapping resource="hibernate/dto/Movement.hbm.xml"/>
    <mapping resource="hibernate/dto/PaymentTerm.hbm.xml"/>
    <mapping resource="hibernate/dto/ContractTerm.hbm.xml"/>
    <mapping resource="hibernate/dto/CompanyMaster.hbm.xml"/>
    <mapping resource="hibernate/dto/ProcessingOrder.hbm.xml"/>
    <mapping resource="hibernate/dto/Stock.hbm.xml"/>
    <mapping resource="hibernate/dto/HistoricalStock.hbm.xml"/>
    <mapping resource="hibernate/dto/Menu.hbm.xml"/>
    <mapping resource="hibernate/dto/Authorization.hbm.xml"/>
    <mapping resource="hibernate/dto/Page.hbm.xml"/>
    <mapping resource="hibernate/dto/ContractPriceFixation.hbm.xml"/>
    <mapping resource="hibernate/dto/FuturesContract.hbm.xml"/>
    <mapping resource="hibernate/dto/FutureCloseOut.hbm.xml"/>
    <mapping resource="hibernate/dto/Currency.hbm.xml"/>
    <mapping resource="hibernate/dto/FuturesContractArchive.hbm.xml"/>
    <mapping resource="hibernate/dto/FutureCloseOutArchive.hbm.xml"/>
    <mapping resource="hibernate/dto/ScreenMaster.hbm.xml"/>
    <mapping resource="hibernate/dto/QualityMaster.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

这是我的 HibernateUtil.java:

public class HibernateUtil {
    private static final SessionFactory ourSessionFactory;
    private static ServiceRegistry serviceRegistry;
    private static Configuration configuration = new Configuration().configure();

    static {
        try {
            serviceRegistry = new ServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).buildServiceRegistry();
            ourSessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        return ourSessionFactory.openSession();
    }
}

有人可以找出原因或告诉我导致错误的条件"Too many connection"org.hibernate.exception.JDBCConnectionException: Could not open connection 我尝试找到相关主题但仍未找到问题的答案

感谢您阅读本主题。

更新:我的示例Dao.java

public class CityDAO {

    private Session session = null;

    public CityDAO() {
        session = HibernateUtil.getSession();
    }

    public ArrayList<City> getAllCities() {
        try {
            session.getTransaction().begin();
            Criteria crit = session.createCriteria(City.class);
            ArrayList<City> cities = (ArrayList<City>)crit.list();
            session.flush();
            session.getTransaction().commit();
            return cities;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;
    }

    public City getCityById(int id){
        try {
            session.getTransaction().begin();
            Criteria crit = session.createCriteria(City.class);
            crit.add(Restrictions.eq("id", id));
            City city = (City)crit.uniqueResult();
            session.flush();
            session.getTransaction().commit();
            return city;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;
    }
}
4

3 回答 3

2

我找到了解决我的问题的方法。因为我的 Web 应用程序使用 servlet - 老式的。所以我试试这个:

https://community.jboss.org/wiki/OpenSessionInView

这对我有用。

谢谢大家给我建议:D

于 2013-04-12T03:18:14.053 回答
0

我假设,异常是由 MySql 引发的。要么增加那里的最大连接数,要么检查源是否存在资源泄漏。例如,不要在每次请求后创建连接实例或在每次请求后关闭连接等等。

于 2013-04-11T09:37:52.877 回答
0

您在 DAO 类的每个实例上都有一个打开的会话,即使您设置了连接池,也无济于事。

您制作了类似many-sessions-per-application反模式的东西(与session-per-application有点不同)。该反模式存在问题,在Hiberhate Guide中进行了描述

会话不是线程安全的。如果共享 Session 实例,并发工作的事物,如 HTTP 请求、会话 bean 或 Swing 工作程序,将导致竞争条件。

Hibernate 抛出的异常意味着您必须回滚数据库事务并立即关闭 Session

另外,由于您没有连接池,当连接被服务器终止时,应用程序无法检测到情况。

于 2013-04-11T11:37:06.627 回答