如何使用actor接收来自其他actor的http请求和请求?

时间:2015-01-27 14:49:24

标签: scala akka spray

我希望TestHttp类能够接收来自其他actor的http请求或消息。我该怎么办?

代码:

object Main extends App with SimpleRoutingApp {
  implicit val system = ActorSystem("system")
  import system.dispatcher
  implicit val timeout = Timeout(240.seconds)

  startServer(interface = "localhost", port = 3000) {
    get {
      path("register" / IntNumber) { n =>
        respondWithMediaType(MediaTypes.`application/json`) { ctx =>
          val future = IO(Http) ? Bind(system.actorOf(Props[TestHttp]), interface = "localhost", port = 3000 + n)
          future onSuccess {
            case Http.Bound(msg) => ctx.complete(s"Ok:"+msg)
            case _ => ctx.complete("...")
          }
        }
      } // : Route == RequestContext => Unit
    } // : Route
  }
}

trait TestHttpService extends HttpService {
  val oneRoute = {
        path("test") {
          complete("test")
        }
  }
}

class TestHttp extends Actor with TestHttpService {
  def actorRefFactory = context
  val sealedRoute = sealRoute(oneRoute) 
    def receive = {
      // case HttpRequest(GET, Uri.Path("/ping"), _, _, _) => //not working
      //   sender ! HttpResponse(entity = "PONG")
      case ctx: RequestContext => sealedRoute(ctx) //not working

    } 
  // def receive = runRoute(oneRoute) //it works
}

1 个答案:

答案 0 :(得分:4)

Actor.Receive是一个部分函数,​​它接受Any值并返回UnitPartialFunction[Any, Unit]),因此您可以通过常规PF合成来完成。

HttpService.runRoute返回Actor.Receive(请参阅https://github.com/spray/spray/blob/master/spray-routing/src/main/scala/spray/routing/HttpService.scala#L31

所以,你的解决方案是:

class TestHttp extends Actor with TestHttpService {
  def actorRefFactory = context
  val sealedRoute = sealRoute(oneRoute) 
    def receive = {
        case s: String => println(s"Just got string $s")
    } orElse runRoute(oneRoute)
}