Callback on Tomcat server startup complete

假装没事ソ 提交于 2019-12-20 01:58:09

问题


Is there any mechanism, lifecycle event or callbacks, in Spring or Tomcat to notify once Tomcat server startup is completed? (I have 8 web applications and queues configured. I would prefer to get notification back to each application once all the applications are started.) I know Spring has the application listener, which can be used once the web application is initialized. But I cannot use it in my case because I would prefer to get a notification once all the web apps are initialized.

******EDITED*******

I've implemented a Tomcat listener to log the message, but I have absolutely no idea where to hook this listener.

I tried to create this bean using Spring and also adding the listener to web.xml both did not work.

Here is my code:

public class KPTomcatListener implements LifecycleListener {

    private static final Logger LOG = LoggerFactory.getLogger(KPTomcatListener.class);
    /**
     * All the events of tomcat
     * AFTER_START_EVENT, 
     * AFTER_STOP_EVENT, 
     * BEFORE_START_EVENT, 
     * BEFORE_STOP_EVENT, 
     * DESTROY_EVENT, 
     * INIT_EVENT, 
     * PERIODIC_EVENT, 
     * START_EVENT, 
     * STOP_EVENT
     */
    private static int counter;

    @Override
    public void lifecycleEvent(LifecycleEvent arg0) {
        String event = arg0.getType();
        LOG.debug("Tomcat Envents: " + (++counter) + " :: " + event);
        if(event.equals("AFTER_START_EVENT")) {
            LOG.debug("Hey I've started");
        }
    }

}

回答1:


All of the major Tomcat components implement org.apache.catalina.Lifecycle which includes the ability to add a org.apache.catalina.LifecycleListener. It sounds like you want the AFTER_START_EVENT of the Host.

You configure the listener in server.xml like this:

<Host ... >
  <Listener className="your.package.KPTomcatListener"/>
  <!-- Other nested elements go here -->
</Host>

The class must be packaged in a JAR and the JAR placed in Tomcat's lib directory.




回答2:


In case someone wants to do it programmatically (if using embedded Tomcat for example):

Tomcat tomcat = new Tomcat();
...
tomcat.getServer().addLifecycleListener(new KPTomcatListener());
tomcat.start()


来源:https://stackoverflow.com/questions/22390818/callback-on-tomcat-server-startup-complete

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