是否有任何 Groovy 或 Java 代码在 30 分钟的间隔内检查 microsoft sql 中的服务器可达性进行 3 次尝试

问题描述

能否请您帮忙用 Groovy 或 Java 代码检查 microsoft sql 中的服务器可达性,每隔 30 分钟尝试 3 次。我开发了一个代码来在 msql 中执行查询。 >

但是我需要检查失败情况如果服务器无法访问,请在 30 分钟的间隔内尝试 3 次。

分享了用于连接 sql 服务器并运行查询的示例 groovy 代码

def username="abcc"
def password="sdsadsdsad"
def result=""
def driver = Class.forName('com.microsoft.sqlserver.jdbc.sqlServerDriver').newInstance()
def props = new Properties()
props.setProperty("user",username)
props.setProperty("password",password) 
def conn=driver.connect("jdbc:sqlserver://dbservername:port;databaseName=datatablename;integratedSecurity=true;authenticationScheme=NTLM",props)
def sql = new groovy.sql.sql(conn)
def query="select top(10) taskid from aspn.task_history"
sql.query(query)
{ resultSet ->
while (resultSet.next())
{
  println resultSet.getString("taskid")
}
}
conn.close()

解决方法

def username = "abcc"
def password = "sdsadsdsad"
def result = ""
def driver = Class.forName('com.microsoft.sqlserver.jdbc.SQLServerDriver').newInstance()
def props = new Properties()
props.setProperty("user",username)
props.setProperty("password",password)

def withReconnect = { connect,action ->
  def tryConnect = {
    try {
      println 'Connecting...'
      connect().withCloseable { conn ->
         action(conn)
      }
      return true // all OK
    // use the type of Exception that happens when connection fails below
    } catch (ConnectionException e) {
      e.printStackTrace()
    }
    return false // FAIL
  }
  // try a few times
  for (def i in (1..3)) {
    if (i != 1) { // sleep only if not first time
      println 'Connection failed,will try again in 10 minutes...'
      sleep 10 * 60 * 1000
    }
    def ok = tryConnect()
    if (ok)
    {
      println 'Successfully executed query'
      return // end the script
    }
  }

  // if we get here,we did not have success
  throw new RuntimeException('Failed too many times,aborting...')
}

// define how to connect
def connect = {
  driver.connect(
    "jdbc:sqlserver://dbservername:port;databaseName=datatablename;integratedSecurity=true;authenticationScheme=NTLM",props)
}

// go!
withReconnect(connect) { conn ->
  def sql = new groovy.sql.Sql(conn)
  def query="select top(10) taskid from aspn.task_history"
  sql.query(query) { resultSet ->
    while (resultSet.next())
    {
      println resultSet.getString("taskid")
    }
  }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...