Alternating between Spray-servlet and Spray-can
On a server you may want to deploy your application as a war. How to build a war with spray-servlet Locally it's easiest to run without an application server. We include both the spray-servlet and spray-can dependencies:
name := "sprayApiExample"
version := "1.0"
scalaVersion := "2.11.6"
libraryDependencies ++= {
val akkaV = "2.3.9"
val sprayV = "1.3.3"
Seq(
"io.spray" %% "spray-can" % sprayV,
"io.spray" %% "spray-servlet" % sprayV,
"io.spray" %% "spray-routing" % sprayV,
"io.spray" %% "spray-json" % "1.3.1", //has not been updated yet
"com.typesafe.akka" %% "akka-actor" % akkaV
)
}
//This adds tomcat dependencies, you can also use jetty()
tomcat()
We make a trait with all the common functionality. We extend both SprayApiServlet and SprayApiCan from it.
import akka.actor.{ActorSystem, Props}
import akka.io.IO
import akka.pattern.ask
import akka.util.Timeout
import spray.can.Http
import spray.servlet.WebBoot
import scala.concurrent.duration._
trait SprayApi {
implicit val system = ActorSystem("SprayApiApp")
val apiActor = system.actorOf(Props[ApiActor], "apiActor")
}
//for use with spray-servlet
class SprayApiServlet extends WebBoot with SprayApi {
override val serviceActor = apiActor
}
//for use with spray-can
object SprayApiCan extends App with SprayApi {
implicit val timeout = Timeout(5.seconds)
IO(Http) ? Http.Bind(apiActor, interface = "localhost", port = 8080)
}
You can see the whole example here.