How to properly call a single server from multiple actors / web handlers using Akka HTTP?

此生再无相见时 提交于 2019-12-03 13:37:07

I think you could use Source.queue to buffer your requests. The code below assume that you need to get the answer from 3rd party service, so having a Future[HttpResponse] is very welcomed. This way you could also provide an overflow strategy to prevent resource starvation.

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.stream.scaladsl.{Keep, Sink, Source}
import akka.stream.{ActorMaterializer, OverflowStrategy}

import scala.concurrent.duration._
import scala.concurrent.{Await, Future, Promise}
import scala.util.{Failure, Success}

import scala.concurrent.ExecutionContext.Implicits.global

implicit val system = ActorSystem("main")
implicit val materializer = ActorMaterializer()
val pool = Http().cachedHostConnectionPool[Promise[HttpResponse]](host = "google.com", port = 80)
val queue = Source.queue[(HttpRequest, Promise[HttpResponse])](10, OverflowStrategy.dropNew)
  .via(pool)
  .toMat(Sink.foreach({
    case ((Success(resp), p)) => p.success(resp)
    case ((Failure(e), p)) => p.failure(e)
  }))(Keep.left)
  .run
val promise = Promise[HttpResponse]
val request = HttpRequest(uri = "/") -> promise

val response = queue.offer(request).flatMap(buffered => {
  if (buffered) promise.future
  else Future.failed(new RuntimeException())
})

Await.ready(response, 3 seconds)

(code copied from my blog post)

Here is Java version of the accepted answer

final Flow<
    Pair<HttpRequest, Promise<HttpResponse>>,
    Pair<Try<HttpResponse>, Promise<HttpResponse>>,
    NotUsed> flow =
    Http.get(actorSystem).superPool(materializer);

final SourceQueue<Pair<HttpRequest, Promise<HttpResponse>>> queue = Source.<Pair<HttpRequest, Promise<HttpResponse>>>
    queue(BUFFER_SIZE, OverflowStrategy.dropNew())
    .via(flow)
        .toMat(Sink.foreach(p -> p.second().complete(p.first())), Keep.left())
        .run(materializer);

...

public CompletionStage<HttpResponse> request(HttpRequest request) {
    log.debug("Making request {}", request);

    Promise<HttpResponse> promise = Futures.promise();
    return queue.offer(Pair.create(request, promise))
        .thenCompose(buffered -> {
            if (buffered instanceof QueueOfferResult.Enqueued$) {
                return FutureConverters.toJava(promise.future())
                    .thenApply(resp -> {
                        if (log.isDebugEnabled()) {
                            log.debug("Got response {} {}", resp.status(), resp.getHeaders());
                        }
                        return resp;
                    });
            } else {
                log.error("Could not buffer request {}", request);
                return CompletableFuture.completedFuture(HttpResponse.create().withStatus(StatusCodes.SERVICE_UNAVAILABLE));
            }
        });
}

All you need to do is setup a HostConnectionPool to Service B within your Service A code. This will give you a Flow that can be added to your Service A streams to dispatch requests from A to B using a connection pool instead of a new connection per stream. From the documentation:

As opposed to the Connection-Level Client-Side API the host-level API relieves you from manually managing individual HTTP connections. It autonomously manages a configurable pool of connections to one particular target endpoint (i.e. host/port combination).

Each materialization of this Flow, in different streams, will draw from this underlying pool of connections:

The best way to get a hold of a connection pool to a given target endpoint is the Http.get(system).cachedHostConnectionPool(...) method, which returns a Flow that can be "baked" into an application-level stream setup. This flow is also called a "pool client flow".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!