1

In my application architecture I am having two database servers primary db and secondary db server (Replica server).

In my java code I am making a connection with DB to fetch some data now what I want is I will give the IP addresses of both DB servers in my code and will check which DB server is reachable and will connect with that only. But I am not getting how to implement it, the one way is try to telnet but not a good option because I want to disable the telnet on application server for some reasons.

Is there any other and best way to do this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Piyush Agarwal
  • 25,608
  • 8
  • 98
  • 111

2 Answers2

4

Personally, I would just attempt the connection (using standard database classes) and handle the exceptions if the connection fails.

Even if you confirm connectivity initially, nothing prevents a network problem occurring between that test and your actual attempt to use the database.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
2

You can try pinging both hosts and use the one which responds. Here is a sample program.

        InetAddress address = InetAddress.getByName("172.16.2.0");

        // Try to reach the specified address within the timeout
        // periode. If during this periode the address cannot be
        // reach then the method returns false.
        boolean reachable = address.isReachable(10000);

        System.out.println("Is host reachable? " + reachable);

For a more elaborate program, see this Ping program example in Java.

MoveFast
  • 3,011
  • 2
  • 27
  • 53
  • i need for a particular port number because it may possible that the server is reachable but DB is not running on the specified port. – Piyush Agarwal Feb 17 '13 at 19:41
  • @pyus13 You cannot ping a specific port using `isReachable`. You need to test a connection to a socket in order to do that. Refer to [this answer](http://stackoverflow.com/a/14906123/1247781). – FThompson Feb 18 '13 at 00:11