如何检查SQL Server是否还活着?

时间:2009-12-18 15:59:39

标签: .net sql-server heartbeat

我有一种方法可以检查并确保我的SQL服务器在线,我在代码的一些连接敏感部分使用它。

虽然它工作正常,但我注意到它需要20毫秒才能运行,我想知道是否有人知道检查SQL服务器的更好方法,以确保它能够起作用。

这是我现有的代码。

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public static bool IsSqlServerOnline(string connectionString)
        {
#if DEBUG || DEBUG_SINGLE_CORE
            Stopwatch sw = new Stopwatch();
            sw.Start();
#endif

#if DEBUG || DEBUG_SINGLE_CORE
            // This sould only occur of we are in the VSTS designer
            if (string.IsNullOrEmpty(connectionString))
            {
                return false;
            }
#endif

            if ( !NetworkInterface.GetIsNetworkAvailable() )
            {
                return false;
            }

            if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException("connectionString");

            bool isSqlServerOnline = false;
            SqlConnectionStringBuilder conString = new SqlConnectionStringBuilder(connectionString);

            try
            {
                using (Ping p = new Ping())
                {
                    string sqlSvr = conString.DataSource;
                    if (sqlSvr != null)
                        isSqlServerOnline = p.Send(sqlSvr).Status == IPStatus.Success;
                }
            }
            catch (PingException)
            {
                isSqlServerOnline = false;
            }

            if ( isSqlServerOnline )
            {
                try 
                {
                    conString.ConnectTimeout = 3;
                    using (SqlConnection conn = new SqlConnection(conString.ToString()))
                    {
                        conn.Open();
                        isSqlServerOnline = true;
                    }
                }
                catch ( Exception )
                {
                    isSqlServerOnline = false;
                }
            }

#if DEBUG || DEBUG_SINGLE_CORE
            sw.Stop();
            Trace.WriteLine(string.Format("IsSqlServerOnline: {0}", sw.ElapsedMilliseconds));
#endif
            return isSqlServerOnline;
        }

3 个答案:

答案 0 :(得分:2)

您的代码检查您是否能够建立与SQL Server的连接。 您可能还有兴趣更进一步,通过运行类似

的方式验证它是否正在响应查询
Select @@version

答案 1 :(得分:1)

您可以使用Windows服务控制管理器API:

  1. 调用OpenSCManager(主机名作为参数)
  2. 致电OpenService
  3. 致电QueryServiceStatus
  4. 如果状态为SERVICE_RUNNING,则服务已启动。

    如果您没有进入P / Invoke,请查看System.ServiceProcess.ServiceController。功能

    public ServiceController(string name, string machineName)
    

    看起来可能用于检索特定服务的状态。

答案 2 :(得分:1)

正如其他人所说,20ms的障碍可能无需担心。但是,我可能会问代码调用的频率是多少?将呼叫结果缓存3-5秒(甚至只是2-3)就足够了吗?而不是每次访问网络? 2-3秒是一个非常小的缓存窗口,没有什么可说的“服务器活动”检查无法返回OK只是为了让服务器在执行代码中间崩溃。如果你所浪费的只是每隔几秒20毫秒(最多),那几乎不用担心。

相关问题