Modern Akka DI with Guice

后端 未结 6 1041
时光取名叫无心
时光取名叫无心 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:17

    In case anyone found this question, you need to use IndirectActorProducer, I referred to the Spring example and changed it to use Guice instead.

    /**
     * An actor producer that lets Guice create the Actor instances.
     */
    public class GuiceActorProducer implements IndirectActorProducer {
        final String actorBeanName;
        final Injector injector;
        final Class actorClass;
    
        public GuiceActorProducer(Injector injector, String actorBeanName, Class actorClass) {
            this.actorBeanName = actorBeanName;
            this.injector = injector;
            this.actorClass = actorClass;
        }
    
        @Override
        public Actor produce() {
            return injector.getInstance(Key.get(Actor.class, Names.named(actorBeanName)));
        }
    
        @Override
        public Class actorClass() {
            return actorClass;
        }
    }
    

    In the module

    public class BookingModule extends AbstractModule {
    
        @Override
        protected void configure() {               
            // Raw actor class, meant to be used by GuiceActorProducer.
            // Do not use this directly
            bind(Actor.class).annotatedWith(
                    Names.named(BookingActor.ACTOR_BEAN_NAME)).to(
                    BookingActor.class);
        }
    
        @Singleton
        @Provides
        @Named(BookingActor.ACTOR_ROUTER_BEAN_NAME)
        ActorRef systemActorRouter(Injector injector, ActorSystem actorSystem) {
          Props props = Props.create(GuiceActorProducer.class, injector, BookingActor.ACTOR_BEAN_NAME, actorClass);
          actorSystem.actorOf(props.withRouter(new RoundRobinPool(DEFAULT_ROUTER_SIZE)), BookingActor.ACTOR_ROUTER_BEAN_NAME);
        }
    }
    

提交回复
热议问题