问题:Hibernate, C3P0, Mysql -- 断管

MySQL 的连接似乎有 8 小时的超时时间。我正在使用 Hibernate for ORM 在 Tomcat 中运行多个 WAR。 8 小时后(即一夜之间),当它获得空闲连接时,我的管道损坏了。

我已经跟踪了代码,并加倍确定我提交或回滚了所有事务。

这是我的 hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!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.bytecode.use_reflection_optimizer">false</property>
    <property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
    <property name="hibernate.connection.password"></property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
    <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <!--property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property-->

    <property name="c3p0.min_size">3</property>
    <property name="c3p0.max_size">5</property>
    <property name="c3p0.timeout">1800</property>
    <property name="c3p0.preferredTestQuery">SELECT 1</property>
    <property name="c3p0.testConnectionOnCheckout">true</property>
    <property name="c3p0.idle_test_period">100</property> <!-- seconds -->

    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <property name="cache.use_query_cache">false</property>
    <property name="cache.use_minimal_puts">false</property>
    <property name="max_fetch_depth">10</property>

    <property name="hibernate.hbm2ddl.auto">update</property>

    <!-- classes removed -->

</session-factory>

我认为可以修复它的参数是c3p0.idle_test_period——它默认为 0。但是,运行 8 小时后我们仍然遇到断管问题。虽然谷歌有多个帖子索引,但没有一个得到令人满意的答案。

解答

所以事实证明我错过了启用 c3p0 的关键行(我正在调整的 c3p0 参数没有效果,因为 Hibernate 正在使用它内置的连接池——它适当地警告它不适合生产)。在 hibernate 2.x 中,设置hibernate.c3p0.max_size属性启用 c3p0 连接池。但是,在 3.x 中,您必须指定以下属性——

<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>

此外,这是我的最终配置参数——

<property name="hibernate.c3p0.min_size">3</property>
<property name="hibernate.c3p0.max_size">5</property>
<property name="hibernate.c3p0.timeout">1800</property>
<property name="hibernate.c3p0.idle_test_period">100</property> <!-- seconds -->

不幸的是,Hibernate 和 c3p0 在这方面都有糟糕的文档。

Logo

华为、百度、京东云现已入驻,来创建你的专属开发者社区吧!

更多推荐