java - 莫名其妙的连接泄漏导致 webapp 崩溃

标签 java mysql spring c3p0 jdbctemplate

我正在使用 Java 库 C3PO 来实现与 MySQL 数据库的连接池。我在查询之前和之后记录连接以确定连接泄漏。我发现一个查询在不应该使用近 20 个连接的情况下使用了近 20 个连接。事实上,当我检查 MySQL 进程列表时,它创建了 50 个新进程。 这会导致整个 webapp 失败,因为后端无法再连接到数据库。

这是导致泄漏的方法的一些伪代码。

public List<Interaction> getInteractions() {
     // Log the # of connections before the query
     logNumConnections();
     --> stdout: Total (7) Idle: (2) Busy: (5) Orphan: (0)

     // Here's the query that's causing the leak
     String sql="select distinct ... from A left join B on A.x=B.y "
            + "where A.x in (?,?,...)"
     List<Interaction> results = jdbcTemplate.query(sql, args, rowMapper);

     // Log the # connections after the query
     logNumConnections();
     --> stdout: Total (24) Idle: (0) Busy: (24) Orphan: (0)

     return results;
}

JdbcTemplate 应该关闭连接和释放资源。它不应该为一个查询使用 20 个连接!这些连接在查询后很长时间内仍然存在。这是我的 JdbcTemplate 和 DataSource 的配置。

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
     <property name="driverClass" value="${database.driver}" />
     <property name="jdbcUrl" value="${database.url}"/>
     <property name="user" value="${database.username}"/>
     <property name="password" value="${database.password}"/>
     <property name="initialPoolSize" value="5" />
     <property name="minPoolSize" value="5" />
     <property name="maxPoolSize" value="50" />
     <property name="acquireIncrement" value="1" />
     <property name="maxStatements" value="1000" />
     <property name="maxStatementsPerConnection" value="1000"/>
     <property name="maxIdleTime" value="10000"/>
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
     <constructor-arg>
          <ref bean="dataSource" />
     </constructor-arg>
</bean>

最后,这里是explain语句

id|select_type|table|type  |possible_keys|key    |key_len|rows  | Extra  
 1|SIMPLE     |A    |ALL   |NULL         |NULL   |NULL   |437750| Using where; Using temporary
 1|SIMPLE     |B    |eq_ref|PRIMARY      |PRIMARY|4      |1  

知道是什么导致了这个连接泄漏吗?

最佳答案

发现问题。导致连接泄漏的不是上面的查询。这是对单独方法的单独 AJAX 调用,该方法在与上述查询相同的时间范围内执行。上面的查询/方法毕竟没有引起任何问题。

关于java - 莫名其妙的连接泄漏导致 webapp 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18022286/

相关文章:

MySQL TIMESTAMP 到 QDateTime 以毫秒为单位

mysql - 在 MySQL 中使用什么数据类型来存储图像?

mysql - 日期_添加间隔

java - 需要类似 getTotal(ClassName, ListOfObjectsOfClass, numericFieldOfClass)

java - 类定义中什么时候需要 "public"?

java - 如何检查Tomcat Web应用程序是否正在运行,如果有错误则重定向到另一台服务器?

java - CacheProvider 的异常 NoClassDefFoundError

java - 如何将 spring bean 注入(inject) jersey 的资源类中?

java - Hazelcast Spring 集成问题

spring - 如何使用千分尺 Spring 来运行千分尺弹性?