现代Akka DI与Guice

时间:2015-06-16 09:39:20

标签: java akka guice

Java 8,Guice 4.0和Akka 2.3.9。我试图弄清楚如何使用JSR330样式的@Inject注释来注释我的actor类,然后通过Guice将它们连接起来。

但实际上我读过的每篇文章(下面都有一些例子)要么使用Scala代码示例,要么使用犯罪版本的Guice,要么使用犯罪版本的Akka:

因此,给出以下Guice模块:

public interface MyService {
    void doSomething();
}

public class MyServiceImpl implements MyService {
    @Override
    public void doSomething() {
        System.out.println("Something has been done!");
    }
}

public class MyActorSystemModule extends AbstractModule {
    @Override
    public void configure() {
        bind(MyService.class).to(MyServiceImpl.class);
    }
}

并且FizzActor注入了MyService

public class FizzActor extends UntypedActor {
    private final MyService myService;

    @Inject
    public FizzActor(MyService myService) {
        super();

        this.myService = myService;
    }

    @Override
    public void onReceive(Object message) {
        // .. Do fizz stuff inside here.
    }
}

然后我问:如何安装MyActorSystemModule来创建FizzActor的实例并使用Java正确地注入 >斯卡拉!)?

请注意:FizzActor不是演员系统中唯一的演员!

6 个答案:

答案 0 :(得分:7)

使用Creator在guice模块的提供程序方法中创建ActorRef。要区分不同类型的不同ActorRef s,请在提供者方法和注入点上使用注释,就像使用任何guice系统一样。例如,

在你的guice模块中:

@Override
protected void configure() {
    bind(ActorSystem.class).toInstance(ActorSystem.apply());
    bind(FizzService.class).toInstance(new FizzServiceImpl());
}

@Provides @Singleton @Named("fizzActor")
ActorRef serviceActorRef(final ActorSystem system, final FizzService fizzService) {
    return system.actorOf(Props.create(new Creator<Actor>() {
        @Override
        public Actor create() throws Exception {
            return new FizzActor(fizzService);
        }
    }));
}

然后使用actor服务,注入特定的ActorRef

class ClientOfFizzActor {
    @Inject
    ClientOfFizzActor(@Named("fizzActor") ActorRef fizzActorRef) {..}
}

如果Props.create(..)子句是actor类中的静态工厂方法,它看起来更干净。

答案 1 :(得分:3)

除非您尝试将UntypedActor绑定到FizzActor,否则您可以按原样将其注入其他类:

class SomeOtherClass {

    @Inject 
    public SomeOtherClass(FizzActor fizzActor) {
        //do stuff
    }
}

如果您尝试将其绑定到界面,则需要在模块中专门执行此操作:

public class MyActorSystemModule extends AbstractModule {
    @Override
    public void configure() {
        bind(MyService.class).to(MyServiceImpl.class);
        bind(UntypedActor.class).to(FizzActor.class);
    }
}

编辑:

如何使用@Named区分UntypedActor,例如:

class SomeOtherClass {

    @Inject 
    public SomeOtherClass(@Named("fizzActor")UntypedActor fizzActor, @Named("fooActor") UntypedActor fooActor) {
        //do stuff
    }
}

然后在你的模块中你可以进行akka查找:

public class MyActorSystemModule extends AbstractModule {

    ActorSystem system = ActorSystem.create("MySystem");

    @Override
    public void configure() {
        bind(MyService.class).to(MyServiceImpl.class);
    }

    @Provides
    @Named("fizzActor")
    public UntypedActor getFizzActor() {
        return system.actorOf(Props.create(FizzActor.class), "fizzActor");
    }

    @Provides
    @Named("fooActor")
    public UntypedActor getFooActor() {
        return system.actorOf(Props.create(FooActor.class), "fooActor");
    }
}

答案 2 :(得分:2)

使用akka Creator

public class GuiceCreator<T> implements Creator<T> {
 Class<T> clz;
 Module module;
 /*Constructor*/

 public T create() {
    Injector injector = Guice.createInjector(this.module);
    return injector.getInstance(this.clz);
  }
}

然后将Props.create与闪亮的基于guice的创作者一起使用。

免责声明:我实际上并不了解Akka,提到的信息来自浏览文档和JavaDoc。

答案 3 :(得分:0)

如果有人发现了这个问题,你需要使用IndirectActorProducer,我参考了Spring的例子并将其改为使用Guice。

/**
 * An actor producer that lets Guice create the Actor instances.
 */
public class GuiceActorProducer implements IndirectActorProducer {
    final String actorBeanName;
    final Injector injector;
    final Class<? extends Actor> actorClass;

    public GuiceActorProducer(Injector injector, String actorBeanName, Class<? extends Actor> 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<? extends Actor> actorClass() {
        return actorClass;
    }
}

在模块中

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);
    }
}

答案 4 :(得分:0)

所以我最近一直在玩Akka和Guice很多,我觉得那两个人在一起玩的不太好。

我建议你采取与Play相似的方法。

Kutschkem的答案最接近于此。

  1. 使用ActorCreator界面
  2. 确保您有一个无争议的Creator。请勿尝试在@AssisstedInject中执行Creator,因为这意味着您需要为每个要创建的Actor创建一个新的创建者。我个人认为,通过消息传递可以更好地在演员中初始化。
  3. 让ActorCreator使用一个注入器,以便您可以在Creator中轻松创建Actor对象。
  4. 这是使用当前Akka 2.5的代码示例。这是我们为Akka 2.5部署选择的首选设置。为简洁起见,我没有提供该模块,但从成员注入的方式,您想提供的内容中可以清楚地看出。

    代码:

     class ActorCreator implements Creator<MyActor>
       @Inject
       Injector injector;
       public MyActor create() {
         return injector.getInstance(MyActor.class);
       }
     }
    
     class MyActor extends AbstractActor {
       @Inject
       SomeController object;
    
       @Nullable
       MyDataObject data;
    
       public ReceiveBuilder createReceiveBuilder() {
        return receiveBuilder()
          .match(MyDataObject.class, m -> { /* doInitialize() */ })
          .build(); 
       }
    }
    
    class MyParentActor extends AbstractActor {
       @Inject
       ActorCreator creator;
    
       void createChild() {
         getContext().actorOf(new Props(creator));
       }
    
       void initializeChild(ActorRef child, MyDataObject obj) {
         child.tell(obj);
       }
    }
    

答案 5 :(得分:0)

通用Akka Guice集成,不依赖于Play, 请记住,不是唯一的参与者应该在参与者系统中创建。

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 <T extends Actor> void bindActor(Class<T> actorClass, String name) {
        bind(actorClass);

        Provider<ActorSystem> actorSystemProvider = getProvider(ActorSystem.class);
        Provider<T> actorProvider = getProvider(actorClass);

        bind(ActorRef.class)
                .annotatedWith(Names.named(name))
                .toProvider(ActorRefProvider.of(actorSystemProvider, actorProvider, name))
                .asEagerSingleton();
    }

}

通用ActorRefProvider为每个Actor创建ActorRef

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<T extends Actor> implements Provider<ActorRef> {

    private Provider<ActorSystem> actorSystemProvider;
    private Provider<T> actorProvider;
    private String name;

    public final class ActorCreator implements Creator<Actor> {
        @Override
        public Actor create() {
            return actorProvider.get();
        }
    }

    @Override
    public ActorRef get() {
        return actorSystemProvider.get().actorOf(Props.create(new ActorCreator()), name);
    }

}

用法示例

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");
    }

}