java - Guice service dependencies -
i have 3 guava service
s started guava servicemanager
asynchronously.
the first service database connection pool needs start before second/third service can process incoming messages. these being started asynchronously, database may not have started before second/third service starts process message, lead exceptions.
what desired pattern here?
i can inject database service other services , call awaitrunning()
method in service startup, suffer same issue when servicemanager
shutdown.
i believe guice not have out-of-the-box mechanism this. spring e.g. has depends-on attribute can define ordering. there frameworks give guice (e.g. dropwizard guicey implements order annotation). simple solve.
the approach use multibindings define manager dependency classes. call managed (adopted jetty). interface implement ordering. use manager starts services 1 one in defined order (can used shutdown if wanted).
see code example here:
public class executionorder { public static void main(string[] args) { injector createinjector = guice.createinjector(new abstractmodule() { @override protected void configure() { multibinder<managed> multibinder = multibinder.newsetbinder(binder(), managed.class); multibinder.addbinding().to(service1.class); multibinder.addbinding().to(service2.class); bind(managedmanager.class).in(singleton.class); } }); createinjector.getinstance(managedmanager.class); // start } public interface managed extends comparable<managed> { public default void start() {} public default int getorder() { return 0;} @override default int compareto(managed o) { return integer.compare(getorder(), o.getorder()); } } public static class managedmanager { @inject public managedmanager(final set<managed> managed) { managed.stream().sorted().foreach(managed::start); } } public static class service1 implements managed { @override public void start() { system.out.println("started service 1"); } @override public int getorder() { return 1; } } public static class service2 implements managed { @override public void start() { system.out.println("started service 2"); } @override public int getorder() { return 2; } } }
my - admittedly stupidly named - managedmanager injected guice managed interfaces, using guice's multibindings (see module initialise). sort , call start.
the start method initialise services (e.g. database connection). overwriting getorder() method can define service started @ point.
that way defined startup behaviour , can adapt interface have defined shutdown behaviour well.
i hope helps,
artur
Comments
Post a Comment