문제

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
     * See: https://tomcat.apache.org/tomcat-10.0-doc/api/constant-values.html
     * AFTER_DESTROY_EVENT     "after_destroy"
     * AFTER_INIT_EVENT     "after_init"
     * AFTER_START_EVENT     "after_start"
     * AFTER_STOP_EVENT     "after_stop"
     * BEFORE_DESTROY_EVENT     "before_destroy"
     * BEFORE_INIT_EVENT     "before_init"
     * BEFORE_START_EVENT     "before_start"
     * BEFORE_STOP_EVENT     "before_stop"
     * CONFIGURE_START_EVENT     "configure_start"
     * CONFIGURE_STOP_EVENT     "configure_stop"
     * PERIODIC_EVENT     "periodic"
     * START_EVENT     "start"
     * STOP_EVENT     "stop"
     */
    private static int counter;
    
    @Override
    public void lifecycleEvent(LifecycleEvent arg0) {
        String event = arg0.getType();
        LOG.debug("Tomcat Events: " + (++counter) + " :: " + event);
        if(event.equals(org.apache.catalina.Lifecycle.AFTER_START_EVENT)) { // or "after_start"
            LOG.debug("Hey I've started");
        }
    }

}
도움이 되었습니까?

해결책

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.

다른 팁

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()

Following on from Helder's post of embedded Tomcat, you can also handle this in a lambda:

tomcat.getServer().addLifecycleListener((LifecycleEvent e) -> {
  if (e.getType().equals(AFTER_START_EVENT)) {
    // do something
  }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top