I am building an application using node.js and that application communicates with a Tomcat server. While the tomcat server is launching, I am not sure if Tomcat is ready and has come up or not, for now I use CURL and WGET on Windows and Mac with a timeout of 2 seconds to keep checking if localhost:8080 has come up.
Is there a better way to do this without relying on CURL and WGET?
The suggested way is to create a heartbeat service on the tomcat application (I.E. a simple service that sends OK when it's up), and poll that every x seconds.
A heartbeat service is essential for monitoring while the application is running, and there are also times when the application isn't ready even though it's already listening on the port (because there is some heavy initialization going on).
There are other ways though, if you're on the same server, you can tail the catalina.out until you receive "server started" line.
You can setup your tomcat application to notify your server that it's up (though that means the tomcat needs to know the url for the node.js server), or alternatively setup some kind of message queue (like ApacheMq or such) that you can register when the tomcat is up, this will also allow push messages between the two services.
You could implement a httpWatcher (mimicking the contract of file watcher - fs.watch). It could poll an http endpoint (a status route or html file) and would fire a callback when a 200 is returned (or when a max runs has been reached). Something like this:
var request = require('request');
var watch = function(uri) {
var options;
var callback;
if ('object' == typeof arguments[1]) {
options = arguments[1];
callback = arguments[2];
} else {
options = {};
callback = arguments[1];
}
if (options.interval === undefined) options.interval = 2000;
if (options.maxRuns === undefined) options.maxRuns = 10;
var runCount = 0;
var intervalId = setInterval(function() {
runCount++;
if(runCount > options.maxRuns) {
clearInterval(intervalId);
callback(null, false);
}
request(uri, function (error, response, body) {
if (!error && response.statusCode == 200) {
clearInterval(intervalId);
callback(null, true);
}
});
}, options.interval);
}
Then use it like so:
watch('http://blah.asdfasdfasdfasdfasdfs.com/', function(err, isGood) {
if (!err) {
console.log(isGood);
}
});
Or pass in options...
watch('http://www.google.com/', {interval:1000,maxRuns:3},
function(err, isGood) {
if (!err) {
console.log(isGood);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With