/ / ActorSystem内のSprayクライアントを使用したルーティングの実装-scala、routing、akka、actor、spray

ActorSystem内のスプレークライアントによるルーティングの実装 - scala、routing、akka、actor、spray

REST Webサービスを呼び出すために使用されるSprayクライアントがあります。現在、このクライアントのインスタンスを作成しています( new GeoSprayWebClient)[以下のコードを参照]およびmyRESTリクエストを行うアクター。ただし、サービスの単一インスタンスはすべての負荷を処理することはできません。したがって、RESTサービスのレプリカを紹介したいと思います。

私は「スプレーの初心者であり、まだ基礎を学ぼうとしています。私の質問は

1)Sprayは内部でAkkaアクターを使用していることを知っています。この特定のケースでは、 ActorRef クライアントインスタンスの場合複数のクライアントActorRefを作成し、それらを使用してAkkaルーターを作成します。 2)SprayクライアントAPIは、ユースケースをサポートするルーティング機能を提供しますか?

 import akka.actor.ActorSystem
import spray.client.pipelining._
import spray.http._
import scala.concurrent.Future


trait GeoWebClient {
def get(url: String, params: Map[String, String]): Future[String]
}

class GeoSprayWebClient(implicit system: ActorSystem) extends GeoWebClient {

import system.dispatcher

// create a function from HttpRequest to a Future of HttpResponse
val pipeline: HttpRequest => Future[HttpResponse] = sendReceive

// create a function to send a GET request and receive a string response
def get(path: String, params: Map[String, String]): Future[String] = {
val uri = Uri(path) withQuery params
val request = Get(uri)
val futureResponse = pipeline(request)
futureResponse.map(_.entity.asString)
}
}

回答:

回答№1は0
  1. GeoSprayWebClientを呼び出して作業を行うWebClientActorを実装します。

  2. スプレーハンドラーとしてルーターを作成します。

val handler = context.actorOf( Props [WebClientActor] .withRouter(RoundRobinRouter(5))、name = "handlerRouter")

  1. 要求メッセージをハンドラーに送信します

このようにして、リクエストを行う5つのクライアントインスタンスがあります。

私も「スプレーするのは初めてです。確かではありません」はあなたの目的のためかどうかです。ご参考まで。

乾杯〜!


回答№2の場合は0

に基づく この 私は得ることができました ActorRef

def createHttpRESTClient(host: String, port: Int): ActorRef = {

// execution context for future transformations below
import system.dispatcher
implicit val timeout: Timeout = 10 seconds

val ref: Future[ActorRef] = for {
Http.HostConnectorInfo(hostConnector: ActorRef, _) <- IO(Http) ? Http.HostConnectorSetup(host, port)
}
yield {
hostConnector
}
//FIXME - TODO fix this it"s really bad. However, We are going to create this only once when we create the actor, so I guess it"s okay for now.
Await.result(ref, 10 seconds)
}

これが、ActorRefを使用してリクエストを送信し、サービスからレスポンスを取得する方法です。

  def sendReq(text: String): Future[String] = {
import spray.http._
val params = Map(("key" -> text))
val uri = Uri("/myservice") withQuery params
val request = Get(uri)
//send GET request using the "ask" pattern; the timeout
//TODO - not sure if we can use tell instead of ask here ?
val response: Future[HttpResponse] = restSvrActorRef.ask(request).mapTo[HttpResponse]
log.debug(s"done with sending a request to the REST service")
response.map(_.entity.asString)
}