【问题标题】:How to know number of connections which are still open using mysql and .Net?如何知道使用 mysql 和 .Net 仍然打开的连接数?
【发布时间】:2012-06-13 12:16:13
【问题描述】:

我正在将 Asp.Net 与 MySql 一起使用,我正在尝试解决错误:

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

我正在努力确保我没有泄露任何连接。 我需要知道连接池的状态(现在打开了多少个连接)?在这个thread 中,我了解到我可以使用性能监视器来了解池数。但是当使用 MySql 而不是 Sql Server 时,我该怎么做呢?

【问题讨论】:

    标签: .net mysql connection-pooling


    【解决方案1】:

    下面讨论的上述代码的原始参考是here:

    我已经使用 Oracle 完成了以下操作,我认为它可以与 MySQL 一起进行一些小的修改(例如更改 OracleConnection 等)。您可以创建一个名为 ConnectionSpy 的类(见下文)。这是在 VB.Net 中,如果您愿意,您可以将代码转换为 C#。

    Imports System
    Imports System.Data
    Imports Oracle.DataAccess.Client
    Imports System.Diagnostics
    Imports System.IO
    
    Public Class ConnectionSpy
        Dim con As OracleConnection
        Dim st As StackTrace
        Dim handler As StateChangeEventHandler
        Dim logfileName As String
    
        Public Sub New(ByVal con As OracleConnection, ByVal st As StackTrace, ByVal logfileName As String)
            If (logfileName Is Nothing Or logfileName.Trim().Length() = 0) Then
                Throw New ArgumentException("The logfileName cannot be null or empty", logfileName)
            End If
    
            Me.logfileName = logfileName
            Me.st = st
            'latch on to the connection
            Me.con = con
            handler = AddressOf StateChange
            AddHandler con.StateChange, handler
            'substitute the spy's finalizer for the 
            'connection's
            GC.SuppressFinalize(con)
        End Sub
        Public Sub StateChange(ByVal sender As Object, ByVal args As System.Data.StateChangeEventArgs)
            If args.CurrentState = ConnectionState.Closed Then
                'detach the spy object and let it float away into space
                'if the connection and the spy are already in the FReachable queue
                'GC.SuppressFinalize doesn't do anyting.
                GC.SuppressFinalize(Me)
                RemoveHandler con.StateChange, handler
                con = Nothing
                st = Nothing
            End If
        End Sub
        Protected Overrides Sub Finalize()
            'if we got here then the connection was not closed.
            Using stream As FileStream = New FileStream( _
                        logfileName, _
                        FileMode.Append, _
                        FileAccess.Write, _
                        FileShare.Write)
    
                Using sw As StreamWriter = New StreamWriter(stream)
                    Dim text As String = _
                        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") & _
                        ": WARNING: Open Connection is being Garbage Collected" & _
                        Environment.NewLine & "The connection was initially opened " & st.ToString()
                    sw.WriteLine(text)
                    sw.Flush()
                    RemoveHandler con.StateChange, handler
                    'clean up the connection
                    con.Dispose()
                End Using
    
            End Using
        End Sub
    End Class
    

    然后,在您的 web.config/app.config 中,您可以添加如下部分:

    <configuration>
        <appSettings>
            <!--
              if you need to track connections that are not being closed, set
              UseConnectionSpy to "true". If you use the connection spy, a log
              will be created (the logfile can be specified with the ConnectionSpyLog
              parameter) which will give you a stack trace of each code location
              where a connection was not closed        
            -->
        <add key="UseConnectionSpy" value="true"/>
        <add key="ConnectionSpyLog" value="c:\\log\\connectionspy.log"/>
        </appSettings>
    </configuration>
    

    然后,无论您在代码中的何处创建数据库连接,都可以执行此操作(见下文)。mConnection 变量将代表您的 MySQL 连接,当您到达这一点时,您已经创建了该连接。

        If ConfigurationManager.AppSettings("UseConnectionSpy") = "true" Then
            Dim st As StackTrace = New StackTrace(True)
            Dim sl As ConnectionSpy = New ConnectionSpy(mConnection, st, _
                                                        ConfigurationManager.AppSettings("ConnectionSpyLog"))
        End If
    

    那么,如果您有任何连接在关闭之前被垃圾回收,则会在日志文件中报告。我在一些应用程序中使用了这种技术,并且效果很好。

    您需要做的是为您的 MySQL 数据库连接创建一个包装类,然后您可以将上面的代码放在适当的位置以跟踪连接。或者,您可以将上述调用添加到您创建连接的任何位置。包装类更简洁一些(这就是我们所做的)

    【讨论】:

      猜你喜欢
      • 2012-08-28
      • 2013-04-13
      • 1970-01-01
      • 2015-08-27
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多