使用Akka-http时如何在另一个actor中完成请求 [英] How to complete a request in another actor when using akka-http

查看:120
本文介绍了使用Akka-http时如何在另一个actor中完成请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用akka-http 1.0,我想使用定义为

I am using akka-http 1.0 and I would like to use a route defined as

def route: Route = path("") {
  // start actor with requestContext
  // call requestContext.complete(...) in actor with the result
}

我该怎么做?

推荐答案

下面的代码详细说明@jrudolph的注释,满足您将RequestContext值分发给Actor的要求。您的问题表明,您希望每个请求都拥有一个新的Actor;但是,以下代码对所有请求使用相同的Actor,我认为这是一个更有效/更可能的用例。

Elaborating on @jrudolph's comment, the below code satisfies your requirements of dispatching RequestContext values to an Actor. Your question indicated that you wanted a new Actor for each request; however, the below code uses the same Actor for all requests which I think is a more efficient/likely use case. The Actor creation can always be moved inside handleRequest if needed.

首先,我们需要一个Actor来处理对响应的请求:

First we need an Actor for processing a request to a response:

import akka.actor.Actor
import akka.http.scaladsl.server.{RequestContext, RouteResult}
import akka.http.scaladsl.model.HttpResponse

class RequestActor extends Actor {

  //business logic - returns empty HttpResponse
  def handleRequestMessage(requestContext : RequestContext) = 
    RouteResult.Complete(new HttpResponse())

  override def receive = {
    case reqContext : RequestContext => 
      sender ! handleRequestMessage(reqContext)
  }
}//end class RequestActor

现在创建用于查询Actor的实用函数:

Now create a utility function for querying the Actor:

import akka.actor.ActorRef
import scala.concurrent.Future
import akka.pattern.ask

object RequestActor {
  val handleRequest : ActorRef => RequestContext => Future[RouteResult] =
    (actorRef) =>
      (requestContext) =>
        ask(actorRef,reqContext).mapTo[RouteResult]
}

剩下要做的就是将所有内容连接到服务中:

And all that is left to do is wire everything together into a service:

import akka.actor.{ActorSystem, Props}
import akka.stream.ActorMaterializer
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives.{get,path}
import akka.util.Timeout

object RouteActorTest extends App {
  implicit val as = ActorSystem("RouteActorTest")
  implicit val timeout = new Timeout(1000)

  val sendRequestToActor : RequestContext => Future[RouteResult] = 
    RequestActor handleRequest (as actorOf Props[RequestActor])      

  val route = path("")(get(sendRequestToActor))

  //rest of application...

}//end object RouteActorTest

这篇关于使用Akka-http时如何在另一个actor中完成请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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