如何发现数据库连接泄露

     1. 根据日志查找;
     首先,翻看系统日志,找到连接池溢出的时刻。然后,对应这个时间,查找用户正在进行的操作。
     这种方法适合于不启动任何监控程序或进程,不改变系统设置,就能人为的缩小可能泄露连接的代码范围。

     2. 利用连接池本身的utility设施;比如C3P0,以下是需要用到的两个参数(推荐):
unreturnedConnectionTimeout
Default: 0
Seconds. If set, if an application checks out but then fails to check-in [i.e. close()] a Connection within the specified period of time, the pool will unceremoniously destroy() the Connection. This permits applications with occasional Connection leaks to survive, rather than eventually exhausting the Connection pool. And that's a shame. Zero means no timeout, applications are expected to close() their own Connections. Obviously, if a non-zero value is set, it should be to a value longer than any Connection should reasonably be checked-out. Otherwise, the pool will occasionally kill Connections in active use, which is bad. This is basically a bad idea, but it's a commonly requested feature. Fix your $%!@% applications so they don't leak Connections! Use this temporarily in combination with debugUnreturnedConnectionStackTraces to figure out where Connections are being checked-out that don't make it back into the pool!

debugUnreturnedConnectionStackTraces
Default: false
If true, and if unreturnedConnectionTimeout is set to a positive value, then the pool will capture the stack trace (via an Exception) of all Connection checkouts, and the stack traces will be printed when unreturned checked-out Connections timeout. This is intended to debug applications with Connection leaks, that is applications that occasionally fail to return Connections, leading to pool growth, and eventually exhaustion (when the pool hits maxPoolSize with all Connections checked-out and lost). This parameter should only be set while debugging, as capturing the stack trace will slow down every Connection check-out.


     当我们同时使用这两个参数时,比如unreturnedConnectionTimeout设为5秒,debugUnreturnedConnectionStackTraces设为true。那么,当一个连接被check out 5秒,还没有被check in的时候,连接池会抛出一个错误堆栈。有了堆栈,那我们就可以精确定位出现问题的代码位置了。
     当然,这个方法中的参数并不是C3P0特有的,其他连接池配置中,应该也有类似的参数。
     

猜你喜欢

转载自power1128.iteye.com/blog/1476169