我使用的Java庫C3PO實現連接MySQL數據庫池。我在查詢之前和之後記錄連接以識別連接泄漏。我發現一個查詢不應該使用近20個連接。事實上,當我檢查MySQL進程列表時,它創建了50個新進程。 這導致整個Web應用程序失敗,因爲後端不再能獲取到數據庫的連接。莫名連接泄漏崩潰的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
任何想法,這可能是造成這種連接泄漏?
,我在我的配置唯一的差異是,不是要求數據源REF:<豆ID =「JdbcTemplate的」類=「org.springframework.jdbc.core.JdbcTemplate」> <構造帶參數> constructor-arg> 在一個構造函數中,我在類級別中執行它,然後調用JDBCTemplate另一個比較是池的初始大小是1並且漸進式在5中。 –