问题描述
能否请您帮忙用 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")
}
}
}