2017-03-05 154 views
0

在每个Web服务调用之后,我一直保持最大连接数。它看起来像每次创建EntityManager并创建到数据库的新连接,但它永远不会完全关闭或释放连接。我总是最大限度地关闭连接,并且在初始呼叫之后,我永远不能再次连接或运行任何查询。休眠JPA连接太多

我是否需要使用SessionManager/SessionFactory或其他方法而不是使用EntityManager?

我也尝试过不使用静态Connection cconn,并继续与EntityManager建立连接,然后在finally块中关闭em,但仍然出现错误。我是JPA新手,所以它是我的设计,我的设置,代码,一切?

获取连接 - ConnectionUtil.java

public static Connection cconn = null; 

public static Connection conn(){ 

     try { 
      if(ConnectionUtil.cconn != null && !ConnectionUtil.cconn.isClosed()){ 
       return cconn; 
      } 
     } catch (SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     Connection conn = null; 
     try { 
      String lcp = ConnectionUtil.getLcp(); 
      logging.info("LCP : " + lcp); 

      EntityManagerFactory factory = null; 
      Map<String,Object> prop = null; 

      String url ,password, user, connString; 

      // Set default Connection details 
      if(lcp == null){ 
       factory = Persistence.createEntityManagerFactory(LOCAL_PER); 
       prop = factory.getProperties(); 

       url = (String) prop.get("javax.persistence.jdbc.url"); 
       password = (String) prop.get("javax.persistence.jdbc.password"); 
       user = (String) prop.get("javax.persistence.jdbc.user"); 
       connString = url +"?user="+user+"&password="+password; 

       connString = "jdbc:mysql://localhost:3306/"+ConnectionUtil.DATABASE+"?" + "user=root&password=password"; 
       logging.info("Setting EntityManager to: default values"); 
       logging.info("Using string: "+ connString); 
       Properties properties = new Properties(); 
       properties.put("connectTimeout", "20000"); 
       conn = DriverManager.getConnection(connString,properties); 
       cconn = conn; 
      } 

persistance.xml

<?xml version="1.0" encoding="UTF-8"?> 
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> 

    <persistence-unit name="Hunting" transaction-type="RESOURCE_LOCAL"> 
     <provider>org.hibernate.ejb.HibernatePersistence</provider> 
     <properties> 
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/database"/> 
      <property name="javax.persistence.jdbc.user" value="root"/> 
      <property name="javax.persistence.jdbc.password" value="password"/> 
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> 


      <!-- Hibernate properties --> 
      <property name="hibernate.show_sql" value="false" /> 
      <property name="hibernate.format_sql" value="false" /> 
      <property name="hibernate.connection.release_mode" value="on_close" /> 
      <property name="hibernate.connection.pool_size" value="100" /> 


      <!-- Configuring Connection Pool --> 
      <property name="hibernate.c3p0.min_size" value="5" /> 
      <property name="hibernate.c3p0.max_size" value="20" /> 
      <property name="hibernate.c3p0.timeout" value="20" /> 
      <property name="hibernate.c3p0.max_statements" value="50" /> 
      <property name="hibernate.c3p0.idle_test_period" value="2000" /> 
     </properties> 
    </persistence-unit> 

获取用户俱乐部从我的web服务的功能。

public static Club getClubById(long id){ 
     Club cc = new Club(); 
     EntityManager em = null; 
     try{ 
      em = ConnectionUtil.getEnitityManager(); 
      cc = em.find(Club.class, id); 
      cc.buildClubUsers(); 
     }finally{ 
      if(em != null){ 
       em.close(); 
      } 
     } 
     return cc; 
    } 

连接错误

15:32:26.315 [http-bio-8080-exec-7] WARN org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator - HHH000022: c3p0 properties were encountered, but the org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider provider class was not found on the classpath; these properties are going to be ignored. 
15:32:26.315 [http-bio-8080-exec-7] INFO org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl - HHH000402: Using Hibernate built-in connection pool (not for production use!) 
15:32:26.315 [http-bio-8080-exec-7] INFO org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 100 
15:32:26.315 [http-bio-8080-exec-7] INFO org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl - HHH000006: Autocommit mode: true 
15:32:26.315 [http-bio-8080-exec-7] INFO org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl - HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/database] 
15:32:26.315 [http-bio-8080-exec-7] INFO org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl - HHH000046: Connection properties: {user=root, password=password, autocommit=true, release_mode=on_close} 
15:32:26.315 [http-bio-8080-exec-7] DEBUG org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl - Opening new JDBC connection 
15:32:26.316 [http-bio-8080-exec-7] WARN org.hibernate.engine.jdbc.internal.JdbcServicesImpl - HHH000342: Could not obtain connection to query metadata : Data source rejected establishment of connection, message from server: "Too many connections" 

编辑:1新增C3PO,得到了相同 “的连接太多” 错误

Mar 05, 2017 3:46:17 PM com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run 
WARNING: [email protected]9 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: 
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections" 
+0

你真的不应该在每个业务/资源库用例中创建一个新的'EntityManagerFactory'。这将是你的应用程序无缘无故的大量开销。通常,您的应用程序应该在启动时生成一个'EntityManagerFactory'或'SessionFactory',并重用工厂根据您的用例分别创建'EntityManager'或'Session'实例。 – Naros

回答

0

我建议你依靠容器上,让它管理您的交易。 在我的以下回答中,我因此假设您使用任何能够管理JPA事务的Web容器 - 这是最先进的功能。

因此,你必须改变你的persistance.xml

<persistence-unit name="Hunting" transaction-type="JTA"> 

为什么JTA超过RESOURCE_LOCAL?简而言之:您不必自己管理交易。 https://stackoverflow.com/a/28998110/3507356

然后调整你POJO

@PersistenceContext("Hunting") 
EntityManager em; 

public static Club getClubById(long id){ 
    Club cc = new Club(); 
    EntityManager em = null; 
    try{ 
     // em = ConnectionUtil.getEnitityManager(); 
     // EM is injected 
     cc = em.find(Club.class, id); 
     cc.buildClubUsers(); 
    }finally{ 
     if(em != null){ 
      em.close(); 
     } 
    } 
    return cc; 
} 

我现在再假设你的俱乐部级被注释为适当领域的注释的@Entity等

我想你就可以摆脱你的ConnectionUtil,因为你只需要将你的Club-jpa服务注入你的web服务并使用它。

+0

我会给这个镜头。我有我的持久性切换连接细节,因为本地我需要我的应用程序连接到本地主机,并在QA/PR我需要它连接到亚马逊aws。我可以在启动“狩猎”或“狩猎亚马逊”时更改或设置@PersistenceContext(“狩猎”)吗? – tiggles

+0

不建议更改Persistence-unit-name或使其动态变化。 (即使你可以使用maven/ant脚本等) 如果你依赖你的容器 - 你应该在容器中定义数据源,并通过JNDI命名它。 因此,在persistence.xml中,您定义访问凭证的部分应该更好地转到服务器配置。 然后,您只需通过以下名称/调用您的数据源: '''jta-data-source> jdbc/oracle''' 您正在使用哪台服务器?查找您的特定容器的“JNDI Dataresource”。 – The86Freak