Skip to content

Instantly share code, notes, and snippets.

@zergood
Created May 27, 2015 11:11
Show Gist options
  • Save zergood/e705cd6ce4cfec47c0a5 to your computer and use it in GitHub Desktop.
Save zergood/e705cd6ce4cfec47c0a5 to your computer and use it in GitHub Desktop.
Quick and dirty load balancer
trait Frontend {
this: Core =>
def config: Config
val log = LoggerFactory.getLogger(getClass)
def route(flow:Flow[HttpRequest, Future[HttpResponse], Unit]): Route = {
path("dictionaries" / Segment / "suggestions"){ dictionaryId =>
get{
parameters("ngr"){ ngr =>
ctx =>
Source.single(ctx.request)
.via(flow)
.runWith(Sink.head)
.flatMap(r => ctx.complete(r))
}
}
}
}
def start() = {
val flow = Flow() { implicit b =>
import akka.stream.scaladsl.FlowGraph.Implicits._
val balance = b.add(Balance[HttpRequest](2))
val merge = b.add(Merge[Future[HttpResponse]](2))
val proxyTo51 = Flow[HttpRequest].map(_ =>
Http().singleRequest(HttpRequest(uri = Uri("http://localhost:4051/dictionaries/hello/suggestions?ngr=hond")))
)
val proxyTo52 = Flow[HttpRequest].map(_ =>
Http().singleRequest(HttpRequest(uri = Uri("http://localhost:4052/dictionaries/hello/suggestions?ngr=hond")))
)
balance ~> proxyTo51 ~> merge
balance ~> proxyTo52 ~> merge
(balance.in, merge.out)
}
Http().bind(
interface = config.getString("frontend.interface"),
port = config.getInt("frontend.port")
).to(Sink.foreach { conn =>
log.info(s"Connection from ${conn.remoteAddress}")
conn.flow.join(route(flow)).run()
}).run()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment