How can i check if MySQL and Tomcat are running?

牧云@^-^@ 提交于 2019-12-04 07:36:37

Most straightforward way would be to just connect the server and see if it succeeds.

MySQL:

Connection connection = null;
try {
    connection = DriverManager.getConnection(url, username, password);
    // Succes!
} catch (SQLException e) {
    // Fail!
} finally {
    if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}

Tomcat:

try {
    new URL(url).openConnection().connect();
    // Succes!
} catch (IOException e) {
    // Fail!
}

If you want a bit more specific status, e.g. checking if a certain DB table is available or a specific webapp resource is available, then you have to fire a more specific SELECT statement or HTTP request respectively.

I assume that you know the ports of which are running in advance (or from configuration files). The easiest way to check is to make socket connections to those ports like a telnet program does. Something like:

public boolean isServerUp(int port) {
    boolean isUp = false;
    try {
        Socket socket = new Socket("127.0.0.1", port);
        // Server is up
        isUp = true;
        socket.close();
    }
    catch (IOException e)
    {
        // Server is down
    }
    return isUp;
}

Usage:

isTomcatUp = isServerUp(8080);
isMysqlUp = isServerUp(3306);

However, I would say that is a false-negative check.. Sometimes it says server UP but the server is stuck or not responding...

I would make sure that what ever monitoring you setup is actually exercising some code. Monitoring the JVM via jmx can also be helpful after the fact. Check out http://www.cacti.net/ .

Firing a simple fixed query through MySQL

SELECT 'a-ok';

and have the .jsp return that a-ok text. If it times out and/or doesn't respond with a-ok, then something's hinky. If you need something more detailed, you can add extra checks, like requesting now() or something bigger, like SHOW INNODB STATUS.

The easiest thing is to look for the MySQL and Tomcat PID files. You need to look at your start scripts to make sure of the exact location, but once you find it, you simply test for existence of the pid file.

Create a servlet as a status page. In the servlet perform a cheap query, if the query succeeds let the servlet print OK otherwise Error. Put the servlet into a war and deploy it to all instances.

This could be used for checks in yor admin console by doing a loop over all instances.

I'd create a simple REST webservice that runs on each Tomcat instance and does a no-op query against the database. That makes it easy to drive from anywhere (command line, web app, GUI app, etc.)

If these are publicly available servers you can use a service like binarycanary.com to poll a page or service in your app.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!