结合喷涂路线+演员模式匹配

时间:2015-06-17 20:23:54

标签: scala akka spray akka-cluster

在Akka Cluster文档之后,我运行了Worker Dial-in示例。

http://doc.akka.io/docs/akka/snapshot/java/cluster-usage.html

所以我试图将其与喷雾路线整合在一起。

我的想法是在幕后拥有一个群集,并通过http休息,调用该服务。

所以我有以下代码。

object Boot extends App {

  val port = if (args.isEmpty) "0" else args(0)
  val config =
    ConfigFactory
      .parseString(s"akka.remote.netty.tcp.port=$port")
      .withFallback(ConfigFactory.parseString("akka.cluster.roles = [frontend]"))
      .withFallback(ConfigFactory.load())

  val system = ActorSystem("ClusterSystem", config)
  val frontend = system.actorOf(Props[TransformationFrontend], name = "frontend")
  implicit val actSystem = ActorSystem()

  IO(Http) ! Http.Bind(frontend, interface = config.getString("http.interface"), port = config.getInt("http.port"))
}

class TransformationFrontend extends Actor {

  var backends = IndexedSeq.empty[ActorRef]
  var jobCounter = 0
  implicit val timeout = Timeout(5 seconds)

  override def receive: Receive = {

    case _: Http.Connected => sender ! Http.Register(self)

    case HttpRequest(GET, Uri.Path("/job"), _, _, _) =>

      jobCounter += 1
      val backend = backends(jobCounter % backends.size)

      val originalSender = sender()

      val future : Future[TransformationResult] = (backend ? new TransformationJob(jobCounter + "-job")).mapTo[TransformationResult]
      future onComplete {
        case Success(s) =>
          println("received from backend: " + s.text)
          originalSender ! s.text
        case Failure(f) => println("error found: " + f.getMessage)
      }

    case job: TransformationJob if backends.isEmpty =>
      sender() ! JobFailed("Service unavailable, try again later", job)

    case job: TransformationJob =>
      jobCounter += 1
      backends(jobCounter % backends.size) forward job

    case BackendRegistration if !backends.contains(sender()) =>
      println("backend registered")
      context watch sender()
      backends = backends :+ sender()

    case Terminated(a) =>
      backends = backends.filterNot(_ == a)
  }
}

但我真正想做的是将喷雾路线与那些模式匹配相结合。

不像上面那样写我的GET,我想这样写:

path("job") {
  get {
    respondWithMediaType(`application/json`) {
      complete {
        (backend ? new TransformationJob(jobCounter + "-job")).mapTo[TransformationResult]
      }
    }
  }
}

但是用这个类来扩展我的Actor,我必须做以下的

def receive = runRoute(defaultRoute)

如何将此方法与TransformationFrontend Actor模式匹配方法相结合? BackendRegistration,Terminated,TransformationJob?

1 个答案:

答案 0 :(得分:3)

您可以使用PartialFunction撰写Receive PartialFunction.orElse

class TransformationFrontend extends Actor {
  // ...
  def myReceive: Receive = {
    case job: TransformationJob => // ...
    // ...
  }
  def defaultRoute: Route =
    get {
      // ...
    }
  override def receive: Receive = runRoute(defaultRoute) orElse myReceive
}

也就是说,如果可能的话,将功能分成几个参与者(如上面的评论所示)通常是有意义的。