如何响应演员呼吁的结果? [英] How to respond with the result of an actor call?

查看:78
本文介绍了如何响应演员呼吁的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We are looking at using Akka-HTTP Java API - using Routing DSL.

目前尚不清楚如何使用路由功能来响应HttpRequest;使用无类型Akka演员。
例如,匹配路由路径后,我们如何将请求传递给处理程序 ActorRef,该处理程序随后将以异步方式通过HttpResponse进行响应?

It's not clear how to use the Routing functionality to respond to an HttpRequest; using an Untyped Akka Actor. For example, upon matching a Route path, how do we hand off the request to a "handler" ActorRef, which will then respond with a HttpResponse in a asynchronous way?

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

A similar question was posted on Akka-User mailing list, but with no followup solutions as such - https://groups.google.com/d/msg/akka-user/qHe3Ko7EVvg/KC-aKz_o5aoJ.

推荐答案

这可以通过 onComplete 指令和询问模式。

在下面的示例中, RequestHandlerActor actor用于基于 HttpReq创建 HttpResponse 西方

In the below example the RequestHandlerActor actor is used to create a HttpResponse based on the HttpRequest. This Actor is asked from within the route.

我从来没有使用Java来路由代码,所以我的回答是在Scala中。

I have never used Java for routing code so my response is in 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}"))
    } 
  }

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

This route can then be used passed into the bindAndHandle method like any other Flow.

这篇关于如何响应演员呼吁的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆