2016-09-15 53 views
0

我正在做一个RESTful服务与数据库进行通信,使用Hibernate作为ORM。克服休眠5连接限制

我面临的问题是Hibernate的连接池限制,只要达到极限就会抛出异常。

Exception in thread "main" org.hibernate.HibernateException: The internal connection pool has reached its maximum size and no connection is currently available! 

1)我已经尝试设置最大池大小在hibernate.cfg.xml

<property name="connection.pool_size">10</property> 

2)我已经试过,而不是打开一个新的Session每次获取当前连接

public static Session getCurrentSession(){ 
     try{ 
      return sessionFactory.getCurrentSession(); 
     } 
     catch(Exception e){ 
      try { 
       return sessionFactory.openSession(); 
      } catch (Exception e1) { 
       e1.printStackTrace(); 
      } 
     } 
} 

我总是最终达到limit

有没有办法完全克服这一点?

+1

通常,这表示会话泄漏,从而导致连接泄漏。确保您打开的每个会话都关闭。否则它保持打开状态,并且保持与打开/正在使用的数据库的连接。 –

回答

0

我还没找到对hibernate连接池设置限制。然而,从这个答案:Hibernate config connection pool size

你不应该使用hibernate的池机制,因为它不适合生产(你可以看到...)。您可能想要使用像c3p0或hikariCP这样的池化API(我听说DBCP很旧)。

c3p0有一个“c3p0.minPoolSize”参数,但没有强制的最大大小,所以它会根据需要增长。而且很容易与Hibernate集成(http://www.mchange.com/projects/c3p0/https://www.mkyong.com/hibernate/how-to-configure-the-c3p0-connection-pool-in-hibernate/如果你使用Spring和Maven)

然而,当前的配置,如果你之前有多少的最大连接数在您的应用程序没有上限崩溃,可能有泄漏(检查是否关闭了所有连接)。

0

2)我都试过,而不是每次都打开一个新的Session,...

我认为在你平时的代码,你就这样打开你的会话:

Session session = sessionFactory.openSession(); 

您报告的Exception通常在您未关闭会话时发生。但是,即使您已经关闭了session,但有可能发生了一些异常,导致控制权无法达到session.close()声明。

Session session = sessionFactory.openSession(); 
statement1; 
statement2; //  <-- Exception occurs here 
statement3; 
session.close();// <-- because of above Exception, your control never reaches here. 

因此,在这种情况下最好的做法是写你的session.close()在finally块这样的。

Session session; 
try {  
    session = sessionFactory.openSession(); 
    statement1; 
    statement2; //  <-- Exception occurs here 
    statement3; 
} 
finally { 
    session.close();// <-- although there's an exception above, your control won't leave without executing this statement. 
} 

如果您使用的是Java 7及以上,那么你也可以使用try with resourcesoracle doc

try (Session session = sessionFactory.openSession()) { 
    statement1; 
    statement2; 
    statement3; 
}