Skip to main content

Microservice Listeners

The lifecycle methods of the Microservice class are non-final so that subclasses can override them. A listener interface offers the same hooks without subclassing.

When to use it​

Use a listener to run code when the microservice starts or stops, or to restart it when a section of the config file changes.

Example​

import org.apache.juneau.config.event.*;
import org.apache.juneau.microservice.*;

public class MyMicroserviceListener extends BasicMicroserviceListener {

@Override /* MicroserviceListener */
public void onStart(Microservice microservice) {
System.out.println("Started");
}

@Override /* MicroserviceListener */
public void onConfigChange(Microservice microservice, ConfigEvents events) {

// Restart the microservice if anything was modified in one of our sections
try {
if (events.isSectionModified("MySection"))
microservice.stop().start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

Options​

Microservice.Builderlistener(MicroserviceListener)MicroserviceListeneronStart(Microservice) onStop(Microservice) onConfigChange(Microservice,ConfigEvents)BasicMicroserviceListener

Note that the Microservice.onConfigChange(ConfigEvents) method can also be overridden to react to configuration changes as well:

public class MyMicroservice extends Microservice {

@Override /* MicroserviceListener */
public void onConfigChange(ConfigEvents events) {

// Restart the microservice if anything was modified in one of our sections
if (events.isSectionModified("MySection"))
this.stop().start();
}
}

See also​