12

我很困惑如何使用蛋糕模式确保我的演员具有适当的依赖关系。我仍然在处理这个问题,我在任何地方都找不到任何例子。我基本上只是在寻找要遵循的教程/资源。

干杯,克里斯。

4

2 回答 2

10

Actors as dependency:

trait DBComponent {
   def db: ActorRef // no compile time guarantees

   type K
   type V

   object DBActor {
      case class Put(key: K, value: V)
      case class Get(key: K)
   }

   class DBActor {
      import DBActor._
      val db = scala.collection.mutable.Map.empty[K, V]
      def receive = {
         case Put(k, v) => db.put(k, v)
         case Get(k) => sender ! db.get(k)
      }
   }
}

trait ServiceComponent {
   this: DBComponent =>

   import DBActor._

   // you could be talking to deadLetters for all you know
   def put(k: K, v: V): Unit = db ! Put(k, v)
   def get(k: K): Option[V] = {
      implicit val timeout = Timeout(5 seconds)
      val future = ask(actor, Get(k)).mapTo[Option[V]]
      Await.result(future, timeout.duration)
   }
}

Actors having dependencies (where there is nothing special to it):

trait DBComponent {
   def db: DB

   type K
   type V

   trait DB {
      def put(key: K, value: V): Unit
      def get(key: K): Option[V]
   }
}

trait ServiceComponent {
   this: DBComponent =>

   object ServiceActor {
      case class Put(key: K, value: V)
      case class Get(key: K)
   }

   class ServiceActor {
      import ServiceActor._
      def receive = {
         case Put(k, v) => db.put(k, v) // db is in scope
         case Get(k) => sender ! db.get(k)
      }
   }
}
于 2013-04-14T16:40:15.500 回答
2

正如 Owen 所指出的,另外一个问题是使用创建actoractorOf(Props[MyClass])不适用于内部类。即:以下将失败:

trait MyComponent {
  class MyActor {
    def receive = ...
  }
}

new MyComponent {
  val myActorRef = system.actorOf( Props[MyActor] )
}

根据http://doc.akka.io/docs/akka/snapshot/scala/actors.html的文档,

如果它们没有在顶级对象中声明,则需要将封闭实例的 this 引用作为第一个参数传递

但是,scaladoc Props 方法签名似乎不支持这一点。我发现解决这个问题的唯一方法是使用 Props(actor: Actor) 构造函数,实例化 actor mysql 并将其传递给 Props。

val myActorRef = system.actorOf( Props( new MyActor(arg1, arg2) ) )

有兴趣知道是否有更好的方法..

于 2013-09-22T18:15:24.477 回答