Reputation: 75
I want to check the online/offline status about a Database Server with Java.
Can I check this with a Socket connection over the port? I want to do this wihtout a Database connection with jdbc because the login and Database system info is unknown.
Upvotes: 2
Views: 2901
Reputation: 9839
The above approaches don't really consider timing out in case the remote is unreachable, and a reasonable timeout should be defined because the default value is 20 seconds!!
You can state a timeout using the socket.connect
method AFTER you create a blank socket.
SocketFactory sf = SocketFactory.getDefault();
try (Socket socket = sf.createSocket()) {
socket.connect(new InetSocketAddress(ipAdder, port), timeoutInMillis);
logger.info("database is up");
} catch (IOException e) {
logger.info("database is down");
}
The example above uses try with resources
Upvotes: 1
Reputation: 2234
Yes, you can just open a Socket
to the address and port of your databse server, if you get an IOException
the server is down. (tested with postgress)
public boolean isDatabaseOnline(String address, int port) {
boolean result;
try {
Socket socket = new Socket(address, port);
socket.close();
result = true;
} catch (IOException e) {
result = false;
}
return result;
}
Upvotes: 2
Reputation: 4636
You can try the following:
try {
Socket socket = new Socket("127.0.0.1", port); //Port dependent on your DB/Server
// Server is up
socket.close();
}
catch (IOException e)
{
// Server is down
}
Upvotes: 6