Как использовать актера для получения http-запросов и запросов от других акторов?

Я хочу, чтобы класс TestHttp мог получать 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
}

person tomite    schedule 27.01.2015    source источник


Ответы (1)


Actor.Receive — это частичная функция, которая принимает значение Any и возвращает Unit (PartialFunction[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)
}
person abatyuk    schedule 27.01.2015