public interface ServiceDependencies
When starting a server, Ratpack will extract all instances of ServiceDependencies
from the server registry.
Each will be called with a spec
that they can use to define the dependencies between services.
Services are guaranteed to start after and stop before their dependencies. Services that do not have a dependency relationship may start and stop concurrently. If a depended on service fails to start, the dependent service will not be started.
import ratpack.server.RatpackServer;
import ratpack.service.Service;
import ratpack.service.ServiceDependencies;
import ratpack.service.StartEvent;
import ratpack.service.StopEvent;
import java.util.ArrayList;
import java.util.List;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class Example {
private static final List<String> EVENTS = new ArrayList<>();
private static class MyService implements Service {
private final String label;
public MyService(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
@Override
public void onStart(StartEvent event) throws Exception {
EVENTS.add(label + "-start");
}
@Override
public void onStop(StopEvent event) throws Exception {
EVENTS.add(label + "-stop");
}
}
public static void main(String[] args) throws Exception {
RatpackServer server = RatpackServer.of(s -> s
.registryOf(r -> r
.add(new MyService("one"))
.add(new MyService("two"))
// service two depends on service one
.add(ServiceDependencies.class, d -> d.dependsOn(
MyService.class, service -> service.getLabel().equals("two"),
MyService.class, service -> service.getLabel().equals("one")
))
)
);
server.start();
assertEquals(asList("one-start", "two-start"), EVENTS);
server.stop();
assertEquals(asList("one-start", "two-start", "two-stop", "one-stop"), EVENTS);
}
}
If dependencies between services can be declared purely via types, consider using the DependsOn
annotation instead which is more concise yet equivalent.
DependsOn
,
ServiceDependenciesSpec
Modifier and Type | Method and Description |
---|---|
void |
define(ServiceDependenciesSpec spec)
Declares service depenencies via the given spec.
|
void define(ServiceDependenciesSpec spec) throws Exception
spec
- the spec of service dependenciesException
- any