如何回应演员电话的结果?

时间:2015-06-19 04:45:29

标签: java akka-stream akka-http

我们正在考虑使用Akka-HTTP Java API - 使用路由DSL。

目前尚不清楚如何使用路由功能来响应HttpRequest;使用Untyped Akka Actor。 例如,在匹配Route路径时,我们如何将请求移交给“handler”ActorRef,然后它将以异步方式响应HttpResponse?

类似的问题发布在Akka-User邮件列表中,但没有后续解决方案 - https://groups.google.com/d/msg/akka-user/qHe3Ko7EVvg/KC-aKz_o5aoJ

2 个答案:

答案 0 :(得分:5)

这可以通过onComplete指令和ask模式的组合来实现。

在下面的示例中,RequestHandlerActor actor用于根据HttpResponse创建HttpRequest。这个演员是在路线内被问到的。

我从未使用过Java来路由代码,因此我的回复是在Scala中。

import scala.concurrent.duration._
import akka.actor.ActorSystem
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.HttpRequest
import akka.actor.Actor
import akka.http.scaladsl.server.Directives._
import akka.actor.Props
import akka.pattern.ask
import akka.util.Timeout
import scala.util.{Success, Failure}
import akka.http.scaladsl.model.StatusCodes.InternalServerError

class RequestHandlerActor extends Actor {
  override def receive = {
    case httpRequest : HttpRequest =>
      sender() ! HttpResponse(entity = "actor responds nicely")
  }
}

implicit val actorSystem = ActorSystem()
implicit val timeout = Timeout(5 seconds)

val requestRef = actorSystem actorOf Props[RequestHandlerActor]

val route = 
  extractRequest { request =>
    onComplete((requestRef ? request).mapTo[HttpResponse]) {
      case Success(response) => complete(response)
      case Failure(ex) => 
        complete((InternalServerError, s"Actor not playing nice: ${ex.getMessage}"))
    } 
  }

然后可以像使用任何其他Flow一样将此路由传递到bindAndHandle方法。

答案 1 :(得分:1)

我一直在寻找问题作者描述的同一问题的解决方案。最后,我提出了以下用于创建路由的Java代码:

    ActorRef ref = system.actorOf(Props.create(RequestHandlerActor.class));

    return get(() -> route(
            pathSingleSlash(() ->
                    extractRequest(httpRequest -> {
                        Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS));
                        CompletionStage<HttpResponse> completionStage = PatternsCS.ask(ref, httpRequest, timeout)
                                .thenApplyAsync(HttpResponse.class::cast);

                        return completeWithFuture(completionStage);
                    })
            ))
    );

RequestHandlerActor是:

public class RequestHandlerActor extends UntypedActor {
    @Override
    public void onReceive(Object msg) {
        if (msg instanceof HttpRequest) {
            HttpResponse httpResponse = HttpResponse.create()
                    .withEntity(ContentTypes.TEXT_HTML_UTF8,
                            "<html><body>Hello world!</body></html>");

            getSender().tell(httpResponse, getSelf());
        } else {
            unhandled(msg);
        }
    }
}