先贴代码,然后再演示,代码非常简单。
代码
public class TestHeartBeat {
public static void main(String[] args) throws Exception {
databaseHeartBeatCheck();
redisHeartBeatCheck();
}
//测试数据库
public static void databaseHeartBeatCheck() throws Exception{
//标志位
Boolean isAlive = true;
//数据库的Ip地址
String hostIPAddr = "127.0.0.1";
//数据库的端口号
int hostPort = 3306;
//创建telnetClient实例
TelnetClient telnetClient = new TelnetClient();
//设置默认的超时时间
telnetClient.setDefaultTimeout(3000);
try {
//建立连接
telnetClient.connect(hostIPAddr, hostPort);
} catch (SocketException e) {
isAlive = false;
System.out.println("数据库--->>>"+hostIPAddr+"心跳检测异常!");
} catch (IOException e) {
isAlive = false;
System.out.println("数据库--->>>"+hostIPAddr+"心跳检测异常!");
}
//如果未抛出异常,则表示可以连接
if(isAlive)
System.out.println("数据库--->>>"+hostIPAddr+"心跳检测正常!");
}
//测试redis
public static void redisHeartBeatCheck(){
Boolean isAlive = true;
String hostIPAddr = "127.0.0.1";
int hostPort = 6379;
TelnetClient telnetClient = new TelnetClient();
telnetClient.setDefaultTimeout(30000);
try {
telnetClient.connect(hostIPAddr, hostPort);
} catch (SocketException e) {
isAlive = false;
System.out.println("redis--->>>"+hostIPAddr+"心跳检测异常!");
} catch (IOException e) {
isAlive = false;
System.out.println("redis--->>>"+hostIPAddr+"心跳检测异常!");
}
if(isAlive)
System.out.println("redis--->>>"+hostIPAddr+"心跳检测正常!");
}
}
TelnetClient在org.apache.commons.net.telnet包下,只需要导入相关依赖或jar即可。