2016-06-14 68 views
0

我已經通過play-akka配置文件爲數據庫操作分配了一個專用線程池。現在我正在將需要此線程池的服務注入到actor系統並訪問執行上下文。如何將自定義執行程序注入到應用程序中?

public class ServiceA{ 

    final Executor executionContext; 

    @Inject 
    public ServiceA(ActorSystem system) { 
     this.executionContext = system.dispatchers().lookup("akka.actor.db-context"); 
} 

但是這使得很難測試ServiceA。我想要做的只是直接像這樣注入Executor:

public class ServiceA{ 

    final Executor executionContext; 

    @Inject 
    public ServiceA(Executor dbExecutionCtx) { 
     this.executionContext = dbExecutionCtx; 
} 

我該如何做到這一點?我已經嘗試創建一個guice模塊來注入Executor,但它錯誤地抱怨沒有啓動的應用程序,並且在它執行綁定類時沒有訪問ActorSystem。

回答

1

我使用一種模式,我可以在任何地方獲得EC。我在Singleton中創建了一個ActorSystem,並將它注入到我的服務中。

我有一個設計與ActorSystems,調度員和更多的監測。看看這個,看看你是否可以整合它。

因此,如果MyActorSystem注入您的課程,您可以從中訪問EC。看看MyDispatcher和使用EC的:

@Singleton 
public class MyActorSystem implements IMyActorSystem{ 

    ActorSystem system; 
    public MyActorSystem() { 
     system = ActorSystem.create(); 

    } 

    public ActorRef create() { 
     final ActorRef actor = system.actorOf(
       Props.create(MyWorker.class).withDispatcher("my-disp") 
     ); 
     return actor; 
    } 

    public void shutdown(){ 
     system.shutdown(); 
    } 

    public ExecutionContextExecutor getDispatcher(){ 
     return system.dispatcher(); 
    } 
    } 

    public class MyDispatcher implements IMyDispatcher { 

    MyActorSystem system; 

    @Inject public MyDispatcher(MyActorSystem system) { 
     this.system = system; 
    } 


    public CompletableFuture<Object> dispatch(final Object story) { 
     List<CompletableFuture<Object>> futureList = new ArrayList<>(); 
     final ActorRef actor = system.create(); 
     final CompletableFuture<Object> completed = FutureConverter 
       .fromScalaFuture(Patterns.ask(actor, story, 50000)).executeOn(system.getDispatcher()) 
       .thenApply(i -> (Object) i); 
     return completed; 
    } 

    public ExecutionContextExecutor getDispatcher(){ 
     return system.getDispatcher(); 
    } 
} 
+0

這是什麼樣的我落得這樣做了。現在你必須調用getDispatcher()這樣的方法,但它是一個改進的解決方案。我試圖探索是否有其他方法直接注入執行程序,而無需任何其他方法調用。 – jesukumar

相關問題