负载均衡 akka-http

Load Balancing akka-http


我正在使用 akka-http,我的 build.sbt 配置是:

scalaVersion := "2.11.7"
libraryDependencies += "com.typesafe.akka" % "akka-actor_2.11" % "2.4.2"
libraryDependencies += "com.typesafe.akka" % "akka-http-experimental_2.11" % "2.4.2"
libraryDependencies += "com.typesafe.akka" % "akka-http-spray-json-experimental_2.11" % "2.4.2"
libraryDependencies += "com.typesafe.akka" % "akka-slf4j_2.11" % "2.4.2"

我公开了一个简单的 REST api 只有一个 GET url
foo 是一个 returns 一个 Future

的函数
implicit val actorSystem = ActorSystem("system", config)
implicit val actorMaterializer = ActorMaterializer()

val route: Route = {
  get {
    path("foo") {
      complete { foo }
    }
  }
}

网络服务预计会有很多调用,我想在失败的情况下使服务冗余,所以我想要两个实例运行 同时处理所有请求。

1) 让 Web 服务的两个实例同时处理请求的最佳方法是什么?使用外部负载平衡器或内部使用一些魔法(我不知道) akka/akka-http ?

2) 我必须调整哪些主要参数以提高性能?

的答案演示了如何从 Route.

中进行 Actor 调用

如果您将该技术与 Akka 中的 clustering 功能相结合,您应该能够完成这项工作。

让您的路由向 Router that will dispatch the message to 1 of N remotely deployed Actors (from your question it sounds like a round robin 路由器发送消息是您想要的)。

class HttpResponseActor extends Actor {

  def foo : HttpResponse = ??? // Not specified in question

  override def receive = {
    case _ : HttpRequest => foo 
  }
}

import akka.actor.{ Address, AddressFromURIString }
import akka.remote.routing.RemoteRouterConfig

val addresses = Seq(Address("akka.tcp", "remotesys", "otherhost", 1234),
                    AddressFromURIString("akka.tcp://othersys@anotherhost:1234"))

val routerRemote = 
  system.actorOf(RemoteRouterConfig(RoundRobinPool(5), addresses).props(Props[HttpResponseActor]))

远程 Actor 使用 HttpResponse 进行响应。此响应可以 go through the Router or directly back to the Route.

路由将 complete 指令中的答案粘贴到 return 返回给客户端。

val route = 
  get {
    path("foo") {
      onComplete((routerRemote ? request).mapTo[HttpResponse]) {
        case Success(response) => complete(response)
        case Failure(ex) => complete((InternalServerError, s"Actor not playing nice: ${ex.getMessage}"))
      }
    }
  }