Skip to content

Instantly share code, notes, and snippets.

@EdgeCaseBerg
Created May 12, 2015 20:42
Show Gist options
  • Select an option

  • Save EdgeCaseBerg/4e71acb59a11d6ab1464 to your computer and use it in GitHub Desktop.

Select an option

Save EdgeCaseBerg/4e71acb59a11d6ab1464 to your computer and use it in GitHub Desktop.
Example for multi controller routing in Akka Spray
import akka.io.IO
import akka.actor._
import akka.pattern.ask
import akka.util.Timeout
import spray.http._
import spray.can.Http
import spray.routing._
import spray.routing.RequestContext
import spray.routing.directives.CachingDirectives._
import scala.concurrent.duration._
import MediaTypes._
object DummyActor {
case class Process(s: String)
}
class DummyActor(requestContext: RequestContext) extends Actor {
def receive = {
case DummyActor.Process(s) =>
requestContext.complete(s)
context.stop(self)
}
}
trait Beef extends HttpService {
val beefRoutes =
pathPrefix("beef") {
path("cows"){
pathEnd {
respondWithMediaType(`text/plain`) {
requestContext => {
val dummyService = actorRefFactory.actorOf(Props(new DummyActor(requestContext)))
dummyService ! DummyActor.Process("cows")
}
}
}
} ~
path("bulls") {
respondWithMediaType(`text/plain`) {
requestContext => {
val dummyService = actorRefFactory.actorOf(Props(new DummyActor(requestContext)))
dummyService ! DummyActor.Process("bulls")
}
}
}
}
}
trait Nog extends HttpService {
val nogRoutes =
pathPrefix("nog") {
path("egg") {
respondWithMediaType(`text/plain`) {
requestContext => {
val dummyService = actorRefFactory.actorOf(Props(new DummyActor(requestContext)))
dummyService ! DummyActor.Process("eggnog!")
}
}
}
}
}
trait RouteService extends HttpService
with Beef
with Nog
{
val route = {
beefRoutes ~
nogRoutes
}
}
class HttpApp extends Actor with RouteService {
override val actorRefFactory: ActorRefFactory = context
def receive = runRoute(route)
}
object HttpApp extends App {
runserver(host= "localhost", port = 8089)
def runserver(host: String, port: Int) {
implicit lazy val system = ActorSystem("HttpSystem")
sys.addShutdownHook(system.shutdown())
val httpActor = system.actorOf(Props[HttpApp], name = "httpActor")
implicit val timeout = Timeout(5.seconds)
IO(Http) ? Http.Bind(httpActor, interface = host, port = port)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment