2016-07-15 89 views
1

早些時候,我讀到創建根(在/ user /)actor(system.actorOf)之後很貴。工廠演員模式

是否有一個常見的模式來創建ClientFactoryActor,其主要責任是簡單地根據請求返回新的actor(例如,我們需要每個客戶端新的websocket actor等)?

+0

不要忘記殺死演員,以避免內存泄漏。 – ipoteka

回答

1

事實上,您應該嘗試爲錯誤處理目的維護角色的層次結構(不同的監督策略) 創建角色的一種便捷方式是創建一個伴隨對象,該對象返回對想要的角色實例化的引用給定的參數(單件廠)

object DemoActor { 
     /** 
     * Create Props for an actor of this type. 
     * 
     * @param magicNumber The magic number to be passed to this actor’s constructor. 
     * @return a Props for creating this actor, which can then be further configured 
     *   (e.g. calling `.withDispatcher()` on it) 
     */ 
     def props(magicNumber: Int): Props = Props(new DemoActor(magicNumber)) 
    } 

    class DemoActor(magicNumber: Int) extends Actor { 
     def receive = { 
     case x: Int => sender() ! (x + magicNumber) 
     } 
    } 

    class SomeOtherActor extends Actor { 
     // Props(new DemoActor(42)) would not be safe 
     context.actorOf(DemoActor.props(42), "demo") 
     // ... 
    } 

一個很好的起點是Akka documentation頁面。