如何响应actor调用的结果?

编程入门 行业动态 更新时间:2024-10-16 22:20:07
本文介绍了如何响应actor调用的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

不清楚如何使用路由功能来响应一个HttpRequest;使用无类型 Akka Actor.例如,匹配 Route 路径后,我们如何将请求传递给处理程序"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 邮件列表上发布了一个类似的问题,但没有后续解决方案 - groups.google/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 - groups.google/d/msg/akka-user/qHe3Ko7EVvg/KC-aKz_o5aoJ.

推荐答案

这可以通过 onComplete 指令和 ask 模式.

在下面的示例中,RequestHandlerActor 角色用于基于 HttpRequest 创建一个 HttpResponse.从路由内询问此 Actor.

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.

更多推荐

如何响应actor调用的结果?

本文发布于:2023-11-25 23:04:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631703.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:actor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!