确定Tomcat的最佳方法是从node.js开始的

我正在使用node.js构build应用程序,并且该应用程序与Tomcat服务器进行通信。 当Tomcat服务器启动时,我不确定Tomcat是否准备就绪,现在我在Windows和Mac上使用CURL和WGET,超时时间为2秒,以检查localhost:8080是否已经启动。

有没有更好的方法来做到这一点,而不依赖于CURL和WGET?

build议的方法是在tomcat应用程序上创build一个心跳服务(IE是一个简单的服务,当它启动时发送OK),并每隔x秒轮询一次。
在应用程序运行时,心跳服务对于进行监控是非常重要的,即使已经在端口上侦听(因为有大量的初始化正在进行),应用程序还没有准备好。

还有其他一些方法,如果你在同一个服务器上,你可以使用catalina.out直到你收到“服务器启动”的行。
你可以设置你的tomcat应用程序来通知你的服务器它已经启动了(尽pipe这意味着tomcat需要知道node.js服务器的url),或者设置一些类似的消息队列(比如ApacheMq等)当tomcat启动时,这也将允许在两个服务之间推送消息。

你可以实现一个httpWatcher(模仿文件观察者的合同 – fs.watch)。 它可以轮询一个http端点(一个状态路由或者html文件),并且在返回200(或者达到最大运行时)时触发一个callback。 像这样的东西:

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); } 

然后像这样使用它:

 watch('http://blah.asdfasdfasdfasdfasdfs.com/', function(err, isGood) { if (!err) { console.log(isGood); } }); 

或通过选项…

 watch('http://www.google.com/', {interval:1000,maxRuns:3}, function(err, isGood) { if (!err) { console.log(isGood); } }); 

那么,你可以从Node.JS应用程序请求:

 var http = require("http"); var options = { host: "example.com", port: 80, path: "/foo.html" }; http.get(options, function(resp){ var data = ""; resp.on("data", function(chunk){ data += chunk; }); resp.on("end", function() { console.log(data); // do something with data }); }).on("error", function(e){ // HANDLE ERRORS console.log("Got error: " + e.message); }).on("socket", function(socket) { // ADD TIMEOUT socket.setTimeout(2000); socket.on("timeout", function() { req.abort(); // or make the request one more time }); }); 

文档:

http://nodejs.org/docs/v0.4.11/api/http.html#http.request