如何在Tomcat启动时运行脚本?

时间:2015-03-17 10:08:36

标签: shell tomcat

我想知道如何在Tomcat启动时运行shell脚本,即catalina.log打印" INFO:服务器启动时间为xxx ms"

提前致谢,再见

2 个答案:

答案 0 :(得分:3)

在Tomcat 7中,您可以通过tomcat配置的server.xml文件中的自定义侦听器来实现此目的:

<?xml version="1.0" encoding="utf-8"?>
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="your.domain.CustomEventHookListener" />

  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <Listener className="org.apache.catalina.core.JasperListener" />
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
  <Service name="Catalina">
    <Connector port="8888" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    <Engine name="Catalina" defaultHost="default">
      <Host name="default" 
            appBase="webapps" 
            unpackWARs="false" 
            autoDeploy="false">
        <Context path="" docBase="/opt/www/application">
        </Context>
      </Host>
    </Engine>
  </Service>
</Server>

CustomEventHootListener.java:

package your.domain;

import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;

public class CustomEventHookListener implements LifecycleListener {
  @Override
  public void lifecycleEvent(LifecycleEvent arg0) {
    Lifecycle lifecycle = arg0.getLifecycle();
    if (lifecycle == null) {
      return;
    }
    String type = arg0.getType();
    if (type == null) {
      return;
    }
    String stateName = lifecycle.getStateName();
    if (stateName == null) {
      return;
    }
    if (type.equals("after_start") && stateName.equals("STARTED")) {
      startPostInitScript();
    }
  }

  private void startPostInitScript() {
    // Non-blocking please.
    Thread t = new Thread() {
      @Override
      public void run() {
        try {
          super.run();
          String script = "/path/to/your-script.sh";
          // inheritIO to output things to JVM.
          new ProcessBuilder().command(script).inheritIO().start().waitFor();
        } catch (Throwable e) {
          e.printStackTrace();
        }
      }
    };
    t.setDaemon(true);
    t.start();
  }
}

您可以在https://github.com/Valemobi/tomcat-events-hook

查看功能示例

答案 1 :(得分:0)

找到tomcat启动脚本(在/etc/init.d/中可能tomcat7)并在start块的适当位置编写调用脚本。