2016-09-15 54 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; 
}