确定Tomcat已经用node.js启动的最好方法是什么?

What is the best way to determine Tomcat has started with node.js

本文关键字:方法 是什么 启动 js Tomcat node 确定      更新时间:2023-09-26

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

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

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

还有其他方法,如果你在同一台服务器上,你可以跟踪catalina。直到你收到"server started"行。
您可以设置tomcat应用程序来通知服务器它已启动(尽管这意味着tomcat需要知道node.js服务器的url),或者设置某种消息队列(如ApacheMq等),您可以在tomcat启动时注册,这也允许在两个服务之间推送消息。

你可以实现一个httpWatcher(模仿文件watcher - fs.watch的契约)。它可以轮询http端点(状态路由或html文件),并在返回200(或达到最大运行数)时触发回调。像这样:

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 app中发出请求:

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