Modern Akka DI with Guice

后端 未结 6 1049
时光取名叫无心
时光取名叫无心 2021-02-13 19:41

Java 8, Guice 4.0 and Akka 2.3.9 here. I am trying to figure out how to annotate my actor classes with JSR330-style @Inject annotations, and then wire them all up v

6条回答
  •  青春惊慌失措
    2021-02-13 20:44

    Generic Akka Guice integration without dependency on Play, keeping in mind, not the only actor should be created in the actor system.

    import akka.actor.Actor;
    import akka.actor.ActorRef;
    import akka.actor.ActorSystem;
    import com.google.inject.AbstractModule;
    import com.google.inject.Provider;
    import com.google.inject.name.Names;
    
    public abstract class AkkaGuiceModule extends AbstractModule {
    
        protected  void bindActor(Class actorClass, String name) {
            bind(actorClass);
    
            Provider actorSystemProvider = getProvider(ActorSystem.class);
            Provider actorProvider = getProvider(actorClass);
    
            bind(ActorRef.class)
                    .annotatedWith(Names.named(name))
                    .toProvider(ActorRefProvider.of(actorSystemProvider, actorProvider, name))
                    .asEagerSingleton();
        }
    
    }
    

    Generic ActorRefProvider to create ActorRef for each Actor

    import akka.actor.Actor;
    import akka.actor.ActorRef;
    import akka.actor.ActorSystem;
    import akka.actor.Props;
    import akka.japi.Creator;
    import com.google.inject.Provider;
    import lombok.Value;
    
    @Value(staticConstructor = "of")
    public class ActorRefProvider implements Provider {
    
        private Provider actorSystemProvider;
        private Provider actorProvider;
        private String name;
    
        public final class ActorCreator implements Creator {
            @Override
            public Actor create() {
                return actorProvider.get();
            }
        }
    
        @Override
        public ActorRef get() {
            return actorSystemProvider.get().actorOf(Props.create(new ActorCreator()), name);
        }
    
    }
    

    Usage example

    import akka.actor.ActorSystem;
    import com.google.inject.Provides;
    import com.typesafe.config.Config; // optional
    
    public class MyAkkaModule extends AkkaGuiceModule {
    
        @Provides
        @Singleton
        ActorSystem actorSystem(Config config) {
            return ActorSystem.create("actor-system-name", config);
        }
    
        @Override
        protected void configure() {
            bindActor(SomeActor1.class, "actorName1");
            bindActor(SomeActor2.class, "actorName2");
        }
    
    }
    

提交回复
热议问题