當程序存在缺陷時,申請的連接忘記關閉,這時候,就存在連接泄漏了。Druid提供了RemoveAbandanded相關配置,用來關閉長時間不使用的連接。例如:
配置
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
... ...
<property name="removeAbandoned" value="true" /> <!-- 打開removeAbandoned功能 -->
<property name="removeAbandonedTimeout" value="1800" /> <!-- 1800秒,也就是30分鍾 -->
<property name="logAbandoned" value="true" /> <!-- 關閉abanded連接時輸出錯誤日志 -->
... ...
</bean>
配置removeAbandoned對性能會有一些影響,建議懷疑存在泄漏之后再打開。在上面的配置中,如果連接超過30分鍾未關閉,就會被強行回收,並且日志記錄連接申請時的調用堆棧。
內置監控頁面查看未關閉連接堆棧信息
當removeAbandoned=true之后,可以在內置監控界面datasource.html中的查看ActiveConnection StackTrace屬性的,可以看到未關閉連接的具體堆棧信息,從而方便查出哪些連接泄漏了。
web應用
如果你的應用配置了WebStatFilter: https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_%E9%85%8D%E7%BD%AEWebStatFilter
在內置監控頁面weburi-detail.html中,查看JdbcPoolConnectionOpenCount和JdbcPoolConnectionCloseCount屬性,如果不相等,就是泄漏了。
https://github.com/alibaba/druid/wiki/%E8%BF%9E%E6%8E%A5%E6%B3%84%E6%BC%8F%E7%9B%91%E6%B5%8B