3

我有以下代码

    Configuration config = new Configuration().configure();
    config.buildMappings();
    serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); 
    SessionFactory factory = config.buildSessionFactory(serviceRegistry);
    Session hibernateSession = factory.openSession();
    Transaction tx = hibernateSession.beginTransaction();
    ObjectType ot = (ObjectType)hibernateSession.merge(someObj);
    tx.commit();
    return ot;

hibernate.cfg.xml包含:

<session-factory>

    <property name="connection.url">jdbc:postgresql://127.0.0.1:5432/dbase</property>
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="connection.driver_class">org.postgresql.Driver</property>

    <property name="connection.username">username</property>
    <property name="connection.password">password</property>

    <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>        
    <property name="hibernate.c3p0.acquire_increment">1</property>
    <property name="hibernate.c3p0.min_size">5</property>
    <property name="hibernate.c3p0.max_size">20</property>
    <property name="hibernate.c3p0.max_statements">50</property>
    <property name="hibernate.c3p0.timeout">300</property>
    <property name="hibernate.c3p0.idle_test_period">3000</property>
    <property name="hibernate.c3p0.acquireRetryAttempts">1</property>
    <property name="hibernate.c3p0.acquireRetryDelay">250</property>

    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.use_sql_comments">true</property>

    <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    <property name="hibernate.current_session_context_class">thread</property>

    <mapping class="...." />

</session-factory>

几秒钟和一些成功插入后,出现以下异常:

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already
    at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:291)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:108)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:66)
    at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:125)
    at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:30)
    at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:22)
    at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:30)
    at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:24)
    at org.postgresql.Driver.makeConnection(Driver.java:393)
    at org.postgresql.Driver.connect(Driver.java:267)
    at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:135)
    at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182)
    at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137)
    at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014)
    at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32)
    at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810)
    at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
12:24:19.151 [          Thread-160] WARN                   internal.JdbcServicesImpl - HHH000342: Could not obtain connection to query metadata : Connections could not be acquired from the underlying database!
12:24:19.151 [          Thread-160] INFO                             dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
12:24:19.151 [          Thread-160] INFO                  internal.LobCreatorBuilder - HHH000422: Disabling contextual LOB creation as connection was null
12:24:19.151 [          Thread-160] INFO        internal.TransactionFactoryInitiator - HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
12:24:19.151 [          Thread-160] INFO               ast.ASTQueryTranslatorFactory - HHH000397: Using ASTQueryTranslatorFactory
12:24:19.151 [          Thread-160] INFO                        hbm2ddl.SchemaUpdate - HHH000228: Running hbm2ddl schema update
12:24:19.151 [          Thread-160] INFO                        hbm2ddl.SchemaUpdate - HHH000102: Fetching database metadata
12:24:19.211 [Runner$PoolThread-#0] WARN              resourcepool.BasicResourcePool - com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@ee4084 -- 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 (1). Last acquisition attempt exception: 
org.postgresql.util.PSQLException: FATAL: sorry, too many clients already
    at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:291)

似乎休眠并没有实现连接。但是因为被调用而hibernateSession.close()导致异常。Session is closedtx.commit()

4

3 回答 3

1

我不太确定这里发生了什么,但我建议您不要将 hibernate.c3p0.acquireRetryAttempts 设置为 1。首先,这会使您的下一个设置 hibernate.c3p0.acquireRetryDelay 无关紧要——它设置了之间的时间长度重试尝试,但如果只有一次尝试(好吧,参数名称具有误导性,它设置了尝试的总数),则没有重试。您设置的效果只是让池在客户端进入时尝试获取连接,然后在失败时立即向客户端抛出异常。它根本不限制池将尝试获取的连接数(除非您将 breakOnAcquireFailure 设置为 true,在这种情况下,根据您的设置,任何未能获取连接都会使整个池无效)。

我同意 sol 对您缺乏可靠的资源清理的担忧。如果在您的设置下, commit() 表示 close() (并且您不允许显式调用 close?这似乎很糟糕),那么应该在 finally 块中提交(但在 finally 块中提交也似乎很糟糕,有时你不想提交)。无论关闭/提交有什么问题,使用您拥有的代码,openSession 和提交之间的偶尔异常都会导致连接泄漏。

但这不应该是您的太多打开连接问题的原因。如果您泄漏连接,您会发现连接池最终会冻结(因为 maxPoolSize Connectiosn 由于泄漏而被永远检出)。您只有 25 个打开的连接。其他事情正在发生。尝试查看您的日志。是否以某种方式初始化了多个连接池?(c3p0 在池初始化时在 INFO 级别转储配置信息,因此如果打开了多个池,您应该会看到多条消息。或者,您可以通过 JMX 检查正在运行的 c3p0 池,以查看是否/为什么打开了超过 25 个连接。 )

祝你好运!

于 2012-10-16T18:06:31.323 回答
1

我找到了 c3p0 以这种方式表现的原因。问题很简单......这部分代码:

Configuration config = new Configuration().configure();
config.buildMappings();
serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); 
SessionFactory factory = config.buildSessionFactory(serviceRegistry);

被执行了多次。谢谢史蒂夫的提示。

于 2012-10-17T18:41:26.277 回答
0

我建议你使用 try-catch-finally 块,

finally 关闭会话

IE

try {           
        tx.commit();
    } catch (HibernateException e) {
        handleException(e);
    } finally {
        hibernateSession.close();
    }

而且, postgresql.conf
中的 max_connections 属性默认为 100。如果需要,请增加它。

于 2012-10-16T12:01:39.883 回答